aoptx86.pas 285 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. {
  42. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  43. the use of a register by allocs/dealloc, so it can ignore calls.
  44. In the following example, GetNextInstructionUsingReg will return the second movq,
  45. GetNextInstructionUsingRegTrackingUse won't.
  46. movq %rdi,%rax
  47. # Register rdi released
  48. # Register rdi allocated
  49. movq %rax,%rdi
  50. While in this example:
  51. movq %rdi,%rax
  52. call proc
  53. movq %rdi,%rax
  54. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  55. won't.
  56. }
  57. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  58. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  59. private
  60. function SkipSimpleInstructions(var hp1: tai): Boolean;
  61. protected
  62. class function IsMOVZXAcceptable: Boolean; static; inline;
  63. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  64. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  65. { checks whether reading the value in reg1 depends on the value of reg2. This
  66. is very similar to SuperRegisterEquals, except it takes into account that
  67. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  68. depend on the value in AH). }
  69. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  70. { Replaces all references to AOldReg in a memory reference to ANewReg }
  71. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  72. { Replaces all references to AOldReg in an operand to ANewReg }
  73. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  74. { Replaces all references to AOldReg in an instruction to ANewReg,
  75. except where the register is being written }
  76. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  77. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  78. or writes to a global symbol }
  79. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  80. { Returns true if the given MOV instruction can be safely converted to CMOV }
  81. class function CanBeCMOV(p : tai) : boolean; static;
  82. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  83. conversion was successful }
  84. function ConvertLEA(const p : taicpu): Boolean;
  85. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  86. procedure DebugMsg(const s : string; p : tai);inline;
  87. class function IsExitCode(p : tai) : boolean; static;
  88. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  89. procedure RemoveLastDeallocForFuncRes(p : tai);
  90. function DoSubAddOpt(var p : tai) : Boolean;
  91. function PrePeepholeOptSxx(var p : tai) : boolean;
  92. function PrePeepholeOptIMUL(var p : tai) : boolean;
  93. function OptPass1AND(var p : tai) : boolean;
  94. function OptPass1_V_MOVAP(var p : tai) : boolean;
  95. function OptPass1VOP(var p : tai) : boolean;
  96. function OptPass1MOV(var p : tai) : boolean;
  97. function OptPass1Movx(var p : tai) : boolean;
  98. function OptPass1MOVXX(var p : tai) : boolean;
  99. function OptPass1OP(var p : tai) : boolean;
  100. function OptPass1LEA(var p : tai) : boolean;
  101. function OptPass1Sub(var p : tai) : boolean;
  102. function OptPass1SHLSAL(var p : tai) : boolean;
  103. function OptPass1SETcc(var p : tai) : boolean;
  104. function OptPass1FSTP(var p : tai) : boolean;
  105. function OptPass1FLD(var p : tai) : boolean;
  106. function OptPass1Cmp(var p : tai) : boolean;
  107. function OptPass1PXor(var p : tai) : boolean;
  108. function OptPass1VPXor(var p: tai): boolean;
  109. function OptPass1Imul(var p : tai) : boolean;
  110. function OptPass2MOV(var p : tai) : boolean;
  111. function OptPass2Imul(var p : tai) : boolean;
  112. function OptPass2Jmp(var p : tai) : boolean;
  113. function OptPass2Jcc(var p : tai) : boolean;
  114. function OptPass2Lea(var p: tai): Boolean;
  115. function OptPass2SUB(var p: tai): Boolean;
  116. function PostPeepholeOptMov(var p : tai) : Boolean;
  117. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  118. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  119. function PostPeepholeOptXor(var p : tai) : Boolean;
  120. {$endif}
  121. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  122. function PostPeepholeOptCmp(var p : tai) : Boolean;
  123. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  124. function PostPeepholeOptCall(var p : tai) : Boolean;
  125. function PostPeepholeOptLea(var p : tai) : Boolean;
  126. function PostPeepholeOptPush(var p: tai): Boolean;
  127. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  128. { Processor-dependent reference optimisation }
  129. class procedure OptimizeRefs(var p: taicpu); static;
  130. end;
  131. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  132. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  133. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  134. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  135. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  136. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  137. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  138. {$if max_operands>2}
  139. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  140. {$endif max_operands>2}
  141. function RefsEqual(const r1, r2: treference): boolean;
  142. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  143. { returns true, if ref is a reference using only the registers passed as base and index
  144. and having an offset }
  145. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  146. implementation
  147. uses
  148. cutils,verbose,
  149. systems,
  150. globals,
  151. cpuinfo,
  152. procinfo,
  153. paramgr,
  154. aasmbase,
  155. aoptbase,aoptutils,
  156. symconst,symsym,
  157. cgx86,
  158. itcpugas;
  159. {$ifdef DEBUG_AOPTCPU}
  160. const
  161. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  162. {$else DEBUG_AOPTCPU}
  163. { Empty strings help the optimizer to remove string concatenations that won't
  164. ever appear to the user on release builds. [Kit] }
  165. const
  166. SPeepholeOptimization = '';
  167. {$endif DEBUG_AOPTCPU}
  168. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  169. begin
  170. result :=
  171. (instr.typ = ait_instruction) and
  172. (taicpu(instr).opcode = op) and
  173. ((opsize = []) or (taicpu(instr).opsize in opsize));
  174. end;
  175. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  176. begin
  177. result :=
  178. (instr.typ = ait_instruction) and
  179. ((taicpu(instr).opcode = op1) or
  180. (taicpu(instr).opcode = op2)
  181. ) and
  182. ((opsize = []) or (taicpu(instr).opsize in opsize));
  183. end;
  184. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  185. begin
  186. result :=
  187. (instr.typ = ait_instruction) and
  188. ((taicpu(instr).opcode = op1) or
  189. (taicpu(instr).opcode = op2) or
  190. (taicpu(instr).opcode = op3)
  191. ) and
  192. ((opsize = []) or (taicpu(instr).opsize in opsize));
  193. end;
  194. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  195. const opsize : topsizes) : boolean;
  196. var
  197. op : TAsmOp;
  198. begin
  199. result:=false;
  200. for op in ops do
  201. begin
  202. if (instr.typ = ait_instruction) and
  203. (taicpu(instr).opcode = op) and
  204. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  205. begin
  206. result:=true;
  207. exit;
  208. end;
  209. end;
  210. end;
  211. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  212. begin
  213. result := (oper.typ = top_reg) and (oper.reg = reg);
  214. end;
  215. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  216. begin
  217. result := (oper.typ = top_const) and (oper.val = a);
  218. end;
  219. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  220. begin
  221. result := oper1.typ = oper2.typ;
  222. if result then
  223. case oper1.typ of
  224. top_const:
  225. Result:=oper1.val = oper2.val;
  226. top_reg:
  227. Result:=oper1.reg = oper2.reg;
  228. top_ref:
  229. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  230. else
  231. internalerror(2013102801);
  232. end
  233. end;
  234. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  235. begin
  236. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  237. if result then
  238. case oper1.typ of
  239. top_const:
  240. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  241. top_reg:
  242. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  243. top_ref:
  244. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  245. else
  246. internalerror(2020052401);
  247. end
  248. end;
  249. function RefsEqual(const r1, r2: treference): boolean;
  250. begin
  251. RefsEqual :=
  252. (r1.offset = r2.offset) and
  253. (r1.segment = r2.segment) and (r1.base = r2.base) and
  254. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  255. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  256. (r1.relsymbol = r2.relsymbol) and
  257. (r1.volatility=[]) and
  258. (r2.volatility=[]);
  259. end;
  260. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  261. begin
  262. Result:=(ref.offset=0) and
  263. (ref.scalefactor in [0,1]) and
  264. (ref.segment=NR_NO) and
  265. (ref.symbol=nil) and
  266. (ref.relsymbol=nil) and
  267. ((base=NR_INVALID) or
  268. (ref.base=base)) and
  269. ((index=NR_INVALID) or
  270. (ref.index=index)) and
  271. (ref.volatility=[]);
  272. end;
  273. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  274. begin
  275. Result:=(ref.scalefactor in [0,1]) and
  276. (ref.segment=NR_NO) and
  277. (ref.symbol=nil) and
  278. (ref.relsymbol=nil) and
  279. ((base=NR_INVALID) or
  280. (ref.base=base)) and
  281. ((index=NR_INVALID) or
  282. (ref.index=index)) and
  283. (ref.volatility=[]);
  284. end;
  285. function InstrReadsFlags(p: tai): boolean;
  286. begin
  287. InstrReadsFlags := true;
  288. case p.typ of
  289. ait_instruction:
  290. if InsProp[taicpu(p).opcode].Ch*
  291. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  292. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  293. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  294. exit;
  295. ait_label:
  296. exit;
  297. else
  298. ;
  299. end;
  300. InstrReadsFlags := false;
  301. end;
  302. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  303. begin
  304. Next:=Current;
  305. repeat
  306. Result:=GetNextInstruction(Next,Next);
  307. until not (Result) or
  308. not(cs_opt_level3 in current_settings.optimizerswitches) or
  309. (Next.typ<>ait_instruction) or
  310. RegInInstruction(reg,Next) or
  311. is_calljmp(taicpu(Next).opcode);
  312. end;
  313. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  314. begin
  315. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  316. begin
  317. Result:=GetNextInstruction(Current,Next);
  318. exit;
  319. end;
  320. Next:=tai(Current.Next);
  321. Result:=false;
  322. while assigned(Next) do
  323. begin
  324. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  325. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  326. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  327. exit
  328. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  329. begin
  330. Result:=true;
  331. exit;
  332. end;
  333. Next:=tai(Next.Next);
  334. end;
  335. end;
  336. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  337. begin
  338. Result:=RegReadByInstruction(reg,hp);
  339. end;
  340. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  341. var
  342. p: taicpu;
  343. opcount: longint;
  344. begin
  345. RegReadByInstruction := false;
  346. if hp.typ <> ait_instruction then
  347. exit;
  348. p := taicpu(hp);
  349. case p.opcode of
  350. A_CALL:
  351. regreadbyinstruction := true;
  352. A_IMUL:
  353. case p.ops of
  354. 1:
  355. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  356. (
  357. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  358. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  359. );
  360. 2,3:
  361. regReadByInstruction :=
  362. reginop(reg,p.oper[0]^) or
  363. reginop(reg,p.oper[1]^);
  364. else
  365. InternalError(2019112801);
  366. end;
  367. A_MUL:
  368. begin
  369. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  370. (
  371. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  372. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  373. );
  374. end;
  375. A_IDIV,A_DIV:
  376. begin
  377. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  378. (
  379. (getregtype(reg)=R_INTREGISTER) and
  380. (
  381. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  382. )
  383. );
  384. end;
  385. else
  386. begin
  387. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  388. begin
  389. RegReadByInstruction := false;
  390. exit;
  391. end;
  392. for opcount := 0 to p.ops-1 do
  393. if (p.oper[opCount]^.typ = top_ref) and
  394. RegInRef(reg,p.oper[opcount]^.ref^) then
  395. begin
  396. RegReadByInstruction := true;
  397. exit
  398. end;
  399. { special handling for SSE MOVSD }
  400. if (p.opcode=A_MOVSD) and (p.ops>0) then
  401. begin
  402. if p.ops<>2 then
  403. internalerror(2017042702);
  404. regReadByInstruction := reginop(reg,p.oper[0]^) or
  405. (
  406. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  407. );
  408. exit;
  409. end;
  410. with insprop[p.opcode] do
  411. begin
  412. if getregtype(reg)=R_INTREGISTER then
  413. begin
  414. case getsupreg(reg) of
  415. RS_EAX:
  416. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  417. begin
  418. RegReadByInstruction := true;
  419. exit
  420. end;
  421. RS_ECX:
  422. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  423. begin
  424. RegReadByInstruction := true;
  425. exit
  426. end;
  427. RS_EDX:
  428. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  429. begin
  430. RegReadByInstruction := true;
  431. exit
  432. end;
  433. RS_EBX:
  434. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  435. begin
  436. RegReadByInstruction := true;
  437. exit
  438. end;
  439. RS_ESP:
  440. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  441. begin
  442. RegReadByInstruction := true;
  443. exit
  444. end;
  445. RS_EBP:
  446. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. RS_ESI:
  452. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  453. begin
  454. RegReadByInstruction := true;
  455. exit
  456. end;
  457. RS_EDI:
  458. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  459. begin
  460. RegReadByInstruction := true;
  461. exit
  462. end;
  463. end;
  464. end;
  465. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  466. begin
  467. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  468. begin
  469. case p.condition of
  470. C_A,C_NBE, { CF=0 and ZF=0 }
  471. C_BE,C_NA: { CF=1 or ZF=1 }
  472. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  473. C_AE,C_NB,C_NC, { CF=0 }
  474. C_B,C_NAE,C_C: { CF=1 }
  475. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  476. C_NE,C_NZ, { ZF=0 }
  477. C_E,C_Z: { ZF=1 }
  478. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  479. C_G,C_NLE, { ZF=0 and SF=OF }
  480. C_LE,C_NG: { ZF=1 or SF<>OF }
  481. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  482. C_GE,C_NL, { SF=OF }
  483. C_L,C_NGE: { SF<>OF }
  484. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  485. C_NO, { OF=0 }
  486. C_O: { OF=1 }
  487. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  488. C_NP,C_PO, { PF=0 }
  489. C_P,C_PE: { PF=1 }
  490. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  491. C_NS, { SF=0 }
  492. C_S: { SF=1 }
  493. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  494. else
  495. internalerror(2017042701);
  496. end;
  497. if RegReadByInstruction then
  498. exit;
  499. end;
  500. case getsubreg(reg) of
  501. R_SUBW,R_SUBD,R_SUBQ:
  502. RegReadByInstruction :=
  503. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  504. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  505. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  506. R_SUBFLAGCARRY:
  507. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  508. R_SUBFLAGPARITY:
  509. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  510. R_SUBFLAGAUXILIARY:
  511. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  512. R_SUBFLAGZERO:
  513. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  514. R_SUBFLAGSIGN:
  515. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  516. R_SUBFLAGOVERFLOW:
  517. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  518. R_SUBFLAGINTERRUPT:
  519. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  520. R_SUBFLAGDIRECTION:
  521. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  522. else
  523. internalerror(2017042601);
  524. end;
  525. exit;
  526. end;
  527. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  528. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  529. (p.oper[0]^.reg=p.oper[1]^.reg) then
  530. exit;
  531. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  532. begin
  533. RegReadByInstruction := true;
  534. exit
  535. end;
  536. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  537. begin
  538. RegReadByInstruction := true;
  539. exit
  540. end;
  541. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  542. begin
  543. RegReadByInstruction := true;
  544. exit
  545. end;
  546. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  547. begin
  548. RegReadByInstruction := true;
  549. exit
  550. end;
  551. end;
  552. end;
  553. end;
  554. end;
  555. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  556. begin
  557. result:=false;
  558. if p1.typ<>ait_instruction then
  559. exit;
  560. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  561. exit(true);
  562. if (getregtype(reg)=R_INTREGISTER) and
  563. { change information for xmm movsd are not correct }
  564. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  565. begin
  566. case getsupreg(reg) of
  567. { RS_EAX = RS_RAX on x86-64 }
  568. RS_EAX:
  569. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  570. RS_ECX:
  571. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  572. RS_EDX:
  573. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  574. RS_EBX:
  575. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  576. RS_ESP:
  577. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  578. RS_EBP:
  579. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  580. RS_ESI:
  581. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  582. RS_EDI:
  583. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  584. else
  585. ;
  586. end;
  587. if result then
  588. exit;
  589. end
  590. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  591. begin
  592. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  593. exit(true);
  594. case getsubreg(reg) of
  595. R_SUBFLAGCARRY:
  596. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  597. R_SUBFLAGPARITY:
  598. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  599. R_SUBFLAGAUXILIARY:
  600. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  601. R_SUBFLAGZERO:
  602. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  603. R_SUBFLAGSIGN:
  604. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  605. R_SUBFLAGOVERFLOW:
  606. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  607. R_SUBFLAGINTERRUPT:
  608. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  609. R_SUBFLAGDIRECTION:
  610. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  611. else
  612. ;
  613. end;
  614. if result then
  615. exit;
  616. end
  617. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  618. exit(true);
  619. Result:=inherited RegInInstruction(Reg, p1);
  620. end;
  621. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  622. begin
  623. Result := False;
  624. if p1.typ <> ait_instruction then
  625. exit;
  626. with insprop[taicpu(p1).opcode] do
  627. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  628. begin
  629. case getsubreg(reg) of
  630. R_SUBW,R_SUBD,R_SUBQ:
  631. Result :=
  632. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  633. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  634. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  635. R_SUBFLAGCARRY:
  636. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  637. R_SUBFLAGPARITY:
  638. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  639. R_SUBFLAGAUXILIARY:
  640. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  641. R_SUBFLAGZERO:
  642. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  643. R_SUBFLAGSIGN:
  644. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  645. R_SUBFLAGOVERFLOW:
  646. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  647. R_SUBFLAGINTERRUPT:
  648. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  649. R_SUBFLAGDIRECTION:
  650. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  651. else
  652. internalerror(2017042602);
  653. end;
  654. exit;
  655. end;
  656. case taicpu(p1).opcode of
  657. A_CALL:
  658. { We could potentially set Result to False if the register in
  659. question is non-volatile for the subroutine's calling convention,
  660. but this would require detecting the calling convention in use and
  661. also assuming that the routine doesn't contain malformed assembly
  662. language, for example... so it could only be done under -O4 as it
  663. would be considered a side-effect. [Kit] }
  664. Result := True;
  665. A_MOVSD:
  666. { special handling for SSE MOVSD }
  667. if (taicpu(p1).ops>0) then
  668. begin
  669. if taicpu(p1).ops<>2 then
  670. internalerror(2017042703);
  671. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  672. end;
  673. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  674. so fix it here (FK)
  675. }
  676. A_VMOVSS,
  677. A_VMOVSD:
  678. begin
  679. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  680. exit;
  681. end;
  682. A_IMUL:
  683. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  684. else
  685. ;
  686. end;
  687. if Result then
  688. exit;
  689. with insprop[taicpu(p1).opcode] do
  690. begin
  691. if getregtype(reg)=R_INTREGISTER then
  692. begin
  693. case getsupreg(reg) of
  694. RS_EAX:
  695. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  696. begin
  697. Result := True;
  698. exit
  699. end;
  700. RS_ECX:
  701. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  702. begin
  703. Result := True;
  704. exit
  705. end;
  706. RS_EDX:
  707. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  708. begin
  709. Result := True;
  710. exit
  711. end;
  712. RS_EBX:
  713. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  714. begin
  715. Result := True;
  716. exit
  717. end;
  718. RS_ESP:
  719. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  720. begin
  721. Result := True;
  722. exit
  723. end;
  724. RS_EBP:
  725. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  726. begin
  727. Result := True;
  728. exit
  729. end;
  730. RS_ESI:
  731. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  732. begin
  733. Result := True;
  734. exit
  735. end;
  736. RS_EDI:
  737. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  738. begin
  739. Result := True;
  740. exit
  741. end;
  742. end;
  743. end;
  744. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  745. begin
  746. Result := true;
  747. exit
  748. end;
  749. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  750. begin
  751. Result := true;
  752. exit
  753. end;
  754. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  755. begin
  756. Result := true;
  757. exit
  758. end;
  759. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  760. begin
  761. Result := true;
  762. exit
  763. end;
  764. end;
  765. end;
  766. {$ifdef DEBUG_AOPTCPU}
  767. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  768. begin
  769. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  770. end;
  771. function debug_tostr(i: tcgint): string; inline;
  772. begin
  773. Result := tostr(i);
  774. end;
  775. function debug_regname(r: TRegister): string; inline;
  776. begin
  777. Result := '%' + std_regname(r);
  778. end;
  779. { Debug output function - creates a string representation of an operator }
  780. function debug_operstr(oper: TOper): string;
  781. begin
  782. case oper.typ of
  783. top_const:
  784. Result := '$' + debug_tostr(oper.val);
  785. top_reg:
  786. Result := debug_regname(oper.reg);
  787. top_ref:
  788. begin
  789. if oper.ref^.offset <> 0 then
  790. Result := debug_tostr(oper.ref^.offset) + '('
  791. else
  792. Result := '(';
  793. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  794. begin
  795. Result := Result + debug_regname(oper.ref^.base);
  796. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  797. Result := Result + ',' + debug_regname(oper.ref^.index);
  798. end
  799. else
  800. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  801. Result := Result + debug_regname(oper.ref^.index);
  802. if (oper.ref^.scalefactor > 1) then
  803. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  804. else
  805. Result := Result + ')';
  806. end;
  807. else
  808. Result := '[UNKNOWN]';
  809. end;
  810. end;
  811. function debug_op2str(opcode: tasmop): string; inline;
  812. begin
  813. Result := std_op2str[opcode];
  814. end;
  815. function debug_opsize2str(opsize: topsize): string; inline;
  816. begin
  817. Result := gas_opsize2str[opsize];
  818. end;
  819. {$else DEBUG_AOPTCPU}
  820. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  821. begin
  822. end;
  823. function debug_tostr(i: tcgint): string; inline;
  824. begin
  825. Result := '';
  826. end;
  827. function debug_regname(r: TRegister): string; inline;
  828. begin
  829. Result := '';
  830. end;
  831. function debug_operstr(oper: TOper): string; inline;
  832. begin
  833. Result := '';
  834. end;
  835. function debug_op2str(opcode: tasmop): string; inline;
  836. begin
  837. Result := '';
  838. end;
  839. function debug_opsize2str(opsize: topsize): string; inline;
  840. begin
  841. Result := '';
  842. end;
  843. {$endif DEBUG_AOPTCPU}
  844. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  845. begin
  846. {$ifdef x86_64}
  847. { Always fine on x86-64 }
  848. Result := True;
  849. {$else x86_64}
  850. Result :=
  851. {$ifdef i8086}
  852. (current_settings.cputype >= cpu_386) and
  853. {$endif i8086}
  854. (
  855. { Always accept if optimising for size }
  856. (cs_opt_size in current_settings.optimizerswitches) or
  857. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  858. (current_settings.optimizecputype >= cpu_Pentium2)
  859. );
  860. {$endif x86_64}
  861. end;
  862. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  863. begin
  864. if not SuperRegistersEqual(reg1,reg2) then
  865. exit(false);
  866. if getregtype(reg1)<>R_INTREGISTER then
  867. exit(true); {because SuperRegisterEqual is true}
  868. case getsubreg(reg1) of
  869. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  870. higher, it preserves the high bits, so the new value depends on
  871. reg2's previous value. In other words, it is equivalent to doing:
  872. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  873. R_SUBL:
  874. exit(getsubreg(reg2)=R_SUBL);
  875. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  876. higher, it actually does a:
  877. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  878. R_SUBH:
  879. exit(getsubreg(reg2)=R_SUBH);
  880. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  881. bits of reg2:
  882. reg2 := (reg2 and $ffff0000) or word(reg1); }
  883. R_SUBW:
  884. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  885. { a write to R_SUBD always overwrites every other subregister,
  886. because it clears the high 32 bits of R_SUBQ on x86_64 }
  887. R_SUBD,
  888. R_SUBQ:
  889. exit(true);
  890. else
  891. internalerror(2017042801);
  892. end;
  893. end;
  894. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  895. begin
  896. if not SuperRegistersEqual(reg1,reg2) then
  897. exit(false);
  898. if getregtype(reg1)<>R_INTREGISTER then
  899. exit(true); {because SuperRegisterEqual is true}
  900. case getsubreg(reg1) of
  901. R_SUBL:
  902. exit(getsubreg(reg2)<>R_SUBH);
  903. R_SUBH:
  904. exit(getsubreg(reg2)<>R_SUBL);
  905. R_SUBW,
  906. R_SUBD,
  907. R_SUBQ:
  908. exit(true);
  909. else
  910. internalerror(2017042802);
  911. end;
  912. end;
  913. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  914. var
  915. hp1 : tai;
  916. l : TCGInt;
  917. begin
  918. result:=false;
  919. { changes the code sequence
  920. shr/sar const1, x
  921. shl const2, x
  922. to
  923. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  924. if GetNextInstruction(p, hp1) and
  925. MatchInstruction(hp1,A_SHL,[]) and
  926. (taicpu(p).oper[0]^.typ = top_const) and
  927. (taicpu(hp1).oper[0]^.typ = top_const) and
  928. (taicpu(hp1).opsize = taicpu(p).opsize) and
  929. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  930. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  931. begin
  932. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  933. not(cs_opt_size in current_settings.optimizerswitches) then
  934. begin
  935. { shr/sar const1, %reg
  936. shl const2, %reg
  937. with const1 > const2 }
  938. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  939. taicpu(hp1).opcode := A_AND;
  940. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  941. case taicpu(p).opsize Of
  942. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  943. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  944. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  945. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  946. else
  947. Internalerror(2017050703)
  948. end;
  949. end
  950. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  951. not(cs_opt_size in current_settings.optimizerswitches) then
  952. begin
  953. { shr/sar const1, %reg
  954. shl const2, %reg
  955. with const1 < const2 }
  956. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  957. taicpu(p).opcode := A_AND;
  958. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  959. case taicpu(p).opsize Of
  960. S_B: taicpu(p).loadConst(0,l Xor $ff);
  961. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  962. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  963. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  964. else
  965. Internalerror(2017050702)
  966. end;
  967. end
  968. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  969. begin
  970. { shr/sar const1, %reg
  971. shl const2, %reg
  972. with const1 = const2 }
  973. taicpu(p).opcode := A_AND;
  974. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  975. case taicpu(p).opsize Of
  976. S_B: taicpu(p).loadConst(0,l Xor $ff);
  977. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  978. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  979. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  980. else
  981. Internalerror(2017050701)
  982. end;
  983. RemoveInstruction(hp1);
  984. end;
  985. end;
  986. end;
  987. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  988. var
  989. opsize : topsize;
  990. hp1 : tai;
  991. tmpref : treference;
  992. ShiftValue : Cardinal;
  993. BaseValue : TCGInt;
  994. begin
  995. result:=false;
  996. opsize:=taicpu(p).opsize;
  997. { changes certain "imul const, %reg"'s to lea sequences }
  998. if (MatchOpType(taicpu(p),top_const,top_reg) or
  999. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1000. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1001. if (taicpu(p).oper[0]^.val = 1) then
  1002. if (taicpu(p).ops = 2) then
  1003. { remove "imul $1, reg" }
  1004. begin
  1005. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1006. Result := RemoveCurrentP(p);
  1007. end
  1008. else
  1009. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1010. begin
  1011. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1012. InsertLLItem(p.previous, p.next, hp1);
  1013. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1014. p.free;
  1015. p := hp1;
  1016. end
  1017. else if ((taicpu(p).ops <= 2) or
  1018. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1019. not(cs_opt_size in current_settings.optimizerswitches) and
  1020. (not(GetNextInstruction(p, hp1)) or
  1021. not((tai(hp1).typ = ait_instruction) and
  1022. ((taicpu(hp1).opcode=A_Jcc) and
  1023. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1024. begin
  1025. {
  1026. imul X, reg1, reg2 to
  1027. lea (reg1,reg1,Y), reg2
  1028. shl ZZ,reg2
  1029. imul XX, reg1 to
  1030. lea (reg1,reg1,YY), reg1
  1031. shl ZZ,reg2
  1032. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1033. it does not exist as a separate optimization target in FPC though.
  1034. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1035. at most two zeros
  1036. }
  1037. reference_reset(tmpref,1,[]);
  1038. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1039. begin
  1040. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1041. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1042. TmpRef.base := taicpu(p).oper[1]^.reg;
  1043. TmpRef.index := taicpu(p).oper[1]^.reg;
  1044. if not(BaseValue in [3,5,9]) then
  1045. Internalerror(2018110101);
  1046. TmpRef.ScaleFactor := BaseValue-1;
  1047. if (taicpu(p).ops = 2) then
  1048. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1049. else
  1050. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1051. AsmL.InsertAfter(hp1,p);
  1052. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1053. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1054. RemoveCurrentP(p, hp1);
  1055. if ShiftValue>0 then
  1056. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1057. end;
  1058. end;
  1059. end;
  1060. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1061. var
  1062. p: taicpu;
  1063. begin
  1064. if not assigned(hp) or
  1065. (hp.typ <> ait_instruction) then
  1066. begin
  1067. Result := false;
  1068. exit;
  1069. end;
  1070. p := taicpu(hp);
  1071. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1072. with insprop[p.opcode] do
  1073. begin
  1074. case getsubreg(reg) of
  1075. R_SUBW,R_SUBD,R_SUBQ:
  1076. Result:=
  1077. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1078. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1079. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1080. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1081. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1082. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1083. R_SUBFLAGCARRY:
  1084. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1085. R_SUBFLAGPARITY:
  1086. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1087. R_SUBFLAGAUXILIARY:
  1088. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1089. R_SUBFLAGZERO:
  1090. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1091. R_SUBFLAGSIGN:
  1092. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1093. R_SUBFLAGOVERFLOW:
  1094. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1095. R_SUBFLAGINTERRUPT:
  1096. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1097. R_SUBFLAGDIRECTION:
  1098. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1099. else
  1100. begin
  1101. writeln(getsubreg(reg));
  1102. internalerror(2017050501);
  1103. end;
  1104. end;
  1105. exit;
  1106. end;
  1107. Result :=
  1108. (((p.opcode = A_MOV) or
  1109. (p.opcode = A_MOVZX) or
  1110. (p.opcode = A_MOVSX) or
  1111. (p.opcode = A_LEA) or
  1112. (p.opcode = A_VMOVSS) or
  1113. (p.opcode = A_VMOVSD) or
  1114. (p.opcode = A_VMOVAPD) or
  1115. (p.opcode = A_VMOVAPS) or
  1116. (p.opcode = A_VMOVQ) or
  1117. (p.opcode = A_MOVSS) or
  1118. (p.opcode = A_MOVSD) or
  1119. (p.opcode = A_MOVQ) or
  1120. (p.opcode = A_MOVAPD) or
  1121. (p.opcode = A_MOVAPS) or
  1122. {$ifndef x86_64}
  1123. (p.opcode = A_LDS) or
  1124. (p.opcode = A_LES) or
  1125. {$endif not x86_64}
  1126. (p.opcode = A_LFS) or
  1127. (p.opcode = A_LGS) or
  1128. (p.opcode = A_LSS)) and
  1129. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1130. (p.oper[1]^.typ = top_reg) and
  1131. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1132. ((p.oper[0]^.typ = top_const) or
  1133. ((p.oper[0]^.typ = top_reg) and
  1134. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1135. ((p.oper[0]^.typ = top_ref) and
  1136. not RegInRef(reg,p.oper[0]^.ref^)))) or
  1137. ((p.opcode = A_POP) and
  1138. (Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg))) or
  1139. ((p.opcode = A_IMUL) and
  1140. (p.ops=3) and
  1141. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1142. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1143. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^))))) or
  1144. ((((p.opcode = A_IMUL) or
  1145. (p.opcode = A_MUL)) and
  1146. (p.ops=1)) and
  1147. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1148. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^)))) and
  1149. (((p.opsize=S_B) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1150. ((p.opsize=S_W) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1151. ((p.opsize=S_L) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg))
  1152. {$ifdef x86_64}
  1153. or ((p.opsize=S_Q) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg))
  1154. {$endif x86_64}
  1155. )) or
  1156. ((p.opcode = A_CWD) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1157. ((p.opcode = A_CDQ) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)) or
  1158. {$ifdef x86_64}
  1159. ((p.opcode = A_CQO) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)) or
  1160. {$endif x86_64}
  1161. ((p.opcode = A_CBW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1162. {$ifndef x86_64}
  1163. ((p.opcode = A_LDS) and (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1164. ((p.opcode = A_LES) and (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1165. {$endif not x86_64}
  1166. ((p.opcode = A_LFS) and (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1167. ((p.opcode = A_LGS) and (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1168. ((p.opcode = A_LSS) and (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1169. {$ifndef x86_64}
  1170. ((p.opcode = A_AAM) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1171. {$endif not x86_64}
  1172. ((p.opcode = A_LAHF) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1173. ((p.opcode = A_LODSB) and Reg1WriteOverwritesReg2Entirely(NR_AL,reg)) or
  1174. ((p.opcode = A_LODSW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg)) or
  1175. ((p.opcode = A_LODSD) and Reg1WriteOverwritesReg2Entirely(NR_EAX,reg)) or
  1176. {$ifdef x86_64}
  1177. ((p.opcode = A_LODSQ) and Reg1WriteOverwritesReg2Entirely(NR_RAX,reg)) or
  1178. {$endif x86_64}
  1179. ((p.opcode = A_SETcc) and (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1180. (((p.opcode = A_FSTSW) or
  1181. (p.opcode = A_FNSTSW)) and
  1182. (p.oper[0]^.typ=top_reg) and
  1183. Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1184. (((p.opcode = A_XOR) or (p.opcode = A_SUB) or (p.opcode = A_SBB)) and
  1185. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  1186. (p.oper[0]^.reg=p.oper[1]^.reg) and
  1187. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg));
  1188. end;
  1189. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1190. var
  1191. hp2,hp3 : tai;
  1192. begin
  1193. { some x86-64 issue a NOP before the real exit code }
  1194. if MatchInstruction(p,A_NOP,[]) then
  1195. GetNextInstruction(p,p);
  1196. result:=assigned(p) and (p.typ=ait_instruction) and
  1197. ((taicpu(p).opcode = A_RET) or
  1198. ((taicpu(p).opcode=A_LEAVE) and
  1199. GetNextInstruction(p,hp2) and
  1200. MatchInstruction(hp2,A_RET,[S_NO])
  1201. ) or
  1202. (((taicpu(p).opcode=A_LEA) and
  1203. MatchOpType(taicpu(p),top_ref,top_reg) and
  1204. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1205. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1206. ) and
  1207. GetNextInstruction(p,hp2) and
  1208. MatchInstruction(hp2,A_RET,[S_NO])
  1209. ) or
  1210. ((((taicpu(p).opcode=A_MOV) and
  1211. MatchOpType(taicpu(p),top_reg,top_reg) and
  1212. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1213. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1214. ((taicpu(p).opcode=A_LEA) and
  1215. MatchOpType(taicpu(p),top_ref,top_reg) and
  1216. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1217. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1218. )
  1219. ) and
  1220. GetNextInstruction(p,hp2) and
  1221. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1222. MatchOpType(taicpu(hp2),top_reg) and
  1223. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1224. GetNextInstruction(hp2,hp3) and
  1225. MatchInstruction(hp3,A_RET,[S_NO])
  1226. )
  1227. );
  1228. end;
  1229. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1230. begin
  1231. isFoldableArithOp := False;
  1232. case hp1.opcode of
  1233. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1234. isFoldableArithOp :=
  1235. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1236. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1237. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1238. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1239. (taicpu(hp1).oper[1]^.reg = reg);
  1240. A_INC,A_DEC,A_NEG,A_NOT:
  1241. isFoldableArithOp :=
  1242. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1243. (taicpu(hp1).oper[0]^.reg = reg);
  1244. else
  1245. ;
  1246. end;
  1247. end;
  1248. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1249. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1250. var
  1251. hp2: tai;
  1252. begin
  1253. hp2 := p;
  1254. repeat
  1255. hp2 := tai(hp2.previous);
  1256. if assigned(hp2) and
  1257. (hp2.typ = ait_regalloc) and
  1258. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1259. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1260. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1261. begin
  1262. RemoveInstruction(hp2);
  1263. break;
  1264. end;
  1265. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1266. end;
  1267. begin
  1268. case current_procinfo.procdef.returndef.typ of
  1269. arraydef,recorddef,pointerdef,
  1270. stringdef,enumdef,procdef,objectdef,errordef,
  1271. filedef,setdef,procvardef,
  1272. classrefdef,forwarddef:
  1273. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1274. orddef:
  1275. if current_procinfo.procdef.returndef.size <> 0 then
  1276. begin
  1277. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1278. { for int64/qword }
  1279. if current_procinfo.procdef.returndef.size = 8 then
  1280. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1281. end;
  1282. else
  1283. ;
  1284. end;
  1285. end;
  1286. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1287. var
  1288. hp1,hp2 : tai;
  1289. begin
  1290. result:=false;
  1291. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1292. begin
  1293. { vmova* reg1,reg1
  1294. =>
  1295. <nop> }
  1296. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1297. begin
  1298. RemoveCurrentP(p);
  1299. result:=true;
  1300. exit;
  1301. end
  1302. else if GetNextInstruction(p,hp1) then
  1303. begin
  1304. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1305. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1306. begin
  1307. { vmova* reg1,reg2
  1308. vmova* reg2,reg3
  1309. dealloc reg2
  1310. =>
  1311. vmova* reg1,reg3 }
  1312. TransferUsedRegs(TmpUsedRegs);
  1313. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1314. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1315. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1316. begin
  1317. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1318. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1319. RemoveInstruction(hp1);
  1320. result:=true;
  1321. exit;
  1322. end
  1323. { special case:
  1324. vmova* reg1,<op>
  1325. vmova* <op>,reg1
  1326. =>
  1327. vmova* reg1,<op> }
  1328. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1329. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1330. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1331. ) then
  1332. begin
  1333. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1334. RemoveInstruction(hp1);
  1335. result:=true;
  1336. exit;
  1337. end
  1338. end
  1339. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1340. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1341. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1342. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1343. ) and
  1344. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1345. begin
  1346. { vmova* reg1,reg2
  1347. vmovs* reg2,<op>
  1348. dealloc reg2
  1349. =>
  1350. vmovs* reg1,reg3 }
  1351. TransferUsedRegs(TmpUsedRegs);
  1352. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1353. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1354. begin
  1355. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1356. taicpu(p).opcode:=taicpu(hp1).opcode;
  1357. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1358. RemoveInstruction(hp1);
  1359. result:=true;
  1360. exit;
  1361. end
  1362. end;
  1363. end;
  1364. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1365. begin
  1366. if MatchInstruction(hp1,[A_VFMADDPD,
  1367. A_VFMADD132PD,
  1368. A_VFMADD132PS,
  1369. A_VFMADD132SD,
  1370. A_VFMADD132SS,
  1371. A_VFMADD213PD,
  1372. A_VFMADD213PS,
  1373. A_VFMADD213SD,
  1374. A_VFMADD213SS,
  1375. A_VFMADD231PD,
  1376. A_VFMADD231PS,
  1377. A_VFMADD231SD,
  1378. A_VFMADD231SS,
  1379. A_VFMADDSUB132PD,
  1380. A_VFMADDSUB132PS,
  1381. A_VFMADDSUB213PD,
  1382. A_VFMADDSUB213PS,
  1383. A_VFMADDSUB231PD,
  1384. A_VFMADDSUB231PS,
  1385. A_VFMSUB132PD,
  1386. A_VFMSUB132PS,
  1387. A_VFMSUB132SD,
  1388. A_VFMSUB132SS,
  1389. A_VFMSUB213PD,
  1390. A_VFMSUB213PS,
  1391. A_VFMSUB213SD,
  1392. A_VFMSUB213SS,
  1393. A_VFMSUB231PD,
  1394. A_VFMSUB231PS,
  1395. A_VFMSUB231SD,
  1396. A_VFMSUB231SS,
  1397. A_VFMSUBADD132PD,
  1398. A_VFMSUBADD132PS,
  1399. A_VFMSUBADD213PD,
  1400. A_VFMSUBADD213PS,
  1401. A_VFMSUBADD231PD,
  1402. A_VFMSUBADD231PS,
  1403. A_VFNMADD132PD,
  1404. A_VFNMADD132PS,
  1405. A_VFNMADD132SD,
  1406. A_VFNMADD132SS,
  1407. A_VFNMADD213PD,
  1408. A_VFNMADD213PS,
  1409. A_VFNMADD213SD,
  1410. A_VFNMADD213SS,
  1411. A_VFNMADD231PD,
  1412. A_VFNMADD231PS,
  1413. A_VFNMADD231SD,
  1414. A_VFNMADD231SS,
  1415. A_VFNMSUB132PD,
  1416. A_VFNMSUB132PS,
  1417. A_VFNMSUB132SD,
  1418. A_VFNMSUB132SS,
  1419. A_VFNMSUB213PD,
  1420. A_VFNMSUB213PS,
  1421. A_VFNMSUB213SD,
  1422. A_VFNMSUB213SS,
  1423. A_VFNMSUB231PD,
  1424. A_VFNMSUB231PS,
  1425. A_VFNMSUB231SD,
  1426. A_VFNMSUB231SS],[S_NO]) and
  1427. { we mix single and double opperations here because we assume that the compiler
  1428. generates vmovapd only after double operations and vmovaps only after single operations }
  1429. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1430. GetNextInstruction(hp1,hp2) and
  1431. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1432. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1433. begin
  1434. TransferUsedRegs(TmpUsedRegs);
  1435. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1436. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1437. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1438. begin
  1439. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1440. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1441. RemoveInstruction(hp2);
  1442. end;
  1443. end
  1444. else if (hp1.typ = ait_instruction) and
  1445. GetNextInstruction(hp1, hp2) and
  1446. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1447. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1448. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1449. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1450. (((taicpu(p).opcode=A_MOVAPS) and
  1451. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1452. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1453. ((taicpu(p).opcode=A_MOVAPD) and
  1454. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1455. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1456. ) then
  1457. { change
  1458. movapX reg,reg2
  1459. addsX/subsX/... reg3, reg2
  1460. movapX reg2,reg
  1461. to
  1462. addsX/subsX/... reg3,reg
  1463. }
  1464. begin
  1465. TransferUsedRegs(TmpUsedRegs);
  1466. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1467. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1468. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1469. begin
  1470. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1471. debug_op2str(taicpu(p).opcode)+' '+
  1472. debug_op2str(taicpu(hp1).opcode)+' '+
  1473. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1474. { we cannot eliminate the first move if
  1475. the operations uses the same register for source and dest }
  1476. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1477. RemoveCurrentP(p, nil);
  1478. p:=hp1;
  1479. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1480. RemoveInstruction(hp2);
  1481. result:=true;
  1482. end;
  1483. end;
  1484. end;
  1485. end;
  1486. end;
  1487. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1488. var
  1489. hp1 : tai;
  1490. begin
  1491. result:=false;
  1492. { replace
  1493. V<Op>X %mreg1,%mreg2,%mreg3
  1494. VMovX %mreg3,%mreg4
  1495. dealloc %mreg3
  1496. by
  1497. V<Op>X %mreg1,%mreg2,%mreg4
  1498. ?
  1499. }
  1500. if GetNextInstruction(p,hp1) and
  1501. { we mix single and double operations here because we assume that the compiler
  1502. generates vmovapd only after double operations and vmovaps only after single operations }
  1503. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1504. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1505. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1506. begin
  1507. TransferUsedRegs(TmpUsedRegs);
  1508. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1509. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1510. begin
  1511. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1512. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1513. RemoveInstruction(hp1);
  1514. result:=true;
  1515. end;
  1516. end;
  1517. end;
  1518. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1519. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1520. var
  1521. OldSupReg: TSuperRegister;
  1522. OldSubReg, MemSubReg: TSubRegister;
  1523. begin
  1524. Result := False;
  1525. { For safety reasons, only check for exact register matches }
  1526. { Check base register }
  1527. if (ref.base = AOldReg) then
  1528. begin
  1529. ref.base := ANewReg;
  1530. Result := True;
  1531. end;
  1532. { Check index register }
  1533. if (ref.index = AOldReg) then
  1534. begin
  1535. ref.index := ANewReg;
  1536. Result := True;
  1537. end;
  1538. end;
  1539. { Replaces all references to AOldReg in an operand to ANewReg }
  1540. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1541. var
  1542. OldSupReg, NewSupReg: TSuperRegister;
  1543. OldSubReg, NewSubReg, MemSubReg: TSubRegister;
  1544. OldRegType: TRegisterType;
  1545. ThisOper: POper;
  1546. begin
  1547. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1548. Result := False;
  1549. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1550. InternalError(2020011801);
  1551. OldSupReg := getsupreg(AOldReg);
  1552. OldSubReg := getsubreg(AOldReg);
  1553. OldRegType := getregtype(AOldReg);
  1554. NewSupReg := getsupreg(ANewReg);
  1555. NewSubReg := getsubreg(ANewReg);
  1556. if OldRegType <> getregtype(ANewReg) then
  1557. InternalError(2020011802);
  1558. if OldSubReg <> NewSubReg then
  1559. InternalError(2020011803);
  1560. case ThisOper^.typ of
  1561. top_reg:
  1562. if (
  1563. (ThisOper^.reg = AOldReg) or
  1564. (
  1565. (OldRegType = R_INTREGISTER) and
  1566. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1567. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1568. (
  1569. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1570. {$ifndef x86_64}
  1571. and (
  1572. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1573. don't have an 8-bit representation }
  1574. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1575. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1576. )
  1577. {$endif x86_64}
  1578. )
  1579. )
  1580. ) then
  1581. begin
  1582. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1583. Result := True;
  1584. end;
  1585. top_ref:
  1586. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1587. Result := True;
  1588. else
  1589. ;
  1590. end;
  1591. end;
  1592. { Replaces all references to AOldReg in an instruction to ANewReg }
  1593. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1594. const
  1595. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1596. var
  1597. OperIdx: Integer;
  1598. begin
  1599. Result := False;
  1600. for OperIdx := 0 to p.ops - 1 do
  1601. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1602. { The shift and rotate instructions can only use CL }
  1603. not (
  1604. (OperIdx = 0) and
  1605. { This second condition just helps to avoid unnecessarily
  1606. calling MatchInstruction for 10 different opcodes }
  1607. (p.oper[0]^.reg = NR_CL) and
  1608. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1609. ) then
  1610. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1611. end;
  1612. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1613. begin
  1614. Result :=
  1615. (ref^.index = NR_NO) and
  1616. (
  1617. {$ifdef x86_64}
  1618. (
  1619. (ref^.base = NR_RIP) and
  1620. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1621. ) or
  1622. {$endif x86_64}
  1623. (ref^.base = NR_STACK_POINTER_REG) or
  1624. (ref^.base = current_procinfo.framepointer)
  1625. );
  1626. end;
  1627. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1628. var
  1629. l: asizeint;
  1630. begin
  1631. Result := False;
  1632. { Should have been checked previously }
  1633. if p.opcode <> A_LEA then
  1634. InternalError(2020072501);
  1635. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1636. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1637. not(cs_opt_size in current_settings.optimizerswitches) then
  1638. exit;
  1639. with p.oper[0]^.ref^ do
  1640. begin
  1641. if (base <> p.oper[1]^.reg) or
  1642. (index <> NR_NO) or
  1643. assigned(symbol) then
  1644. exit;
  1645. l:=offset;
  1646. if (l=1) and UseIncDec then
  1647. begin
  1648. p.opcode:=A_INC;
  1649. p.loadreg(0,p.oper[1]^.reg);
  1650. p.ops:=1;
  1651. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1652. end
  1653. else if (l=-1) and UseIncDec then
  1654. begin
  1655. p.opcode:=A_DEC;
  1656. p.loadreg(0,p.oper[1]^.reg);
  1657. p.ops:=1;
  1658. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1659. end
  1660. else
  1661. begin
  1662. if (l<0) and (l<>-2147483648) then
  1663. begin
  1664. p.opcode:=A_SUB;
  1665. p.loadConst(0,-l);
  1666. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1667. end
  1668. else
  1669. begin
  1670. p.opcode:=A_ADD;
  1671. p.loadConst(0,l);
  1672. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1673. end;
  1674. end;
  1675. end;
  1676. Result := True;
  1677. end;
  1678. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1679. var
  1680. CurrentReg, ReplaceReg: TRegister;
  1681. SubReg: TSubRegister;
  1682. begin
  1683. Result := False;
  1684. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1685. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1686. case hp.opcode of
  1687. A_FSTSW, A_FNSTSW,
  1688. A_IN, A_INS, A_OUT, A_OUTS,
  1689. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1690. { These routines have explicit operands, but they are restricted in
  1691. what they can be (e.g. IN and OUT can only read from AL, AX or
  1692. EAX. }
  1693. Exit;
  1694. A_IMUL:
  1695. begin
  1696. { The 1-operand version writes to implicit registers
  1697. The 2-operand version reads from the first operator, and reads
  1698. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1699. the 3-operand version reads from a register that it doesn't write to
  1700. }
  1701. case hp.ops of
  1702. 1:
  1703. if (
  1704. (
  1705. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1706. ) or
  1707. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1708. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1709. begin
  1710. Result := True;
  1711. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1712. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1713. end;
  1714. 2:
  1715. { Only modify the first parameter }
  1716. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1717. begin
  1718. Result := True;
  1719. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1720. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1721. end;
  1722. 3:
  1723. { Only modify the second parameter }
  1724. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1725. begin
  1726. Result := True;
  1727. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1728. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1729. end;
  1730. else
  1731. InternalError(2020012901);
  1732. end;
  1733. end;
  1734. else
  1735. if (hp.ops > 0) and
  1736. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1737. begin
  1738. Result := True;
  1739. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1740. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1741. end;
  1742. end;
  1743. end;
  1744. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  1745. var
  1746. hp1, hp2, hp3: tai;
  1747. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  1748. begin
  1749. if taicpu(hp1).opcode = signed_movop then
  1750. begin
  1751. if taicpu(p).oper[0]^.val > max_value shr 1 then
  1752. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  1753. end
  1754. else
  1755. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  1756. end;
  1757. var
  1758. GetNextInstruction_p, TempRegUsed: Boolean;
  1759. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  1760. NewSize: topsize;
  1761. CurrentReg: TRegister;
  1762. begin
  1763. Result:=false;
  1764. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  1765. { remove mov reg1,reg1? }
  1766. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  1767. then
  1768. begin
  1769. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  1770. { take care of the register (de)allocs following p }
  1771. RemoveCurrentP(p, hp1);
  1772. Result:=true;
  1773. exit;
  1774. end;
  1775. { All the next optimisations require a next instruction }
  1776. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  1777. Exit;
  1778. { Look for:
  1779. mov %reg1,%reg2
  1780. ??? %reg2,r/m
  1781. Change to:
  1782. mov %reg1,%reg2
  1783. ??? %reg1,r/m
  1784. }
  1785. if MatchOpType(taicpu(p), top_reg, top_reg) then
  1786. begin
  1787. CurrentReg := taicpu(p).oper[1]^.reg;
  1788. if RegReadByInstruction(CurrentReg, hp1) and
  1789. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  1790. begin
  1791. TransferUsedRegs(TmpUsedRegs);
  1792. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  1793. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  1794. { Just in case something didn't get modified (e.g. an
  1795. implicit register) }
  1796. not RegReadByInstruction(CurrentReg, hp1) then
  1797. begin
  1798. { We can remove the original MOV }
  1799. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  1800. RemoveCurrentp(p, hp1);
  1801. { TmpUsedRegs contains the results of "UpdateUsedRegs(tai(p.Next))" already,
  1802. so just restore it to UsedRegs instead of calculating it again }
  1803. RestoreUsedRegs(TmpUsedRegs);
  1804. Result := True;
  1805. Exit;
  1806. end;
  1807. { If we know a MOV instruction has become a null operation, we might as well
  1808. get rid of it now to save time. }
  1809. if (taicpu(hp1).opcode = A_MOV) and
  1810. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1811. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  1812. { Just being a register is enough to confirm it's a null operation }
  1813. (taicpu(hp1).oper[0]^.typ = top_reg) then
  1814. begin
  1815. Result := True;
  1816. { Speed-up to reduce a pipeline stall... if we had something like...
  1817. movl %eax,%edx
  1818. movw %dx,%ax
  1819. ... the second instruction would change to movw %ax,%ax, but
  1820. given that it is now %ax that's active rather than %eax,
  1821. penalties might occur due to a partial register write, so instead,
  1822. change it to a MOVZX instruction when optimising for speed.
  1823. }
  1824. if not (cs_opt_size in current_settings.optimizerswitches) and
  1825. IsMOVZXAcceptable and
  1826. (taicpu(hp1).opsize < taicpu(p).opsize)
  1827. {$ifdef x86_64}
  1828. { operations already implicitly set the upper 64 bits to zero }
  1829. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  1830. {$endif x86_64}
  1831. then
  1832. begin
  1833. CurrentReg := taicpu(hp1).oper[1]^.reg;
  1834. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  1835. case taicpu(p).opsize of
  1836. S_W:
  1837. if taicpu(hp1).opsize = S_B then
  1838. taicpu(hp1).opsize := S_BL
  1839. else
  1840. InternalError(2020012911);
  1841. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  1842. case taicpu(hp1).opsize of
  1843. S_B:
  1844. taicpu(hp1).opsize := S_BL;
  1845. S_W:
  1846. taicpu(hp1).opsize := S_WL;
  1847. else
  1848. InternalError(2020012912);
  1849. end;
  1850. else
  1851. InternalError(2020012910);
  1852. end;
  1853. taicpu(hp1).opcode := A_MOVZX;
  1854. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  1855. end
  1856. else
  1857. begin
  1858. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  1859. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  1860. RemoveInstruction(hp1);
  1861. { The instruction after what was hp1 is now the immediate next instruction,
  1862. so we can continue to make optimisations if it's present }
  1863. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  1864. Exit;
  1865. hp1 := hp2;
  1866. end;
  1867. end;
  1868. end;
  1869. end;
  1870. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  1871. overwrites the original destination register. e.g.
  1872. movl ###,%reg2d
  1873. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  1874. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  1875. }
  1876. if (taicpu(p).oper[1]^.typ = top_reg) and
  1877. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  1878. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1879. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  1880. begin
  1881. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  1882. begin
  1883. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  1884. case taicpu(p).oper[0]^.typ of
  1885. top_const:
  1886. { We have something like:
  1887. movb $x, %regb
  1888. movzbl %regb,%regd
  1889. Change to:
  1890. movl $x, %regd
  1891. }
  1892. begin
  1893. case taicpu(hp1).opsize of
  1894. S_BW:
  1895. begin
  1896. convert_mov_value(A_MOVSX, $FF);
  1897. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  1898. taicpu(p).opsize := S_W;
  1899. end;
  1900. S_BL:
  1901. begin
  1902. convert_mov_value(A_MOVSX, $FF);
  1903. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1904. taicpu(p).opsize := S_L;
  1905. end;
  1906. S_WL:
  1907. begin
  1908. convert_mov_value(A_MOVSX, $FFFF);
  1909. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1910. taicpu(p).opsize := S_L;
  1911. end;
  1912. {$ifdef x86_64}
  1913. S_BQ:
  1914. begin
  1915. convert_mov_value(A_MOVSX, $FF);
  1916. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1917. taicpu(p).opsize := S_Q;
  1918. end;
  1919. S_WQ:
  1920. begin
  1921. convert_mov_value(A_MOVSX, $FFFF);
  1922. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1923. taicpu(p).opsize := S_Q;
  1924. end;
  1925. S_LQ:
  1926. begin
  1927. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  1928. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1929. taicpu(p).opsize := S_Q;
  1930. end;
  1931. {$endif x86_64}
  1932. else
  1933. { If hp1 was a MOV instruction, it should have been
  1934. optimised already }
  1935. InternalError(2020021001);
  1936. end;
  1937. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  1938. RemoveInstruction(hp1);
  1939. Result := True;
  1940. Exit;
  1941. end;
  1942. top_ref:
  1943. { We have something like:
  1944. movb mem, %regb
  1945. movzbl %regb,%regd
  1946. Change to:
  1947. movzbl mem, %regd
  1948. }
  1949. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  1950. begin
  1951. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  1952. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  1953. RemoveCurrentP(p, hp1);
  1954. Result:=True;
  1955. Exit;
  1956. end;
  1957. else
  1958. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  1959. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  1960. Exit;
  1961. end;
  1962. end
  1963. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  1964. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  1965. optimised }
  1966. else
  1967. begin
  1968. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  1969. RemoveCurrentP(p, hp1);
  1970. Result := True;
  1971. Exit;
  1972. end;
  1973. end;
  1974. if (taicpu(hp1).opcode = A_AND) and
  1975. (taicpu(p).oper[1]^.typ = top_reg) and
  1976. MatchOpType(taicpu(hp1),top_const,top_reg) then
  1977. begin
  1978. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1979. begin
  1980. case taicpu(p).opsize of
  1981. S_L:
  1982. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  1983. begin
  1984. { Optimize out:
  1985. mov x, %reg
  1986. and ffffffffh, %reg
  1987. }
  1988. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  1989. RemoveInstruction(hp1);
  1990. Result:=true;
  1991. exit;
  1992. end;
  1993. S_Q: { TODO: Confirm if this is even possible }
  1994. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  1995. begin
  1996. { Optimize out:
  1997. mov x, %reg
  1998. and ffffffffffffffffh, %reg
  1999. }
  2000. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2001. RemoveInstruction(hp1);
  2002. Result:=true;
  2003. exit;
  2004. end;
  2005. else
  2006. ;
  2007. end;
  2008. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2009. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2010. GetNextInstruction(hp1,hp2) and
  2011. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2012. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2013. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) and
  2014. GetNextInstruction(hp2,hp3) and
  2015. MatchInstruction(hp3,A_Jcc,A_Setcc,[S_NO]) and
  2016. (taicpu(hp3).condition in [C_E,C_NE]) then
  2017. begin
  2018. TransferUsedRegs(TmpUsedRegs);
  2019. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2020. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2021. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2022. begin
  2023. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2024. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2025. taicpu(hp1).opcode:=A_TEST;
  2026. RemoveInstruction(hp2);
  2027. RemoveCurrentP(p, hp1);
  2028. Result:=true;
  2029. exit;
  2030. end;
  2031. end;
  2032. end
  2033. else if IsMOVZXAcceptable and
  2034. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2035. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2036. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2037. then
  2038. begin
  2039. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2040. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2041. case taicpu(p).opsize of
  2042. S_B:
  2043. if (taicpu(hp1).oper[0]^.val = $ff) then
  2044. begin
  2045. { Convert:
  2046. movb x, %regl movb x, %regl
  2047. andw ffh, %regw andl ffh, %regd
  2048. To:
  2049. movzbw x, %regd movzbl x, %regd
  2050. (Identical registers, just different sizes)
  2051. }
  2052. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2053. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2054. case taicpu(hp1).opsize of
  2055. S_W: NewSize := S_BW;
  2056. S_L: NewSize := S_BL;
  2057. {$ifdef x86_64}
  2058. S_Q: NewSize := S_BQ;
  2059. {$endif x86_64}
  2060. else
  2061. InternalError(2018011510);
  2062. end;
  2063. end
  2064. else
  2065. NewSize := S_NO;
  2066. S_W:
  2067. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2068. begin
  2069. { Convert:
  2070. movw x, %regw
  2071. andl ffffh, %regd
  2072. To:
  2073. movzwl x, %regd
  2074. (Identical registers, just different sizes)
  2075. }
  2076. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2077. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2078. case taicpu(hp1).opsize of
  2079. S_L: NewSize := S_WL;
  2080. {$ifdef x86_64}
  2081. S_Q: NewSize := S_WQ;
  2082. {$endif x86_64}
  2083. else
  2084. InternalError(2018011511);
  2085. end;
  2086. end
  2087. else
  2088. NewSize := S_NO;
  2089. else
  2090. NewSize := S_NO;
  2091. end;
  2092. if NewSize <> S_NO then
  2093. begin
  2094. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2095. { The actual optimization }
  2096. taicpu(p).opcode := A_MOVZX;
  2097. taicpu(p).changeopsize(NewSize);
  2098. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2099. { Safeguard if "and" is followed by a conditional command }
  2100. TransferUsedRegs(TmpUsedRegs);
  2101. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2102. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2103. begin
  2104. { At this point, the "and" command is effectively equivalent to
  2105. "test %reg,%reg". This will be handled separately by the
  2106. Peephole Optimizer. [Kit] }
  2107. DebugMsg(SPeepholeOptimization + PreMessage +
  2108. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2109. end
  2110. else
  2111. begin
  2112. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2113. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2114. RemoveInstruction(hp1);
  2115. end;
  2116. Result := True;
  2117. Exit;
  2118. end;
  2119. end;
  2120. end;
  2121. { Next instruction is also a MOV ? }
  2122. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2123. begin
  2124. if (taicpu(p).oper[1]^.typ = top_reg) and
  2125. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2126. begin
  2127. CurrentReg := taicpu(p).oper[1]^.reg;
  2128. TransferUsedRegs(TmpUsedRegs);
  2129. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2130. { we have
  2131. mov x, %treg
  2132. mov %treg, y
  2133. }
  2134. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2135. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2136. { we've got
  2137. mov x, %treg
  2138. mov %treg, y
  2139. with %treg is not used after }
  2140. case taicpu(p).oper[0]^.typ Of
  2141. { top_reg is covered by DeepMOVOpt }
  2142. top_const:
  2143. begin
  2144. { change
  2145. mov const, %treg
  2146. mov %treg, y
  2147. to
  2148. mov const, y
  2149. }
  2150. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2151. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2152. begin
  2153. if taicpu(hp1).oper[1]^.typ=top_reg then
  2154. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2155. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2156. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2157. RemoveInstruction(hp1);
  2158. Result:=true;
  2159. Exit;
  2160. end;
  2161. end;
  2162. top_ref:
  2163. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2164. begin
  2165. { change
  2166. mov mem, %treg
  2167. mov %treg, %reg
  2168. to
  2169. mov mem, %reg"
  2170. }
  2171. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2172. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2173. RemoveInstruction(hp1);
  2174. Result:=true;
  2175. Exit;
  2176. end;
  2177. else
  2178. ;
  2179. end
  2180. else
  2181. { %treg is used afterwards, but all eventualities
  2182. other than the first MOV instruction being a constant
  2183. are covered by DeepMOVOpt, so only check for that }
  2184. if (taicpu(p).oper[0]^.typ = top_const) and
  2185. (
  2186. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2187. not (cs_opt_size in current_settings.optimizerswitches) or
  2188. (taicpu(hp1).opsize = S_B)
  2189. ) and
  2190. (
  2191. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2192. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2193. ) then
  2194. begin
  2195. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2196. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2197. end;
  2198. end;
  2199. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2200. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2201. { mov reg1, mem1 or mov mem1, reg1
  2202. mov mem2, reg2 mov reg2, mem2}
  2203. begin
  2204. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2205. { mov reg1, mem1 or mov mem1, reg1
  2206. mov mem2, reg1 mov reg2, mem1}
  2207. begin
  2208. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2209. { Removes the second statement from
  2210. mov reg1, mem1/reg2
  2211. mov mem1/reg2, reg1 }
  2212. begin
  2213. if taicpu(p).oper[0]^.typ=top_reg then
  2214. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2215. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2216. RemoveInstruction(hp1);
  2217. Result:=true;
  2218. exit;
  2219. end
  2220. else
  2221. begin
  2222. TransferUsedRegs(TmpUsedRegs);
  2223. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2224. if (taicpu(p).oper[1]^.typ = top_ref) and
  2225. { mov reg1, mem1
  2226. mov mem2, reg1 }
  2227. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2228. GetNextInstruction(hp1, hp2) and
  2229. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2230. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2231. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2232. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2233. { change to
  2234. mov reg1, mem1 mov reg1, mem1
  2235. mov mem2, reg1 cmp reg1, mem2
  2236. cmp mem1, reg1
  2237. }
  2238. begin
  2239. RemoveInstruction(hp2);
  2240. taicpu(hp1).opcode := A_CMP;
  2241. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2242. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2243. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2244. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2245. end;
  2246. end;
  2247. end
  2248. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2249. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2250. begin
  2251. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2252. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2253. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2254. end
  2255. else
  2256. begin
  2257. TransferUsedRegs(TmpUsedRegs);
  2258. if GetNextInstruction(hp1, hp2) and
  2259. MatchOpType(taicpu(p),top_ref,top_reg) and
  2260. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2261. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2262. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2263. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2264. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2265. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2266. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2267. { mov mem1, %reg1
  2268. mov %reg1, mem2
  2269. mov mem2, reg2
  2270. to:
  2271. mov mem1, reg2
  2272. mov reg2, mem2}
  2273. begin
  2274. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2275. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2276. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2277. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2278. RemoveInstruction(hp2);
  2279. end
  2280. {$ifdef i386}
  2281. { this is enabled for i386 only, as the rules to create the reg sets below
  2282. are too complicated for x86-64, so this makes this code too error prone
  2283. on x86-64
  2284. }
  2285. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2286. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2287. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2288. { mov mem1, reg1 mov mem1, reg1
  2289. mov reg1, mem2 mov reg1, mem2
  2290. mov mem2, reg2 mov mem2, reg1
  2291. to: to:
  2292. mov mem1, reg1 mov mem1, reg1
  2293. mov mem1, reg2 mov reg1, mem2
  2294. mov reg1, mem2
  2295. or (if mem1 depends on reg1
  2296. and/or if mem2 depends on reg2)
  2297. to:
  2298. mov mem1, reg1
  2299. mov reg1, mem2
  2300. mov reg1, reg2
  2301. }
  2302. begin
  2303. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2304. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2305. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2306. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2307. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2308. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2309. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2310. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2311. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2312. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2313. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2314. end
  2315. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2316. begin
  2317. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2318. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2319. end
  2320. else
  2321. begin
  2322. RemoveInstruction(hp2);
  2323. end
  2324. {$endif i386}
  2325. ;
  2326. end;
  2327. end
  2328. { movl [mem1],reg1
  2329. movl [mem1],reg2
  2330. to
  2331. movl [mem1],reg1
  2332. movl reg1,reg2
  2333. }
  2334. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2335. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2336. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2337. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2338. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2339. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2340. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2341. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2342. begin
  2343. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2344. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2345. end;
  2346. { movl const1,[mem1]
  2347. movl [mem1],reg1
  2348. to
  2349. movl const1,reg1
  2350. movl reg1,[mem1]
  2351. }
  2352. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2353. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2354. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2355. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2356. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2357. begin
  2358. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2359. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2360. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2361. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2362. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2363. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2364. Result:=true;
  2365. exit;
  2366. end;
  2367. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2368. end;
  2369. { search further than the next instruction for a mov }
  2370. if
  2371. { check as much as possible before the expensive GetNextInstructionUsingReg call }
  2372. (taicpu(p).oper[1]^.typ = top_reg) and
  2373. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2374. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) and
  2375. { we work with hp2 here, so hp1 can be still used later on when
  2376. checking for GetNextInstruction_p }
  2377. { GetNextInstructionUsingReg only searches one instruction ahead unless -O3 is specified }
  2378. GetNextInstructionUsingReg(hp1,hp2,taicpu(p).oper[1]^.reg) and
  2379. (hp2.typ=ait_instruction) then
  2380. begin
  2381. case taicpu(hp2).opcode of
  2382. A_MOV:
  2383. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2384. ((taicpu(p).oper[0]^.typ=top_const) or
  2385. ((taicpu(p).oper[0]^.typ=top_reg) and
  2386. not(RegUsedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2387. )
  2388. ) then
  2389. begin
  2390. { we have
  2391. mov x, %treg
  2392. mov %treg, y
  2393. }
  2394. TransferUsedRegs(TmpUsedRegs);
  2395. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2396. { We don't need to call UpdateUsedRegs for every instruction between
  2397. p and hp2 because the register we're concerned about will not
  2398. become deallocated (otherwise GetNextInstructionUsingReg would
  2399. have stopped at an earlier instruction). [Kit] }
  2400. TempRegUsed :=
  2401. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2402. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2403. case taicpu(p).oper[0]^.typ Of
  2404. top_reg:
  2405. begin
  2406. { change
  2407. mov %reg, %treg
  2408. mov %treg, y
  2409. to
  2410. mov %reg, y
  2411. }
  2412. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2413. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2414. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2415. begin
  2416. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2417. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2418. if TempRegUsed then
  2419. begin
  2420. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2421. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2422. RemoveInstruction(hp2);
  2423. end
  2424. else
  2425. begin
  2426. RemoveInstruction(hp2);
  2427. { We can remove the original MOV too }
  2428. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2429. RemoveCurrentP(p, hp1);
  2430. Result:=true;
  2431. Exit;
  2432. end;
  2433. end
  2434. else
  2435. begin
  2436. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2437. taicpu(hp2).loadReg(0, CurrentReg);
  2438. if TempRegUsed then
  2439. begin
  2440. { Don't remove the first instruction if the temporary register is in use }
  2441. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2442. { No need to set Result to True. If there's another instruction later on
  2443. that can be optimised, it will be detected when the main Pass 1 loop
  2444. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2445. end
  2446. else
  2447. begin
  2448. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2449. RemoveCurrentP(p, hp1);
  2450. Result:=true;
  2451. Exit;
  2452. end;
  2453. end;
  2454. end;
  2455. top_const:
  2456. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2457. begin
  2458. { change
  2459. mov const, %treg
  2460. mov %treg, y
  2461. to
  2462. mov const, y
  2463. }
  2464. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2465. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2466. begin
  2467. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2468. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2469. if TempRegUsed then
  2470. begin
  2471. { Don't remove the first instruction if the temporary register is in use }
  2472. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2473. { No need to set Result to True. If there's another instruction later on
  2474. that can be optimised, it will be detected when the main Pass 1 loop
  2475. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2476. end
  2477. else
  2478. begin
  2479. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2480. RemoveCurrentP(p, hp1);
  2481. Result:=true;
  2482. Exit;
  2483. end;
  2484. end;
  2485. end;
  2486. else
  2487. Internalerror(2019103001);
  2488. end;
  2489. end;
  2490. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2491. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2492. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2493. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2494. begin
  2495. {
  2496. Change from:
  2497. mov ###, %reg
  2498. ...
  2499. movs/z %reg,%reg (Same register, just different sizes)
  2500. To:
  2501. movs/z ###, %reg (Longer version)
  2502. ...
  2503. (remove)
  2504. }
  2505. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2506. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2507. { Keep the first instruction as mov if ### is a constant }
  2508. if taicpu(p).oper[0]^.typ = top_const then
  2509. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2510. else
  2511. begin
  2512. taicpu(p).opcode := taicpu(hp2).opcode;
  2513. taicpu(p).opsize := taicpu(hp2).opsize;
  2514. end;
  2515. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2516. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2517. RemoveInstruction(hp2);
  2518. Result := True;
  2519. Exit;
  2520. end;
  2521. else
  2522. ;
  2523. end;
  2524. end;
  2525. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2526. (taicpu(p).oper[1]^.typ = top_reg) and
  2527. (taicpu(p).opsize = S_L) and
  2528. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2529. (taicpu(hp2).opcode = A_AND) and
  2530. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2531. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2532. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2533. ) then
  2534. begin
  2535. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2536. begin
  2537. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2538. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2539. begin
  2540. { Optimize out:
  2541. mov x, %reg
  2542. and ffffffffh, %reg
  2543. }
  2544. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2545. RemoveInstruction(hp2);
  2546. Result:=true;
  2547. exit;
  2548. end;
  2549. end;
  2550. end;
  2551. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2552. x >= RetOffset) as it doesn't do anything (it writes either to a
  2553. parameter or to the temporary storage room for the function
  2554. result)
  2555. }
  2556. if IsExitCode(hp1) and
  2557. (taicpu(p).oper[1]^.typ = top_ref) and
  2558. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2559. (
  2560. (
  2561. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2562. not (
  2563. assigned(current_procinfo.procdef.funcretsym) and
  2564. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2565. )
  2566. ) or
  2567. { Also discard writes to the stack that are below the base pointer,
  2568. as this is temporary storage rather than a function result on the
  2569. stack, say. }
  2570. (
  2571. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2572. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2573. )
  2574. ) then
  2575. begin
  2576. RemoveCurrentp(p, hp1);
  2577. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2578. RemoveLastDeallocForFuncRes(p);
  2579. Result:=true;
  2580. exit;
  2581. end;
  2582. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2583. MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) and
  2584. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2585. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2586. begin
  2587. { change
  2588. mov reg1, mem1
  2589. test/cmp x, mem1
  2590. to
  2591. mov reg1, mem1
  2592. test/cmp x, reg1
  2593. }
  2594. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2595. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2596. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2597. exit;
  2598. end;
  2599. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2600. { If the flags register is in use, don't change the instruction to an
  2601. ADD otherwise this will scramble the flags. [Kit] }
  2602. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2603. begin
  2604. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2605. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2606. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2607. ) or
  2608. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2609. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2610. )
  2611. ) then
  2612. { mov reg1,ref
  2613. lea reg2,[reg1,reg2]
  2614. to
  2615. add reg2,ref}
  2616. begin
  2617. TransferUsedRegs(TmpUsedRegs);
  2618. { reg1 may not be used afterwards }
  2619. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  2620. begin
  2621. Taicpu(hp1).opcode:=A_ADD;
  2622. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  2623. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  2624. RemoveCurrentp(p, hp1);
  2625. result:=true;
  2626. exit;
  2627. end;
  2628. end;
  2629. { If the LEA instruction can be converted into an arithmetic instruction,
  2630. it may be possible to then fold it in the next optimisation, otherwise
  2631. there's nothing more that can be optimised here. }
  2632. if not ConvertLEA(taicpu(hp1)) then
  2633. Exit;
  2634. end;
  2635. if (taicpu(p).oper[1]^.typ = top_reg) and
  2636. (hp1.typ = ait_instruction) and
  2637. GetNextInstruction(hp1, hp2) and
  2638. MatchInstruction(hp2,A_MOV,[]) and
  2639. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  2640. (
  2641. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  2642. {$ifdef x86_64}
  2643. or
  2644. (
  2645. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  2646. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  2647. )
  2648. {$endif x86_64}
  2649. ) then
  2650. begin
  2651. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2652. (taicpu(hp2).oper[0]^.typ=top_reg) then
  2653. { change movsX/movzX reg/ref, reg2
  2654. add/sub/or/... reg3/$const, reg2
  2655. mov reg2 reg/ref
  2656. dealloc reg2
  2657. to
  2658. add/sub/or/... reg3/$const, reg/ref }
  2659. begin
  2660. TransferUsedRegs(TmpUsedRegs);
  2661. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2662. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2663. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2664. begin
  2665. { by example:
  2666. movswl %si,%eax movswl %si,%eax p
  2667. decl %eax addl %edx,%eax hp1
  2668. movw %ax,%si movw %ax,%si hp2
  2669. ->
  2670. movswl %si,%eax movswl %si,%eax p
  2671. decw %eax addw %edx,%eax hp1
  2672. movw %ax,%si movw %ax,%si hp2
  2673. }
  2674. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  2675. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2676. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2677. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2678. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2679. {
  2680. ->
  2681. movswl %si,%eax movswl %si,%eax p
  2682. decw %si addw %dx,%si hp1
  2683. movw %ax,%si movw %ax,%si hp2
  2684. }
  2685. case taicpu(hp1).ops of
  2686. 1:
  2687. begin
  2688. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2689. if taicpu(hp1).oper[0]^.typ=top_reg then
  2690. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2691. end;
  2692. 2:
  2693. begin
  2694. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2695. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2696. (taicpu(hp1).opcode<>A_SHL) and
  2697. (taicpu(hp1).opcode<>A_SHR) and
  2698. (taicpu(hp1).opcode<>A_SAR) then
  2699. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2700. end;
  2701. else
  2702. internalerror(2008042701);
  2703. end;
  2704. {
  2705. ->
  2706. decw %si addw %dx,%si p
  2707. }
  2708. RemoveInstruction(hp2);
  2709. RemoveCurrentP(p, hp1);
  2710. Result:=True;
  2711. Exit;
  2712. end;
  2713. end;
  2714. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2715. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  2716. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  2717. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  2718. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  2719. )
  2720. {$ifdef i386}
  2721. { byte registers of esi, edi, ebp, esp are not available on i386 }
  2722. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2723. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2724. {$endif i386}
  2725. then
  2726. { change movsX/movzX reg/ref, reg2
  2727. add/sub/or/... regX/$const, reg2
  2728. mov reg2, reg3
  2729. dealloc reg2
  2730. to
  2731. movsX/movzX reg/ref, reg3
  2732. add/sub/or/... reg3/$const, reg3
  2733. }
  2734. begin
  2735. TransferUsedRegs(TmpUsedRegs);
  2736. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2737. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2738. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2739. begin
  2740. { by example:
  2741. movswl %si,%eax movswl %si,%eax p
  2742. decl %eax addl %edx,%eax hp1
  2743. movw %ax,%si movw %ax,%si hp2
  2744. ->
  2745. movswl %si,%eax movswl %si,%eax p
  2746. decw %eax addw %edx,%eax hp1
  2747. movw %ax,%si movw %ax,%si hp2
  2748. }
  2749. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  2750. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2751. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2752. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2753. { limit size of constants as well to avoid assembler errors, but
  2754. check opsize to avoid overflow when left shifting the 1 }
  2755. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  2756. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  2757. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2758. taicpu(p).changeopsize(taicpu(hp2).opsize);
  2759. if taicpu(p).oper[0]^.typ=top_reg then
  2760. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2761. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  2762. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  2763. {
  2764. ->
  2765. movswl %si,%eax movswl %si,%eax p
  2766. decw %si addw %dx,%si hp1
  2767. movw %ax,%si movw %ax,%si hp2
  2768. }
  2769. case taicpu(hp1).ops of
  2770. 1:
  2771. begin
  2772. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2773. if taicpu(hp1).oper[0]^.typ=top_reg then
  2774. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2775. end;
  2776. 2:
  2777. begin
  2778. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2779. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2780. (taicpu(hp1).opcode<>A_SHL) and
  2781. (taicpu(hp1).opcode<>A_SHR) and
  2782. (taicpu(hp1).opcode<>A_SAR) then
  2783. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2784. end;
  2785. else
  2786. internalerror(2018111801);
  2787. end;
  2788. {
  2789. ->
  2790. decw %si addw %dx,%si p
  2791. }
  2792. RemoveInstruction(hp2);
  2793. end;
  2794. end;
  2795. end;
  2796. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  2797. GetNextInstruction(hp1, hp2) and
  2798. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  2799. MatchOperand(Taicpu(p).oper[0]^,0) and
  2800. (Taicpu(p).oper[1]^.typ = top_reg) and
  2801. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  2802. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  2803. { mov reg1,0
  2804. bts reg1,operand1 --> mov reg1,operand2
  2805. or reg1,operand2 bts reg1,operand1}
  2806. begin
  2807. Taicpu(hp2).opcode:=A_MOV;
  2808. asml.remove(hp1);
  2809. insertllitem(hp2,hp2.next,hp1);
  2810. RemoveCurrentp(p, hp1);
  2811. Result:=true;
  2812. exit;
  2813. end;
  2814. end;
  2815. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  2816. var
  2817. hp1 : tai;
  2818. begin
  2819. Result:=false;
  2820. if taicpu(p).ops <> 2 then
  2821. exit;
  2822. if GetNextInstruction(p,hp1) and
  2823. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  2824. (taicpu(hp1).ops = 2) then
  2825. begin
  2826. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2827. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2828. { movXX reg1, mem1 or movXX mem1, reg1
  2829. movXX mem2, reg2 movXX reg2, mem2}
  2830. begin
  2831. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2832. { movXX reg1, mem1 or movXX mem1, reg1
  2833. movXX mem2, reg1 movXX reg2, mem1}
  2834. begin
  2835. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2836. begin
  2837. { Removes the second statement from
  2838. movXX reg1, mem1/reg2
  2839. movXX mem1/reg2, reg1
  2840. }
  2841. if taicpu(p).oper[0]^.typ=top_reg then
  2842. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2843. { Removes the second statement from
  2844. movXX mem1/reg1, reg2
  2845. movXX reg2, mem1/reg1
  2846. }
  2847. if (taicpu(p).oper[1]^.typ=top_reg) and
  2848. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  2849. begin
  2850. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  2851. RemoveInstruction(hp1);
  2852. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  2853. end
  2854. else
  2855. begin
  2856. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  2857. RemoveInstruction(hp1);
  2858. end;
  2859. Result:=true;
  2860. exit;
  2861. end
  2862. end;
  2863. end;
  2864. end;
  2865. end;
  2866. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  2867. var
  2868. hp1 : tai;
  2869. begin
  2870. result:=false;
  2871. { replace
  2872. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  2873. MovX %mreg2,%mreg1
  2874. dealloc %mreg2
  2875. by
  2876. <Op>X %mreg2,%mreg1
  2877. ?
  2878. }
  2879. if GetNextInstruction(p,hp1) and
  2880. { we mix single and double opperations here because we assume that the compiler
  2881. generates vmovapd only after double operations and vmovaps only after single operations }
  2882. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  2883. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2884. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2885. (taicpu(p).oper[0]^.typ=top_reg) then
  2886. begin
  2887. TransferUsedRegs(TmpUsedRegs);
  2888. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2889. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2890. begin
  2891. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  2892. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2893. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  2894. RemoveInstruction(hp1);
  2895. result:=true;
  2896. end;
  2897. end;
  2898. end;
  2899. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  2900. var
  2901. hp1, hp2, hp3: tai;
  2902. l : ASizeInt;
  2903. ref: Integer;
  2904. saveref: treference;
  2905. TempReg: TRegister;
  2906. Multiple: TCGInt;
  2907. begin
  2908. Result:=false;
  2909. { removes seg register prefixes from LEA operations, as they
  2910. don't do anything}
  2911. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  2912. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  2913. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2914. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  2915. { do not mess with leas acessing the stack pointer }
  2916. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  2917. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  2918. begin
  2919. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  2920. begin
  2921. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  2922. begin
  2923. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  2924. taicpu(p).oper[1]^.reg);
  2925. InsertLLItem(p.previous,p.next, hp1);
  2926. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  2927. p.free;
  2928. p:=hp1;
  2929. end
  2930. else
  2931. begin
  2932. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  2933. RemoveCurrentP(p);
  2934. end;
  2935. Result:=true;
  2936. exit;
  2937. end
  2938. else if (
  2939. { continue to use lea to adjust the stack pointer,
  2940. it is the recommended way, but only if not optimizing for size }
  2941. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  2942. (cs_opt_size in current_settings.optimizerswitches)
  2943. ) and
  2944. { If the flags register is in use, don't change the instruction
  2945. to an ADD otherwise this will scramble the flags. [Kit] }
  2946. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  2947. ConvertLEA(taicpu(p)) then
  2948. begin
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. end;
  2953. if GetNextInstruction(p,hp1) and
  2954. (hp1.typ=ait_instruction) then
  2955. begin
  2956. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  2957. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2958. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  2959. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  2960. begin
  2961. TransferUsedRegs(TmpUsedRegs);
  2962. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2963. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2964. begin
  2965. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2966. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  2967. RemoveInstruction(hp1);
  2968. result:=true;
  2969. exit;
  2970. end;
  2971. end;
  2972. { changes
  2973. lea <ref1>, reg1
  2974. <op> ...,<ref. with reg1>,...
  2975. to
  2976. <op> ...,<ref1>,... }
  2977. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  2978. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  2979. not(MatchInstruction(hp1,A_LEA,[])) then
  2980. begin
  2981. { find a reference which uses reg1 }
  2982. 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
  2983. ref:=0
  2984. 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
  2985. ref:=1
  2986. else
  2987. ref:=-1;
  2988. if (ref<>-1) and
  2989. { reg1 must be either the base or the index }
  2990. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  2991. begin
  2992. { reg1 can be removed from the reference }
  2993. saveref:=taicpu(hp1).oper[ref]^.ref^;
  2994. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  2995. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  2996. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  2997. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  2998. else
  2999. Internalerror(2019111201);
  3000. { check if the can insert all data of the lea into the second instruction }
  3001. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3002. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3003. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3004. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3005. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3006. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3007. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3008. {$ifdef x86_64}
  3009. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3010. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3011. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3012. )
  3013. {$endif x86_64}
  3014. then
  3015. begin
  3016. { reg1 might not used by the second instruction after it is remove from the reference }
  3017. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3018. begin
  3019. TransferUsedRegs(TmpUsedRegs);
  3020. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3021. { reg1 is not updated so it might not be used afterwards }
  3022. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3023. begin
  3024. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3025. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3026. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3027. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3028. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3029. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3030. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3031. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3032. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3033. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3034. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3035. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3036. RemoveCurrentP(p, hp1);
  3037. result:=true;
  3038. exit;
  3039. end
  3040. end;
  3041. end;
  3042. { recover }
  3043. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3044. end;
  3045. end;
  3046. end;
  3047. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3048. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3049. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3050. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3051. begin
  3052. { changes
  3053. lea offset1(regX), reg1
  3054. lea offset2(reg1), reg1
  3055. to
  3056. lea offset1+offset2(regX), reg1 }
  3057. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3058. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) and
  3059. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  3060. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  3061. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  3062. (((taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg) and
  3063. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3064. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  3065. (taicpu(p).oper[0]^.ref^.index=taicpu(hp1).oper[0]^.ref^.index) and
  3066. (taicpu(p).oper[0]^.ref^.scalefactor=taicpu(hp1).oper[0]^.ref^.scalefactor)
  3067. ) or
  3068. ((taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg) and
  3069. (taicpu(p).oper[0]^.ref^.index=NR_NO)
  3070. ) or
  3071. ((taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg) and
  3072. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3073. (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  3074. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1)))
  3075. ) and
  3076. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1)) and
  3077. (taicpu(p).oper[0]^.ref^.relsymbol=taicpu(hp1).oper[0]^.ref^.relsymbol) and
  3078. (taicpu(p).oper[0]^.ref^.segment=taicpu(hp1).oper[0]^.ref^.segment) and
  3079. (taicpu(p).oper[0]^.ref^.symbol=taicpu(hp1).oper[0]^.ref^.symbol) then
  3080. begin
  3081. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea done',p);
  3082. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3083. begin
  3084. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3085. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3086. { if the register is used as index and base, we have to increase for base as well
  3087. and adapt base }
  3088. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3089. begin
  3090. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3091. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3092. end;
  3093. end
  3094. else
  3095. begin
  3096. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3097. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3098. end;
  3099. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3100. begin
  3101. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3102. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3103. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3104. end;
  3105. RemoveCurrentP(p);
  3106. result:=true;
  3107. exit;
  3108. end;
  3109. { Change:
  3110. leal/q $x(%reg1),%reg2
  3111. ...
  3112. shll/q $y,%reg2
  3113. To:
  3114. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3115. }
  3116. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3117. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3118. (taicpu(hp1).oper[0]^.val <= 3) then
  3119. begin
  3120. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3121. TransferUsedRegs(TmpUsedRegs);
  3122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3123. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3124. if
  3125. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3126. (this works even if scalefactor is zero) }
  3127. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3128. { Ensure offset doesn't go out of bounds }
  3129. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3130. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3131. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3132. (
  3133. (
  3134. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3135. (
  3136. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3137. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3138. (
  3139. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3140. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3141. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3142. )
  3143. )
  3144. ) or (
  3145. (
  3146. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3147. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3148. ) and
  3149. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3150. )
  3151. ) then
  3152. begin
  3153. repeat
  3154. with taicpu(p).oper[0]^.ref^ do
  3155. begin
  3156. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3157. if index = base then
  3158. begin
  3159. if Multiple > 4 then
  3160. { Optimisation will no longer work because resultant
  3161. scale factor will exceed 8 }
  3162. Break;
  3163. base := NR_NO;
  3164. scalefactor := 2;
  3165. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3166. end
  3167. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3168. begin
  3169. { Scale factor only works on the index register }
  3170. index := base;
  3171. base := NR_NO;
  3172. end;
  3173. { For safety }
  3174. if scalefactor <= 1 then
  3175. begin
  3176. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3177. scalefactor := Multiple;
  3178. end
  3179. else
  3180. begin
  3181. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3182. scalefactor := scalefactor * Multiple;
  3183. end;
  3184. offset := offset * Multiple;
  3185. end;
  3186. RemoveInstruction(hp1);
  3187. Result := True;
  3188. Exit;
  3189. { This repeat..until loop exists for the benefit of Break }
  3190. until True;
  3191. end;
  3192. end;
  3193. end;
  3194. end;
  3195. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3196. var
  3197. hp1 : tai;
  3198. begin
  3199. DoSubAddOpt := False;
  3200. if GetLastInstruction(p, hp1) and
  3201. (hp1.typ = ait_instruction) and
  3202. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3203. case taicpu(hp1).opcode Of
  3204. A_DEC:
  3205. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3206. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3207. begin
  3208. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3209. RemoveInstruction(hp1);
  3210. end;
  3211. A_SUB:
  3212. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3213. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3214. begin
  3215. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3216. RemoveInstruction(hp1);
  3217. end;
  3218. A_ADD:
  3219. begin
  3220. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3221. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3222. begin
  3223. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3224. RemoveInstruction(hp1);
  3225. if (taicpu(p).oper[0]^.val = 0) then
  3226. begin
  3227. hp1 := tai(p.next);
  3228. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3229. if not GetLastInstruction(hp1, p) then
  3230. p := hp1;
  3231. DoSubAddOpt := True;
  3232. end
  3233. end;
  3234. end;
  3235. else
  3236. ;
  3237. end;
  3238. end;
  3239. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3240. {$ifdef i386}
  3241. var
  3242. hp1 : tai;
  3243. {$endif i386}
  3244. begin
  3245. Result:=false;
  3246. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3247. { * change "sub/add const1, reg" or "dec reg" followed by
  3248. "sub const2, reg" to one "sub ..., reg" }
  3249. if MatchOpType(taicpu(p),top_const,top_reg) then
  3250. begin
  3251. {$ifdef i386}
  3252. if (taicpu(p).oper[0]^.val = 2) and
  3253. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3254. { Don't do the sub/push optimization if the sub }
  3255. { comes from setting up the stack frame (JM) }
  3256. (not(GetLastInstruction(p,hp1)) or
  3257. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3258. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3259. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3260. begin
  3261. hp1 := tai(p.next);
  3262. while Assigned(hp1) and
  3263. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3264. not RegReadByInstruction(NR_ESP,hp1) and
  3265. not RegModifiedByInstruction(NR_ESP,hp1) do
  3266. hp1 := tai(hp1.next);
  3267. if Assigned(hp1) and
  3268. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3269. begin
  3270. taicpu(hp1).changeopsize(S_L);
  3271. if taicpu(hp1).oper[0]^.typ=top_reg then
  3272. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3273. hp1 := tai(p.next);
  3274. RemoveCurrentp(p, hp1);
  3275. Result:=true;
  3276. exit;
  3277. end;
  3278. end;
  3279. {$endif i386}
  3280. if DoSubAddOpt(p) then
  3281. Result:=true;
  3282. end;
  3283. end;
  3284. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3285. var
  3286. TmpBool1,TmpBool2 : Boolean;
  3287. tmpref : treference;
  3288. hp1,hp2: tai;
  3289. mask: tcgint;
  3290. begin
  3291. Result:=false;
  3292. { All these optimisations work on "shl/sal const,%reg" }
  3293. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3294. Exit;
  3295. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3296. (taicpu(p).oper[0]^.val <= 3) then
  3297. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3298. begin
  3299. { should we check the next instruction? }
  3300. TmpBool1 := True;
  3301. { have we found an add/sub which could be
  3302. integrated in the lea? }
  3303. TmpBool2 := False;
  3304. reference_reset(tmpref,2,[]);
  3305. TmpRef.index := taicpu(p).oper[1]^.reg;
  3306. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3307. while TmpBool1 and
  3308. GetNextInstruction(p, hp1) and
  3309. (tai(hp1).typ = ait_instruction) and
  3310. ((((taicpu(hp1).opcode = A_ADD) or
  3311. (taicpu(hp1).opcode = A_SUB)) and
  3312. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3313. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3314. (((taicpu(hp1).opcode = A_INC) or
  3315. (taicpu(hp1).opcode = A_DEC)) and
  3316. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3317. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3318. ((taicpu(hp1).opcode = A_LEA) and
  3319. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3320. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3321. (not GetNextInstruction(hp1,hp2) or
  3322. not instrReadsFlags(hp2)) Do
  3323. begin
  3324. TmpBool1 := False;
  3325. if taicpu(hp1).opcode=A_LEA then
  3326. begin
  3327. if (TmpRef.base = NR_NO) and
  3328. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3329. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3330. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3331. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3332. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3333. begin
  3334. TmpBool1 := True;
  3335. TmpBool2 := True;
  3336. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3337. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3338. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  3339. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  3340. RemoveInstruction(hp1);
  3341. end
  3342. end
  3343. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  3344. begin
  3345. TmpBool1 := True;
  3346. TmpBool2 := True;
  3347. case taicpu(hp1).opcode of
  3348. A_ADD:
  3349. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3350. A_SUB:
  3351. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3352. else
  3353. internalerror(2019050536);
  3354. end;
  3355. RemoveInstruction(hp1);
  3356. end
  3357. else
  3358. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3359. (((taicpu(hp1).opcode = A_ADD) and
  3360. (TmpRef.base = NR_NO)) or
  3361. (taicpu(hp1).opcode = A_INC) or
  3362. (taicpu(hp1).opcode = A_DEC)) then
  3363. begin
  3364. TmpBool1 := True;
  3365. TmpBool2 := True;
  3366. case taicpu(hp1).opcode of
  3367. A_ADD:
  3368. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  3369. A_INC:
  3370. inc(TmpRef.offset);
  3371. A_DEC:
  3372. dec(TmpRef.offset);
  3373. else
  3374. internalerror(2019050535);
  3375. end;
  3376. RemoveInstruction(hp1);
  3377. end;
  3378. end;
  3379. if TmpBool2
  3380. {$ifndef x86_64}
  3381. or
  3382. ((current_settings.optimizecputype < cpu_Pentium2) and
  3383. (taicpu(p).oper[0]^.val <= 3) and
  3384. not(cs_opt_size in current_settings.optimizerswitches))
  3385. {$endif x86_64}
  3386. then
  3387. begin
  3388. if not(TmpBool2) and
  3389. (taicpu(p).oper[0]^.val=1) then
  3390. begin
  3391. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3392. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  3393. end
  3394. else
  3395. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  3396. taicpu(p).oper[1]^.reg);
  3397. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  3398. InsertLLItem(p.previous, p.next, hp1);
  3399. p.free;
  3400. p := hp1;
  3401. end;
  3402. end
  3403. {$ifndef x86_64}
  3404. else if (current_settings.optimizecputype < cpu_Pentium2) then
  3405. begin
  3406. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  3407. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  3408. (unlike shl, which is only Tairable in the U pipe) }
  3409. if taicpu(p).oper[0]^.val=1 then
  3410. begin
  3411. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3412. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  3413. InsertLLItem(p.previous, p.next, hp1);
  3414. p.free;
  3415. p := hp1;
  3416. end
  3417. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  3418. "shl $3, %reg" to "lea (,%reg,8), %reg }
  3419. else if (taicpu(p).opsize = S_L) and
  3420. (taicpu(p).oper[0]^.val<= 3) then
  3421. begin
  3422. reference_reset(tmpref,2,[]);
  3423. TmpRef.index := taicpu(p).oper[1]^.reg;
  3424. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3425. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  3426. InsertLLItem(p.previous, p.next, hp1);
  3427. p.free;
  3428. p := hp1;
  3429. end;
  3430. end
  3431. {$endif x86_64}
  3432. else if
  3433. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  3434. (
  3435. (
  3436. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  3437. SetAndTest(hp1, hp2)
  3438. {$ifdef x86_64}
  3439. ) or
  3440. (
  3441. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3442. GetNextInstruction(hp1, hp2) and
  3443. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  3444. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3445. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  3446. {$endif x86_64}
  3447. )
  3448. ) and
  3449. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  3450. begin
  3451. { Change:
  3452. shl x, %reg1
  3453. mov -(1<<x), %reg2
  3454. and %reg2, %reg1
  3455. Or:
  3456. shl x, %reg1
  3457. and -(1<<x), %reg1
  3458. To just:
  3459. shl x, %reg1
  3460. Since the and operation only zeroes bits that are already zero from the shl operation
  3461. }
  3462. case taicpu(p).oper[0]^.val of
  3463. 8:
  3464. mask:=$FFFFFFFFFFFFFF00;
  3465. 16:
  3466. mask:=$FFFFFFFFFFFF0000;
  3467. 32:
  3468. mask:=$FFFFFFFF00000000;
  3469. 63:
  3470. { Constant pre-calculated to prevent overflow errors with Int64 }
  3471. mask:=$8000000000000000;
  3472. else
  3473. begin
  3474. if taicpu(p).oper[0]^.val >= 64 then
  3475. { Shouldn't happen realistically, since the register
  3476. is guaranteed to be set to zero at this point }
  3477. mask := 0
  3478. else
  3479. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  3480. end;
  3481. end;
  3482. if taicpu(hp1).oper[0]^.val = mask then
  3483. begin
  3484. { Everything checks out, perform the optimisation, as long as
  3485. the FLAGS register isn't being used}
  3486. TransferUsedRegs(TmpUsedRegs);
  3487. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3488. {$ifdef x86_64}
  3489. if (hp1 <> hp2) then
  3490. begin
  3491. { "shl/mov/and" version }
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3493. { Don't do the optimisation if the FLAGS register is in use }
  3494. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  3495. begin
  3496. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  3497. { Don't remove the 'mov' instruction if its register is used elsewhere }
  3498. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3499. begin
  3500. RemoveInstruction(hp1);
  3501. Result := True;
  3502. end;
  3503. { Only set Result to True if the 'mov' instruction was removed }
  3504. RemoveInstruction(hp2);
  3505. end;
  3506. end
  3507. else
  3508. {$endif x86_64}
  3509. begin
  3510. { "shl/and" version }
  3511. { Don't do the optimisation if the FLAGS register is in use }
  3512. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3513. begin
  3514. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  3515. RemoveInstruction(hp1);
  3516. Result := True;
  3517. end;
  3518. end;
  3519. Exit;
  3520. end
  3521. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  3522. begin
  3523. { Even if the mask doesn't allow for its removal, we might be
  3524. able to optimise the mask for the "shl/and" version, which
  3525. may permit other peephole optimisations }
  3526. {$ifdef DEBUG_AOPTCPU}
  3527. mask := taicpu(hp1).oper[0]^.val and mask;
  3528. if taicpu(hp1).oper[0]^.val <> mask then
  3529. begin
  3530. DebugMsg(
  3531. SPeepholeOptimization +
  3532. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  3533. ' to $' + debug_tostr(mask) +
  3534. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  3535. taicpu(hp1).oper[0]^.val := mask;
  3536. end;
  3537. {$else DEBUG_AOPTCPU}
  3538. { If debugging is off, just set the operand even if it's the same }
  3539. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  3540. {$endif DEBUG_AOPTCPU}
  3541. end;
  3542. end;
  3543. end;
  3544. function TX86AsmOptimizer.OptPass1SETcc(var p: tai): boolean;
  3545. var
  3546. hp1,hp2,next: tai; SetC, JumpC: TAsmCond; Unconditional: Boolean;
  3547. begin
  3548. Result:=false;
  3549. if MatchOpType(taicpu(p),top_reg) and
  3550. GetNextInstruction(p, hp1) and
  3551. ((MatchInstruction(hp1, A_TEST, [S_B]) and
  3552. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3553. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg)) or
  3554. (MatchInstruction(hp1, A_CMP, [S_B]) and
  3555. MatchOpType(taicpu(hp1),top_const,top_reg) and
  3556. (taicpu(hp1).oper[0]^.val=0))
  3557. ) and
  3558. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  3559. GetNextInstruction(hp1, hp2) and
  3560. MatchInstruction(hp2, A_Jcc, []) then
  3561. { Change from: To:
  3562. set(C) %reg j(~C) label
  3563. test %reg,%reg/cmp $0,%reg
  3564. je label
  3565. set(C) %reg j(C) label
  3566. test %reg,%reg/cmp $0,%reg
  3567. jne label
  3568. }
  3569. begin
  3570. next := tai(p.Next);
  3571. TransferUsedRegs(TmpUsedRegs);
  3572. UpdateUsedRegs(TmpUsedRegs, next);
  3573. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3574. JumpC := taicpu(hp2).condition;
  3575. Unconditional := False;
  3576. if conditions_equal(JumpC, C_E) then
  3577. SetC := inverse_cond(taicpu(p).condition)
  3578. else if conditions_equal(JumpC, C_NE) then
  3579. SetC := taicpu(p).condition
  3580. else
  3581. { We've got something weird here (and inefficent) }
  3582. begin
  3583. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  3584. SetC := C_NONE;
  3585. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  3586. if condition_in(C_AE, JumpC) then
  3587. Unconditional := True
  3588. else
  3589. { Not sure what to do with this jump - drop out }
  3590. Exit;
  3591. end;
  3592. RemoveInstruction(hp1);
  3593. if Unconditional then
  3594. MakeUnconditional(taicpu(hp2))
  3595. else
  3596. begin
  3597. if SetC = C_NONE then
  3598. InternalError(2018061402);
  3599. taicpu(hp2).SetCondition(SetC);
  3600. end;
  3601. if not RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs) then
  3602. begin
  3603. RemoveCurrentp(p, hp2);
  3604. Result := True;
  3605. end;
  3606. DebugMsg(SPeepholeOptimization + 'SETcc/TESTCmp/Jcc -> Jcc',p);
  3607. end;
  3608. end;
  3609. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  3610. { returns true if a "continue" should be done after this optimization }
  3611. var
  3612. hp1, hp2: tai;
  3613. begin
  3614. Result := false;
  3615. if MatchOpType(taicpu(p),top_ref) and
  3616. GetNextInstruction(p, hp1) and
  3617. (hp1.typ = ait_instruction) and
  3618. (((taicpu(hp1).opcode = A_FLD) and
  3619. (taicpu(p).opcode = A_FSTP)) or
  3620. ((taicpu(p).opcode = A_FISTP) and
  3621. (taicpu(hp1).opcode = A_FILD))) and
  3622. MatchOpType(taicpu(hp1),top_ref) and
  3623. (taicpu(hp1).opsize = taicpu(p).opsize) and
  3624. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  3625. begin
  3626. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  3627. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  3628. GetNextInstruction(hp1, hp2) and
  3629. (hp2.typ = ait_instruction) and
  3630. IsExitCode(hp2) and
  3631. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  3632. not(assigned(current_procinfo.procdef.funcretsym) and
  3633. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  3634. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  3635. begin
  3636. RemoveInstruction(hp1);
  3637. RemoveCurrentP(p, hp2);
  3638. RemoveLastDeallocForFuncRes(p);
  3639. Result := true;
  3640. end
  3641. else
  3642. { we can do this only in fast math mode as fstp is rounding ...
  3643. ... still disabled as it breaks the compiler and/or rtl }
  3644. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  3645. { ... or if another fstp equal to the first one follows }
  3646. (GetNextInstruction(hp1,hp2) and
  3647. (hp2.typ = ait_instruction) and
  3648. (taicpu(p).opcode=taicpu(hp2).opcode) and
  3649. (taicpu(p).opsize=taicpu(hp2).opsize))
  3650. ) and
  3651. { fst can't store an extended/comp value }
  3652. (taicpu(p).opsize <> S_FX) and
  3653. (taicpu(p).opsize <> S_IQ) then
  3654. begin
  3655. if (taicpu(p).opcode = A_FSTP) then
  3656. taicpu(p).opcode := A_FST
  3657. else
  3658. taicpu(p).opcode := A_FIST;
  3659. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  3660. RemoveInstruction(hp1);
  3661. end;
  3662. end;
  3663. end;
  3664. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  3665. var
  3666. hp1, hp2: tai;
  3667. begin
  3668. result:=false;
  3669. if MatchOpType(taicpu(p),top_reg) and
  3670. GetNextInstruction(p, hp1) and
  3671. (hp1.typ = Ait_Instruction) and
  3672. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3673. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  3674. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  3675. { change to
  3676. fld reg fxxx reg,st
  3677. fxxxp st, st1 (hp1)
  3678. Remark: non commutative operations must be reversed!
  3679. }
  3680. begin
  3681. case taicpu(hp1).opcode Of
  3682. A_FMULP,A_FADDP,
  3683. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  3684. begin
  3685. case taicpu(hp1).opcode Of
  3686. A_FADDP: taicpu(hp1).opcode := A_FADD;
  3687. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  3688. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  3689. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  3690. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  3691. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  3692. else
  3693. internalerror(2019050534);
  3694. end;
  3695. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  3696. taicpu(hp1).oper[1]^.reg := NR_ST;
  3697. RemoveCurrentP(p, hp1);
  3698. Result:=true;
  3699. exit;
  3700. end;
  3701. else
  3702. ;
  3703. end;
  3704. end
  3705. else
  3706. if MatchOpType(taicpu(p),top_ref) and
  3707. GetNextInstruction(p, hp2) and
  3708. (hp2.typ = Ait_Instruction) and
  3709. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3710. (taicpu(p).opsize in [S_FS, S_FL]) and
  3711. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  3712. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  3713. if GetLastInstruction(p, hp1) and
  3714. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  3715. MatchOpType(taicpu(hp1),top_ref) and
  3716. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  3717. if ((taicpu(hp2).opcode = A_FMULP) or
  3718. (taicpu(hp2).opcode = A_FADDP)) then
  3719. { change to
  3720. fld/fst mem1 (hp1) fld/fst mem1
  3721. fld mem1 (p) fadd/
  3722. faddp/ fmul st, st
  3723. fmulp st, st1 (hp2) }
  3724. begin
  3725. RemoveCurrentP(p, hp1);
  3726. if (taicpu(hp2).opcode = A_FADDP) then
  3727. taicpu(hp2).opcode := A_FADD
  3728. else
  3729. taicpu(hp2).opcode := A_FMUL;
  3730. taicpu(hp2).oper[1]^.reg := NR_ST;
  3731. end
  3732. else
  3733. { change to
  3734. fld/fst mem1 (hp1) fld/fst mem1
  3735. fld mem1 (p) fld st}
  3736. begin
  3737. taicpu(p).changeopsize(S_FL);
  3738. taicpu(p).loadreg(0,NR_ST);
  3739. end
  3740. else
  3741. begin
  3742. case taicpu(hp2).opcode Of
  3743. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  3744. { change to
  3745. fld/fst mem1 (hp1) fld/fst mem1
  3746. fld mem2 (p) fxxx mem2
  3747. fxxxp st, st1 (hp2) }
  3748. begin
  3749. case taicpu(hp2).opcode Of
  3750. A_FADDP: taicpu(p).opcode := A_FADD;
  3751. A_FMULP: taicpu(p).opcode := A_FMUL;
  3752. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  3753. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  3754. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  3755. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  3756. else
  3757. internalerror(2019050533);
  3758. end;
  3759. RemoveInstruction(hp2);
  3760. end
  3761. else
  3762. ;
  3763. end
  3764. end
  3765. end;
  3766. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  3767. var
  3768. v: TCGInt;
  3769. hp1, hp2: tai;
  3770. begin
  3771. Result:=false;
  3772. if taicpu(p).oper[0]^.typ = top_const then
  3773. begin
  3774. { Though GetNextInstruction can be factored out, it is an expensive
  3775. call, so delay calling it until we have first checked cheaper
  3776. conditions that are independent of it. }
  3777. if (taicpu(p).oper[0]^.val = 0) and
  3778. (taicpu(p).oper[1]^.typ = top_reg) and
  3779. GetNextInstruction(p, hp1) and
  3780. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  3781. begin
  3782. hp2 := p;
  3783. { When dealing with "cmp $0,%reg", only ZF and SF contain
  3784. anything meaningful once it's converted to "test %reg,%reg";
  3785. additionally, some jumps will always (or never) branch, so
  3786. evaluate every jump immediately following the
  3787. comparison, optimising the conditions if possible.
  3788. Similarly with SETcc... those that are always set to 0 or 1
  3789. are changed to MOV instructions }
  3790. while GetNextInstruction(hp2, hp1) and
  3791. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) do
  3792. begin
  3793. case taicpu(hp1).condition of
  3794. C_B, C_C, C_NAE, C_O:
  3795. { For B/NAE:
  3796. Will never branch since an unsigned integer can never be below zero
  3797. For C/O:
  3798. Result cannot overflow because 0 is being subtracted
  3799. }
  3800. begin
  3801. if taicpu(hp1).opcode = A_Jcc then
  3802. begin
  3803. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  3804. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  3805. RemoveInstruction(hp1);
  3806. { Since hp1 was deleted, hp2 must not be updated }
  3807. Continue;
  3808. end
  3809. else
  3810. begin
  3811. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  3812. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3813. taicpu(hp1).opcode := A_MOV;
  3814. taicpu(hp1).ops := 2;
  3815. taicpu(hp1).condition := C_None;
  3816. taicpu(hp1).opsize := S_B;
  3817. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  3818. taicpu(hp1).loadconst(0, 0);
  3819. end;
  3820. end;
  3821. C_BE, C_NA:
  3822. begin
  3823. { Will only branch if equal to zero }
  3824. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  3825. taicpu(hp1).condition := C_E;
  3826. end;
  3827. C_A, C_NBE:
  3828. begin
  3829. { Will only branch if not equal to zero }
  3830. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  3831. taicpu(hp1).condition := C_NE;
  3832. end;
  3833. C_AE, C_NB, C_NC, C_NO:
  3834. begin
  3835. { Will always branch }
  3836. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  3837. if taicpu(hp1).opcode = A_Jcc then
  3838. begin
  3839. MakeUnconditional(taicpu(hp1));
  3840. { Any jumps/set that follow will now be dead code }
  3841. RemoveDeadCodeAfterJump(taicpu(hp1));
  3842. Break;
  3843. end
  3844. else
  3845. begin
  3846. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3847. taicpu(hp1).opcode := A_MOV;
  3848. taicpu(hp1).ops := 2;
  3849. taicpu(hp1).condition := C_None;
  3850. taicpu(hp1).opsize := S_B;
  3851. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  3852. taicpu(hp1).loadconst(0, 1);
  3853. end;
  3854. end;
  3855. C_None:
  3856. InternalError(2020012201);
  3857. C_P, C_PE, C_NP, C_PO:
  3858. { We can't handle parity checks and they should never be generated
  3859. after a general-purpose CMP (it's used in some floating-point
  3860. comparisons that don't use CMP) }
  3861. InternalError(2020012202);
  3862. else
  3863. { Zero/Equality, Sign, their complements and all of the
  3864. signed comparisons do not need to be converted };
  3865. end;
  3866. hp2 := hp1;
  3867. end;
  3868. { Convert the instruction to a TEST }
  3869. taicpu(p).opcode := A_TEST;
  3870. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  3871. Result := True;
  3872. Exit;
  3873. end
  3874. else if (taicpu(p).oper[0]^.val = 1) and
  3875. GetNextInstruction(p, hp1) and
  3876. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  3877. (taicpu(hp1).condition in [C_L, C_NGE]) then
  3878. begin
  3879. { Convert; To:
  3880. cmp $1,r/m cmp $0,r/m
  3881. jl @lbl jle @lbl
  3882. }
  3883. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  3884. taicpu(p).oper[0]^.val := 0;
  3885. taicpu(hp1).condition := C_LE;
  3886. { If the instruction is now "cmp $0,%reg", convert it to a
  3887. TEST (and effectively do the work of the "cmp $0,%reg" in
  3888. the block above)
  3889. If it's a reference, we can get away with not setting
  3890. Result to True because he haven't evaluated the jump
  3891. in this pass yet.
  3892. }
  3893. if (taicpu(p).oper[1]^.typ = top_reg) then
  3894. begin
  3895. taicpu(p).opcode := A_TEST;
  3896. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  3897. Result := True;
  3898. end;
  3899. Exit;
  3900. end
  3901. else if (taicpu(p).oper[1]^.typ = top_reg) then
  3902. begin
  3903. { cmp register,$8000 neg register
  3904. je target --> jo target
  3905. .... only if register is deallocated before jump.}
  3906. case Taicpu(p).opsize of
  3907. S_B: v:=$80;
  3908. S_W: v:=$8000;
  3909. S_L: v:=qword($80000000);
  3910. { S_Q will never happen: cmp with 64 bit constants is not possible }
  3911. S_Q:
  3912. Exit;
  3913. else
  3914. internalerror(2013112905);
  3915. end;
  3916. if (taicpu(p).oper[0]^.val=v) and
  3917. GetNextInstruction(p, hp1) and
  3918. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  3919. (Taicpu(hp1).condition in [C_E,C_NE]) then
  3920. begin
  3921. TransferUsedRegs(TmpUsedRegs);
  3922. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3923. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  3924. begin
  3925. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  3926. Taicpu(p).opcode:=A_NEG;
  3927. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  3928. Taicpu(p).clearop(1);
  3929. Taicpu(p).ops:=1;
  3930. if Taicpu(hp1).condition=C_E then
  3931. Taicpu(hp1).condition:=C_O
  3932. else
  3933. Taicpu(hp1).condition:=C_NO;
  3934. Result:=true;
  3935. exit;
  3936. end;
  3937. end;
  3938. end;
  3939. end;
  3940. end;
  3941. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  3942. var
  3943. hp1: tai;
  3944. begin
  3945. {
  3946. remove the second (v)pxor from
  3947. pxor reg,reg
  3948. ...
  3949. pxor reg,reg
  3950. }
  3951. Result:=false;
  3952. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  3953. MatchOpType(taicpu(p),top_reg,top_reg) and
  3954. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  3955. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3956. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  3957. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  3958. begin
  3959. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  3960. RemoveInstruction(hp1);
  3961. Result:=true;
  3962. Exit;
  3963. end
  3964. {
  3965. replace
  3966. pxor reg1,reg1
  3967. movapd/s reg1,reg2
  3968. dealloc reg1
  3969. by
  3970. pxor reg2,reg2
  3971. }
  3972. else if GetNextInstruction(p,hp1) and
  3973. { we mix single and double opperations here because we assume that the compiler
  3974. generates vmovapd only after double operations and vmovaps only after single operations }
  3975. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3976. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  3977. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3978. (taicpu(p).oper[0]^.typ=top_reg) then
  3979. begin
  3980. TransferUsedRegs(TmpUsedRegs);
  3981. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3982. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3983. begin
  3984. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  3985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3986. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  3987. RemoveInstruction(hp1);
  3988. result:=true;
  3989. end;
  3990. end;
  3991. end;
  3992. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  3993. var
  3994. hp1: tai;
  3995. begin
  3996. {
  3997. remove the second (v)pxor from
  3998. (v)pxor reg,reg
  3999. ...
  4000. (v)pxor reg,reg
  4001. }
  4002. Result:=false;
  4003. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4004. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4005. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4006. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4007. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4008. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4009. begin
  4010. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4011. RemoveInstruction(hp1);
  4012. Result:=true;
  4013. Exit;
  4014. end
  4015. else
  4016. Result:=OptPass1VOP(p);
  4017. end;
  4018. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4019. var
  4020. hp1 : tai;
  4021. begin
  4022. result:=false;
  4023. { replace
  4024. IMul const,%mreg1,%mreg2
  4025. Mov %reg2,%mreg3
  4026. dealloc %mreg3
  4027. by
  4028. Imul const,%mreg1,%mreg23
  4029. }
  4030. if (taicpu(p).ops=3) and
  4031. GetNextInstruction(p,hp1) and
  4032. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4033. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4034. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4035. begin
  4036. TransferUsedRegs(TmpUsedRegs);
  4037. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4038. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4039. begin
  4040. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4041. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4042. RemoveInstruction(hp1);
  4043. result:=true;
  4044. end;
  4045. end;
  4046. end;
  4047. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  4048. function IsXCHGAcceptable: Boolean; inline;
  4049. begin
  4050. { Always accept if optimising for size }
  4051. Result := (cs_opt_size in current_settings.optimizerswitches) or
  4052. (
  4053. {$ifdef x86_64}
  4054. { XCHG takes 3 cycles on AMD Athlon64 }
  4055. (current_settings.optimizecputype >= cpu_core_i)
  4056. {$else x86_64}
  4057. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  4058. than 3, so it becomes a saving compared to three MOVs with two of
  4059. them able to execute simultaneously. [Kit] }
  4060. (current_settings.optimizecputype >= cpu_PentiumM)
  4061. {$endif x86_64}
  4062. );
  4063. end;
  4064. var
  4065. NewRef: TReference;
  4066. hp1,hp2,hp3: tai;
  4067. {$ifndef x86_64}
  4068. hp4: tai;
  4069. OperIdx: Integer;
  4070. {$endif x86_64}
  4071. begin
  4072. Result:=false;
  4073. if not GetNextInstruction(p, hp1) then
  4074. Exit;
  4075. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  4076. begin
  4077. { Sometimes the MOVs that OptPass2JMP produces can be improved
  4078. further, but we can't just put this jump optimisation in pass 1
  4079. because it tends to perform worse when conditional jumps are
  4080. nearby (e.g. when converting CMOV instructions). [Kit] }
  4081. if OptPass2JMP(hp1) then
  4082. { call OptPass1MOV once to potentially merge any MOVs that were created }
  4083. Result := OptPass1MOV(p)
  4084. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  4085. returned True and the instruction is still a MOV, thus checking
  4086. the optimisations below }
  4087. { If OptPass2JMP returned False, no optimisations were done to
  4088. the jump and there are no further optimisations that can be done
  4089. to the MOV instruction on this pass }
  4090. end
  4091. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4092. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  4093. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4094. MatchOpType(taicpu(hp1),top_const,top_reg) and
  4095. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  4096. { be lazy, checking separately for sub would be slightly better }
  4097. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  4098. begin
  4099. { Change:
  4100. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  4101. addl/q $x,%reg2 subl/q $x,%reg2
  4102. To:
  4103. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  4104. }
  4105. TransferUsedRegs(TmpUsedRegs);
  4106. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4107. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4108. if not GetNextInstruction(hp1, hp2) or
  4109. (
  4110. { The FLAGS register isn't always tracked properly, so do not
  4111. perform this optimisation if a conditional statement follows }
  4112. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  4113. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  4114. ) then
  4115. begin
  4116. reference_reset(NewRef, 1, []);
  4117. NewRef.base := taicpu(p).oper[0]^.reg;
  4118. NewRef.scalefactor := 1;
  4119. if taicpu(hp1).opcode = A_ADD then
  4120. begin
  4121. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  4122. NewRef.offset := taicpu(hp1).oper[0]^.val;
  4123. end
  4124. else
  4125. begin
  4126. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  4127. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  4128. end;
  4129. taicpu(p).opcode := A_LEA;
  4130. taicpu(p).loadref(0, NewRef);
  4131. RemoveInstruction(hp1);
  4132. Result := True;
  4133. Exit;
  4134. end;
  4135. end
  4136. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4137. {$ifdef x86_64}
  4138. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  4139. {$else x86_64}
  4140. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  4141. {$endif x86_64}
  4142. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4143. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  4144. { mov reg1, reg2 mov reg1, reg2
  4145. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  4146. begin
  4147. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4148. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  4149. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  4150. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  4151. TransferUsedRegs(TmpUsedRegs);
  4152. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4153. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  4154. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  4155. then
  4156. begin
  4157. RemoveCurrentP(p, hp1);
  4158. Result:=true;
  4159. end;
  4160. exit;
  4161. end
  4162. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4163. IsXCHGAcceptable and
  4164. { XCHG doesn't support 8-byte registers }
  4165. (taicpu(p).opsize <> S_B) and
  4166. MatchInstruction(hp1, A_MOV, []) and
  4167. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4168. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  4169. GetNextInstruction(hp1, hp2) and
  4170. MatchInstruction(hp2, A_MOV, []) and
  4171. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  4172. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  4173. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  4174. begin
  4175. { mov %reg1,%reg2
  4176. mov %reg3,%reg1 -> xchg %reg3,%reg1
  4177. mov %reg2,%reg3
  4178. (%reg2 not used afterwards)
  4179. Note that xchg takes 3 cycles to execute, and generally mov's take
  4180. only one cycle apiece, but the first two mov's can be executed in
  4181. parallel, only taking 2 cycles overall. Older processors should
  4182. therefore only optimise for size. [Kit]
  4183. }
  4184. TransferUsedRegs(TmpUsedRegs);
  4185. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4187. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  4188. begin
  4189. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  4190. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  4191. taicpu(hp1).opcode := A_XCHG;
  4192. RemoveCurrentP(p, hp1);
  4193. RemoveInstruction(hp2);
  4194. Result := True;
  4195. Exit;
  4196. end;
  4197. end
  4198. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4199. MatchInstruction(hp1, A_SAR, []) then
  4200. begin
  4201. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  4202. begin
  4203. { the use of %edx also covers the opsize being S_L }
  4204. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  4205. begin
  4206. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  4207. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  4208. (taicpu(p).oper[1]^.reg = NR_EDX) then
  4209. begin
  4210. { Change:
  4211. movl %eax,%edx
  4212. sarl $31,%edx
  4213. To:
  4214. cltd
  4215. }
  4216. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  4217. RemoveInstruction(hp1);
  4218. taicpu(p).opcode := A_CDQ;
  4219. taicpu(p).opsize := S_NO;
  4220. taicpu(p).clearop(1);
  4221. taicpu(p).clearop(0);
  4222. taicpu(p).ops:=0;
  4223. Result := True;
  4224. end
  4225. else if (cs_opt_size in current_settings.optimizerswitches) and
  4226. (taicpu(p).oper[0]^.reg = NR_EDX) and
  4227. (taicpu(p).oper[1]^.reg = NR_EAX) then
  4228. begin
  4229. { Change:
  4230. movl %edx,%eax
  4231. sarl $31,%edx
  4232. To:
  4233. movl %edx,%eax
  4234. cltd
  4235. Note that this creates a dependency between the two instructions,
  4236. so only perform if optimising for size.
  4237. }
  4238. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  4239. taicpu(hp1).opcode := A_CDQ;
  4240. taicpu(hp1).opsize := S_NO;
  4241. taicpu(hp1).clearop(1);
  4242. taicpu(hp1).clearop(0);
  4243. taicpu(hp1).ops:=0;
  4244. end;
  4245. {$ifndef x86_64}
  4246. end
  4247. { Don't bother if CMOV is supported, because a more optimal
  4248. sequence would have been generated for the Abs() intrinsic }
  4249. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  4250. { the use of %eax also covers the opsize being S_L }
  4251. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  4252. (taicpu(p).oper[0]^.reg = NR_EAX) and
  4253. (taicpu(p).oper[1]^.reg = NR_EDX) and
  4254. GetNextInstruction(hp1, hp2) and
  4255. MatchInstruction(hp2, A_XOR, [S_L]) and
  4256. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  4257. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  4258. GetNextInstruction(hp2, hp3) and
  4259. MatchInstruction(hp3, A_SUB, [S_L]) and
  4260. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  4261. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  4262. begin
  4263. { Change:
  4264. movl %eax,%edx
  4265. sarl $31,%eax
  4266. xorl %eax,%edx
  4267. subl %eax,%edx
  4268. (Instruction that uses %edx)
  4269. (%eax deallocated)
  4270. (%edx deallocated)
  4271. To:
  4272. cltd
  4273. xorl %edx,%eax <-- Note the registers have swapped
  4274. subl %edx,%eax
  4275. (Instruction that uses %eax) <-- %eax rather than %edx
  4276. }
  4277. TransferUsedRegs(TmpUsedRegs);
  4278. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4279. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4280. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  4281. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  4282. begin
  4283. if GetNextInstruction(hp3, hp4) and
  4284. not RegModifiedByInstruction(NR_EDX, hp4) and
  4285. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  4286. begin
  4287. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  4288. taicpu(p).opcode := A_CDQ;
  4289. taicpu(p).clearop(1);
  4290. taicpu(p).clearop(0);
  4291. taicpu(p).ops:=0;
  4292. RemoveInstruction(hp1);
  4293. taicpu(hp2).loadreg(0, NR_EDX);
  4294. taicpu(hp2).loadreg(1, NR_EAX);
  4295. taicpu(hp3).loadreg(0, NR_EDX);
  4296. taicpu(hp3).loadreg(1, NR_EAX);
  4297. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  4298. { Convert references in the following instruction (hp4) from %edx to %eax }
  4299. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  4300. with taicpu(hp4).oper[OperIdx]^ do
  4301. case typ of
  4302. top_reg:
  4303. if getsupreg(reg) = RS_EDX then
  4304. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4305. top_ref:
  4306. begin
  4307. if getsupreg(reg) = RS_EDX then
  4308. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4309. if getsupreg(reg) = RS_EDX then
  4310. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4311. end;
  4312. else
  4313. ;
  4314. end;
  4315. end;
  4316. end;
  4317. {$else x86_64}
  4318. end;
  4319. end
  4320. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  4321. { the use of %rdx also covers the opsize being S_Q }
  4322. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  4323. begin
  4324. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  4325. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  4326. (taicpu(p).oper[1]^.reg = NR_RDX) then
  4327. begin
  4328. { Change:
  4329. movq %rax,%rdx
  4330. sarq $63,%rdx
  4331. To:
  4332. cqto
  4333. }
  4334. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  4335. RemoveInstruction(hp1);
  4336. taicpu(p).opcode := A_CQO;
  4337. taicpu(p).opsize := S_NO;
  4338. taicpu(p).clearop(1);
  4339. taicpu(p).clearop(0);
  4340. taicpu(p).ops:=0;
  4341. Result := True;
  4342. end
  4343. else if (cs_opt_size in current_settings.optimizerswitches) and
  4344. (taicpu(p).oper[0]^.reg = NR_RDX) and
  4345. (taicpu(p).oper[1]^.reg = NR_RAX) then
  4346. begin
  4347. { Change:
  4348. movq %rdx,%rax
  4349. sarq $63,%rdx
  4350. To:
  4351. movq %rdx,%rax
  4352. cqto
  4353. Note that this creates a dependency between the two instructions,
  4354. so only perform if optimising for size.
  4355. }
  4356. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  4357. taicpu(hp1).opcode := A_CQO;
  4358. taicpu(hp1).opsize := S_NO;
  4359. taicpu(hp1).clearop(1);
  4360. taicpu(hp1).clearop(0);
  4361. taicpu(hp1).ops:=0;
  4362. {$endif x86_64}
  4363. end;
  4364. end;
  4365. end
  4366. else if MatchInstruction(hp1, A_MOV, []) and
  4367. (taicpu(hp1).oper[1]^.typ = top_reg) then
  4368. { Though "GetNextInstruction" could be factored out, along with
  4369. the instructions that depend on hp2, it is an expensive call that
  4370. should be delayed for as long as possible, hence we do cheaper
  4371. checks first that are likely to be False. [Kit] }
  4372. begin
  4373. if MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  4374. (
  4375. (
  4376. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  4377. (
  4378. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4379. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  4380. )
  4381. ) or
  4382. (
  4383. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  4384. (
  4385. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4386. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  4387. )
  4388. )
  4389. ) and
  4390. GetNextInstruction(hp1, hp2) and
  4391. MatchInstruction(hp2, A_SAR, []) and
  4392. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  4393. begin
  4394. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  4395. begin
  4396. { Change:
  4397. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  4398. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  4399. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  4400. To:
  4401. movl r/m,%eax <- Note the change in register
  4402. cltd
  4403. }
  4404. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  4405. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  4406. taicpu(p).loadreg(1, NR_EAX);
  4407. taicpu(hp1).opcode := A_CDQ;
  4408. taicpu(hp1).clearop(1);
  4409. taicpu(hp1).clearop(0);
  4410. taicpu(hp1).ops:=0;
  4411. RemoveInstruction(hp2);
  4412. (*
  4413. {$ifdef x86_64}
  4414. end
  4415. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  4416. { This code sequence does not get generated - however it might become useful
  4417. if and when 128-bit signed integer types make an appearance, so the code
  4418. is kept here for when it is eventually needed. [Kit] }
  4419. (
  4420. (
  4421. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  4422. (
  4423. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4424. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  4425. )
  4426. ) or
  4427. (
  4428. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  4429. (
  4430. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4431. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  4432. )
  4433. )
  4434. ) and
  4435. GetNextInstruction(hp1, hp2) and
  4436. MatchInstruction(hp2, A_SAR, [S_Q]) and
  4437. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  4438. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  4439. begin
  4440. { Change:
  4441. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  4442. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  4443. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  4444. To:
  4445. movq r/m,%rax <- Note the change in register
  4446. cqto
  4447. }
  4448. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  4449. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  4450. taicpu(p).loadreg(1, NR_RAX);
  4451. taicpu(hp1).opcode := A_CQO;
  4452. taicpu(hp1).clearop(1);
  4453. taicpu(hp1).clearop(0);
  4454. taicpu(hp1).ops:=0;
  4455. RemoveInstruction(hp2);
  4456. {$endif x86_64}
  4457. *)
  4458. end;
  4459. end;
  4460. {$ifdef x86_64}
  4461. end
  4462. else if (taicpu(p).opsize = S_L) and
  4463. (taicpu(p).oper[1]^.typ = top_reg) and
  4464. (
  4465. MatchInstruction(hp1, A_MOV,[]) and
  4466. (taicpu(hp1).opsize = S_L) and
  4467. (taicpu(hp1).oper[1]^.typ = top_reg)
  4468. ) and (
  4469. GetNextInstruction(hp1, hp2) and
  4470. (tai(hp2).typ=ait_instruction) and
  4471. (taicpu(hp2).opsize = S_Q) and
  4472. (
  4473. (
  4474. MatchInstruction(hp2, A_ADD,[]) and
  4475. (taicpu(hp2).opsize = S_Q) and
  4476. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  4477. (
  4478. (
  4479. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  4480. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4481. ) or (
  4482. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  4483. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  4484. )
  4485. )
  4486. ) or (
  4487. MatchInstruction(hp2, A_LEA,[]) and
  4488. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  4489. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  4490. (
  4491. (
  4492. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  4493. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4494. ) or (
  4495. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  4496. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  4497. )
  4498. ) and (
  4499. (
  4500. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4501. ) or (
  4502. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  4503. )
  4504. )
  4505. )
  4506. )
  4507. ) and (
  4508. GetNextInstruction(hp2, hp3) and
  4509. MatchInstruction(hp3, A_SHR,[]) and
  4510. (taicpu(hp3).opsize = S_Q) and
  4511. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  4512. (taicpu(hp3).oper[0]^.val = 1) and
  4513. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  4514. ) then
  4515. begin
  4516. { Change movl x, reg1d movl x, reg1d
  4517. movl y, reg2d movl y, reg2d
  4518. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  4519. shrq $1, reg1q shrq $1, reg1q
  4520. ( reg1d and reg2d can be switched around in the first two instructions )
  4521. To movl x, reg1d
  4522. addl y, reg1d
  4523. rcrl $1, reg1d
  4524. This corresponds to the common expression (x + y) shr 1, where
  4525. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  4526. smaller code, but won't account for x + y causing an overflow). [Kit]
  4527. }
  4528. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  4529. { Change first MOV command to have the same register as the final output }
  4530. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  4531. else
  4532. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  4533. { Change second MOV command to an ADD command. This is easier than
  4534. converting the existing command because it means we don't have to
  4535. touch 'y', which might be a complicated reference, and also the
  4536. fact that the third command might either be ADD or LEA. [Kit] }
  4537. taicpu(hp1).opcode := A_ADD;
  4538. { Delete old ADD/LEA instruction }
  4539. RemoveInstruction(hp2);
  4540. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  4541. taicpu(hp3).opcode := A_RCR;
  4542. taicpu(hp3).changeopsize(S_L);
  4543. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  4544. {$endif x86_64}
  4545. end;
  4546. end;
  4547. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  4548. var
  4549. hp1 : tai;
  4550. begin
  4551. Result:=false;
  4552. if (taicpu(p).ops >= 2) and
  4553. ((taicpu(p).oper[0]^.typ = top_const) or
  4554. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  4555. (taicpu(p).oper[1]^.typ = top_reg) and
  4556. ((taicpu(p).ops = 2) or
  4557. ((taicpu(p).oper[2]^.typ = top_reg) and
  4558. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  4559. GetLastInstruction(p,hp1) and
  4560. MatchInstruction(hp1,A_MOV,[]) and
  4561. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4562. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4563. begin
  4564. TransferUsedRegs(TmpUsedRegs);
  4565. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  4566. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  4567. { change
  4568. mov reg1,reg2
  4569. imul y,reg2 to imul y,reg1,reg2 }
  4570. begin
  4571. taicpu(p).ops := 3;
  4572. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  4573. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4574. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  4575. RemoveInstruction(hp1);
  4576. result:=true;
  4577. end;
  4578. end;
  4579. end;
  4580. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  4581. var
  4582. ThisLabel: TAsmLabel;
  4583. begin
  4584. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  4585. ThisLabel.decrefs;
  4586. taicpu(p).opcode := A_RET;
  4587. taicpu(p).is_jmp := false;
  4588. taicpu(p).ops := taicpu(ret_p).ops;
  4589. case taicpu(ret_p).ops of
  4590. 0:
  4591. taicpu(p).clearop(0);
  4592. 1:
  4593. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  4594. else
  4595. internalerror(2016041301);
  4596. end;
  4597. { If the original label is now dead, it might turn out that the label
  4598. immediately follows p. As a result, everything beyond it, which will
  4599. be just some final register configuration and a RET instruction, is
  4600. now dead code. [Kit] }
  4601. { NOTE: This is much faster than introducing a OptPass2RET routine and
  4602. running RemoveDeadCodeAfterJump for each RET instruction, because
  4603. this optimisation rarely happens and most RETs appear at the end of
  4604. routines where there is nothing that can be stripped. [Kit] }
  4605. if not ThisLabel.is_used then
  4606. RemoveDeadCodeAfterJump(p);
  4607. end;
  4608. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  4609. var
  4610. hp1, hp2, hp3: tai;
  4611. OperIdx: Integer;
  4612. begin
  4613. result:=false;
  4614. 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
  4615. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  4616. begin
  4617. hp1:=getlabelwithsym(tasmlabel(taicpu(p).oper[0]^.ref^.symbol));
  4618. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  4619. begin
  4620. case taicpu(hp1).opcode of
  4621. A_RET:
  4622. {
  4623. change
  4624. jmp .L1
  4625. ...
  4626. .L1:
  4627. ret
  4628. into
  4629. ret
  4630. }
  4631. begin
  4632. ConvertJumpToRET(p, hp1);
  4633. result:=true;
  4634. end;
  4635. A_MOV:
  4636. {
  4637. change
  4638. jmp .L1
  4639. ...
  4640. .L1:
  4641. mov ##, ##
  4642. ret
  4643. into
  4644. mov ##, ##
  4645. ret
  4646. }
  4647. { This optimisation tends to increase code size if the pass 1 MOV optimisations aren't
  4648. re-run, so only do this particular optimisation if optimising for speed or when
  4649. optimisations are very in-depth. [Kit] }
  4650. if (current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size] then
  4651. begin
  4652. GetNextInstruction(hp1, hp2);
  4653. if not Assigned(hp2) then
  4654. Exit;
  4655. if (hp2.typ in [ait_label, ait_align]) then
  4656. SkipLabels(hp2,hp2);
  4657. if Assigned(hp2) and MatchInstruction(hp2, A_RET, [S_NO]) then
  4658. begin
  4659. { Duplicate the MOV instruction }
  4660. hp3:=tai(hp1.getcopy);
  4661. asml.InsertBefore(hp3, p);
  4662. { Make sure the compiler knows about any final registers written here }
  4663. for OperIdx := 0 to 1 do
  4664. with taicpu(hp3).oper[OperIdx]^ do
  4665. begin
  4666. case typ of
  4667. top_ref:
  4668. begin
  4669. if (ref^.base <> NR_NO) {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64} then
  4670. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  4671. if (ref^.index <> NR_NO) {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} then
  4672. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  4673. end;
  4674. top_reg:
  4675. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  4676. else
  4677. ;
  4678. end;
  4679. end;
  4680. { Now change the jump into a RET instruction }
  4681. ConvertJumpToRET(p, hp2);
  4682. result:=true;
  4683. end;
  4684. end;
  4685. else
  4686. ;
  4687. end;
  4688. end;
  4689. end;
  4690. end;
  4691. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  4692. begin
  4693. CanBeCMOV:=assigned(p) and
  4694. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  4695. { we can't use cmov ref,reg because
  4696. ref could be nil and cmov still throws an exception
  4697. if ref=nil but the mov isn't done (FK)
  4698. or ((taicpu(p).oper[0]^.typ = top_ref) and
  4699. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  4700. }
  4701. (taicpu(p).oper[1]^.typ = top_reg) and
  4702. (
  4703. (taicpu(p).oper[0]^.typ = top_reg) or
  4704. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  4705. it is not expected that this can cause a seg. violation }
  4706. (
  4707. (taicpu(p).oper[0]^.typ = top_ref) and
  4708. IsRefSafe(taicpu(p).oper[0]^.ref)
  4709. )
  4710. );
  4711. end;
  4712. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  4713. var
  4714. hp1,hp2,hp3,hp4,hpmov2: tai;
  4715. carryadd_opcode : TAsmOp;
  4716. l : Longint;
  4717. condition : TAsmCond;
  4718. symbol: TAsmSymbol;
  4719. reg: tsuperregister;
  4720. regavailable: Boolean;
  4721. begin
  4722. result:=false;
  4723. symbol:=nil;
  4724. if GetNextInstruction(p,hp1) then
  4725. begin
  4726. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  4727. if (hp1.typ=ait_instruction) and
  4728. GetNextInstruction(hp1,hp2) and
  4729. ((hp2.typ=ait_label) or
  4730. { trick to skip align }
  4731. ((hp2.typ=ait_align) and GetNextInstruction(hp2,hp2) and (hp2.typ=ait_label))
  4732. ) and
  4733. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  4734. { jb @@1 cmc
  4735. inc/dec operand --> adc/sbb operand,0
  4736. @@1:
  4737. ... and ...
  4738. jnb @@1
  4739. inc/dec operand --> adc/sbb operand,0
  4740. @@1: }
  4741. begin
  4742. carryadd_opcode:=A_NONE;
  4743. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  4744. begin
  4745. if (Taicpu(hp1).opcode=A_INC) or
  4746. ((Taicpu(hp1).opcode=A_ADD) and
  4747. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4748. (Taicpu(hp1).oper[0]^.val=1)
  4749. ) then
  4750. carryadd_opcode:=A_ADC;
  4751. if (Taicpu(hp1).opcode=A_DEC) or
  4752. ((Taicpu(hp1).opcode=A_SUB) and
  4753. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4754. (Taicpu(hp1).oper[0]^.val=1)
  4755. ) then
  4756. carryadd_opcode:=A_SBB;
  4757. if carryadd_opcode<>A_NONE then
  4758. begin
  4759. Taicpu(p).clearop(0);
  4760. Taicpu(p).ops:=0;
  4761. Taicpu(p).is_jmp:=false;
  4762. Taicpu(p).opcode:=A_CMC;
  4763. Taicpu(p).condition:=C_NONE;
  4764. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  4765. Taicpu(hp1).ops:=2;
  4766. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  4767. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  4768. else
  4769. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  4770. Taicpu(hp1).loadconst(0,0);
  4771. Taicpu(hp1).opcode:=carryadd_opcode;
  4772. result:=true;
  4773. exit;
  4774. end;
  4775. end
  4776. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  4777. begin
  4778. if (Taicpu(hp1).opcode=A_INC) or
  4779. ((Taicpu(hp1).opcode=A_ADD) and
  4780. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4781. (Taicpu(hp1).oper[0]^.val=1)
  4782. ) then
  4783. carryadd_opcode:=A_ADC;
  4784. if (Taicpu(hp1).opcode=A_DEC) or
  4785. ((Taicpu(hp1).opcode=A_SUB) and
  4786. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4787. (Taicpu(hp1).oper[0]^.val=1)
  4788. ) then
  4789. carryadd_opcode:=A_SBB;
  4790. if carryadd_opcode<>A_NONE then
  4791. begin
  4792. Taicpu(hp1).ops:=2;
  4793. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  4794. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  4795. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  4796. else
  4797. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  4798. Taicpu(hp1).loadconst(0,0);
  4799. Taicpu(hp1).opcode:=carryadd_opcode;
  4800. RemoveCurrentP(p, hp1);
  4801. result:=true;
  4802. exit;
  4803. end;
  4804. end
  4805. {
  4806. jcc @@1 setcc tmpreg
  4807. inc/dec/add/sub operand -> (movzx tmpreg)
  4808. @@1: add/sub tmpreg,operand
  4809. While this increases code size slightly, it makes the code much faster if the
  4810. jump is unpredictable
  4811. }
  4812. else if not(cs_opt_size in current_settings.optimizerswitches) and
  4813. ((((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  4814. (Taicpu(hp1).oper[0]^.typ=top_const) and
  4815. (Taicpu(hp1).oper[1]^.typ=top_reg) and
  4816. (Taicpu(hp1).oper[0]^.val=1)) or
  4817. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  4818. ) then
  4819. begin
  4820. TransferUsedRegs(TmpUsedRegs);
  4821. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4822. { search for an available register which is volatile }
  4823. regavailable:=false;
  4824. for reg in tcpuregisterset do
  4825. begin
  4826. if (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  4827. not(reg in TmpUsedRegs[R_INTREGISTER].GetUsedRegs) and
  4828. not(RegInInstruction(newreg(R_INTREGISTER,reg,R_SUBL),hp1))
  4829. {$ifdef i386}
  4830. and (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  4831. {$endif i386}
  4832. then
  4833. begin
  4834. regavailable:=true;
  4835. break;
  4836. end;
  4837. end;
  4838. if regavailable then
  4839. begin
  4840. Taicpu(p).clearop(0);
  4841. Taicpu(p).ops:=1;
  4842. Taicpu(p).is_jmp:=false;
  4843. Taicpu(p).opcode:=A_SETcc;
  4844. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  4845. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  4846. Taicpu(p).loadreg(0,newreg(R_INTREGISTER,reg,R_SUBL));
  4847. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  4848. begin
  4849. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  4850. R_SUBW:
  4851. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,newreg(R_INTREGISTER,reg,R_SUBL),
  4852. newreg(R_INTREGISTER,reg,R_SUBW));
  4853. R_SUBD,
  4854. R_SUBQ:
  4855. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,newreg(R_INTREGISTER,reg,R_SUBL),
  4856. newreg(R_INTREGISTER,reg,R_SUBD));
  4857. else
  4858. Internalerror(2020030601);
  4859. end;
  4860. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  4861. asml.InsertAfter(hp2,p);
  4862. end;
  4863. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  4864. begin
  4865. Taicpu(hp1).ops:=2;
  4866. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  4867. end;
  4868. Taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,reg,getsubreg(Taicpu(hp1).oper[1]^.reg)));
  4869. AllocRegBetween(newreg(R_INTREGISTER,reg,getsubreg(Taicpu(hp1).oper[1]^.reg)),p,hp1,UsedRegs);
  4870. end;
  4871. end;
  4872. end;
  4873. { Detect the following:
  4874. jmp<cond> @Lbl1
  4875. jmp @Lbl2
  4876. ...
  4877. @Lbl1:
  4878. ret
  4879. Change to:
  4880. jmp<inv_cond> @Lbl2
  4881. ret
  4882. }
  4883. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  4884. begin
  4885. hp2:=getlabelwithsym(TAsmLabel(symbol));
  4886. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  4887. MatchInstruction(hp2,A_RET,[S_NO]) then
  4888. begin
  4889. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4890. { Change label address to that of the unconditional jump }
  4891. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  4892. TAsmLabel(symbol).DecRefs;
  4893. taicpu(hp1).opcode := A_RET;
  4894. taicpu(hp1).is_jmp := false;
  4895. taicpu(hp1).ops := taicpu(hp2).ops;
  4896. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  4897. case taicpu(hp2).ops of
  4898. 0:
  4899. taicpu(hp1).clearop(0);
  4900. 1:
  4901. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  4902. else
  4903. internalerror(2016041302);
  4904. end;
  4905. end;
  4906. end;
  4907. end;
  4908. {$ifndef i8086}
  4909. if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  4910. begin
  4911. { check for
  4912. jCC xxx
  4913. <several movs>
  4914. xxx:
  4915. }
  4916. l:=0;
  4917. GetNextInstruction(p, hp1);
  4918. while assigned(hp1) and
  4919. CanBeCMOV(hp1) and
  4920. { stop on labels }
  4921. not(hp1.typ=ait_label) do
  4922. begin
  4923. inc(l);
  4924. GetNextInstruction(hp1,hp1);
  4925. end;
  4926. if assigned(hp1) then
  4927. begin
  4928. if FindLabel(tasmlabel(symbol),hp1) then
  4929. begin
  4930. if (l<=4) and (l>0) then
  4931. begin
  4932. condition:=inverse_cond(taicpu(p).condition);
  4933. GetNextInstruction(p,hp1);
  4934. repeat
  4935. if not Assigned(hp1) then
  4936. InternalError(2018062900);
  4937. taicpu(hp1).opcode:=A_CMOVcc;
  4938. taicpu(hp1).condition:=condition;
  4939. UpdateUsedRegs(hp1);
  4940. GetNextInstruction(hp1,hp1);
  4941. until not(CanBeCMOV(hp1));
  4942. { Remember what hp1 is in case there's multiple aligns to get rid of }
  4943. hp2 := hp1;
  4944. repeat
  4945. if not Assigned(hp2) then
  4946. InternalError(2018062910);
  4947. case hp2.typ of
  4948. ait_label:
  4949. { What we expected - break out of the loop (it won't be a dead label at the top of
  4950. a cluster because that was optimised at an earlier stage) }
  4951. Break;
  4952. ait_align:
  4953. { Go to the next entry until a label is found (may be multiple aligns before it) }
  4954. begin
  4955. hp2 := tai(hp2.Next);
  4956. Continue;
  4957. end;
  4958. else
  4959. begin
  4960. { Might be a comment or temporary allocation entry }
  4961. if not (hp2.typ in SkipInstr) then
  4962. InternalError(2018062911);
  4963. hp2 := tai(hp2.Next);
  4964. Continue;
  4965. end;
  4966. end;
  4967. until False;
  4968. { Now we can safely decrement the reference count }
  4969. tasmlabel(symbol).decrefs;
  4970. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  4971. { Remove the original jump }
  4972. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4973. GetNextInstruction(hp2, p); { Instruction after the label }
  4974. { Remove the label if this is its final reference }
  4975. if (tasmlabel(symbol).getrefs=0) then
  4976. StripLabelFast(hp1);
  4977. if Assigned(p) then
  4978. begin
  4979. UpdateUsedRegs(p);
  4980. result:=true;
  4981. end;
  4982. exit;
  4983. end;
  4984. end
  4985. else
  4986. begin
  4987. { check further for
  4988. jCC xxx
  4989. <several movs 1>
  4990. jmp yyy
  4991. xxx:
  4992. <several movs 2>
  4993. yyy:
  4994. }
  4995. { hp2 points to jmp yyy }
  4996. hp2:=hp1;
  4997. { skip hp1 to xxx (or an align right before it) }
  4998. GetNextInstruction(hp1, hp1);
  4999. if assigned(hp2) and
  5000. assigned(hp1) and
  5001. (l<=3) and
  5002. (hp2.typ=ait_instruction) and
  5003. (taicpu(hp2).is_jmp) and
  5004. (taicpu(hp2).condition=C_None) and
  5005. { real label and jump, no further references to the
  5006. label are allowed }
  5007. (tasmlabel(symbol).getrefs=1) and
  5008. FindLabel(tasmlabel(symbol),hp1) then
  5009. begin
  5010. l:=0;
  5011. { skip hp1 to <several moves 2> }
  5012. if (hp1.typ = ait_align) then
  5013. GetNextInstruction(hp1, hp1);
  5014. GetNextInstruction(hp1, hpmov2);
  5015. hp1 := hpmov2;
  5016. while assigned(hp1) and
  5017. CanBeCMOV(hp1) do
  5018. begin
  5019. inc(l);
  5020. GetNextInstruction(hp1, hp1);
  5021. end;
  5022. { hp1 points to yyy (or an align right before it) }
  5023. hp3 := hp1;
  5024. if assigned(hp1) and
  5025. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  5026. begin
  5027. condition:=inverse_cond(taicpu(p).condition);
  5028. GetNextInstruction(p,hp1);
  5029. repeat
  5030. taicpu(hp1).opcode:=A_CMOVcc;
  5031. taicpu(hp1).condition:=condition;
  5032. UpdateUsedRegs(hp1);
  5033. GetNextInstruction(hp1,hp1);
  5034. until not(assigned(hp1)) or
  5035. not(CanBeCMOV(hp1));
  5036. condition:=inverse_cond(condition);
  5037. hp1 := hpmov2;
  5038. { hp1 is now at <several movs 2> }
  5039. while Assigned(hp1) and CanBeCMOV(hp1) do
  5040. begin
  5041. taicpu(hp1).opcode:=A_CMOVcc;
  5042. taicpu(hp1).condition:=condition;
  5043. UpdateUsedRegs(hp1);
  5044. GetNextInstruction(hp1,hp1);
  5045. end;
  5046. hp1 := p;
  5047. { Get first instruction after label }
  5048. GetNextInstruction(hp3, p);
  5049. if assigned(p) and (hp3.typ = ait_align) then
  5050. GetNextInstruction(p, p);
  5051. { Don't dereference yet, as doing so will cause
  5052. GetNextInstruction to skip the label and
  5053. optional align marker. [Kit] }
  5054. GetNextInstruction(hp2, hp4);
  5055. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  5056. { remove jCC }
  5057. RemoveInstruction(hp1);
  5058. { Now we can safely decrement it }
  5059. tasmlabel(symbol).decrefs;
  5060. { Remove label xxx (it will have a ref of zero due to the initial check }
  5061. StripLabelFast(hp4);
  5062. { remove jmp }
  5063. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  5064. RemoveInstruction(hp2);
  5065. { As before, now we can safely decrement it }
  5066. tasmlabel(symbol).decrefs;
  5067. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  5068. if tasmlabel(symbol).getrefs = 0 then
  5069. StripLabelFast(hp3);
  5070. if Assigned(p) then
  5071. begin
  5072. UpdateUsedRegs(p);
  5073. result:=true;
  5074. end;
  5075. exit;
  5076. end;
  5077. end;
  5078. end;
  5079. end;
  5080. end;
  5081. {$endif i8086}
  5082. end;
  5083. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  5084. var
  5085. hp1,hp2: tai;
  5086. reg_and_hp1_is_instr: Boolean;
  5087. begin
  5088. result:=false;
  5089. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  5090. GetNextInstruction(p,hp1) and
  5091. (hp1.typ = ait_instruction);
  5092. if reg_and_hp1_is_instr and
  5093. (
  5094. (taicpu(hp1).opcode <> A_LEA) or
  5095. { If the LEA instruction can be converted into an arithmetic instruction,
  5096. it may be possible to then fold it. }
  5097. (
  5098. { If the flags register is in use, don't change the instruction
  5099. to an ADD otherwise this will scramble the flags. [Kit] }
  5100. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5101. ConvertLEA(taicpu(hp1))
  5102. )
  5103. ) and
  5104. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  5105. GetNextInstruction(hp1,hp2) and
  5106. MatchInstruction(hp2,A_MOV,[]) and
  5107. (taicpu(hp2).oper[0]^.typ = top_reg) and
  5108. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  5109. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  5110. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  5111. {$ifdef i386}
  5112. { not all registers have byte size sub registers on i386 }
  5113. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  5114. {$endif i386}
  5115. (((taicpu(hp1).ops=2) and
  5116. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  5117. ((taicpu(hp1).ops=1) and
  5118. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  5119. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  5120. begin
  5121. { change movsX/movzX reg/ref, reg2
  5122. add/sub/or/... reg3/$const, reg2
  5123. mov reg2 reg/ref
  5124. to add/sub/or/... reg3/$const, reg/ref }
  5125. { by example:
  5126. movswl %si,%eax movswl %si,%eax p
  5127. decl %eax addl %edx,%eax hp1
  5128. movw %ax,%si movw %ax,%si hp2
  5129. ->
  5130. movswl %si,%eax movswl %si,%eax p
  5131. decw %eax addw %edx,%eax hp1
  5132. movw %ax,%si movw %ax,%si hp2
  5133. }
  5134. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  5135. {
  5136. ->
  5137. movswl %si,%eax movswl %si,%eax p
  5138. decw %si addw %dx,%si hp1
  5139. movw %ax,%si movw %ax,%si hp2
  5140. }
  5141. case taicpu(hp1).ops of
  5142. 1:
  5143. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  5144. 2:
  5145. begin
  5146. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  5147. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5148. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  5149. end;
  5150. else
  5151. internalerror(2008042702);
  5152. end;
  5153. {
  5154. ->
  5155. decw %si addw %dx,%si p
  5156. }
  5157. DebugMsg(SPeepholeOptimization + 'var3',p);
  5158. RemoveCurrentP(p, hp1);
  5159. RemoveInstruction(hp2);
  5160. end
  5161. else if reg_and_hp1_is_instr and
  5162. (taicpu(hp1).opcode = A_MOV) and
  5163. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5164. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  5165. {$ifdef x86_64}
  5166. { check for implicit extension to 64 bit }
  5167. or
  5168. ((taicpu(p).opsize in [S_BL,S_WL]) and
  5169. (taicpu(hp1).opsize=S_Q) and
  5170. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  5171. )
  5172. {$endif x86_64}
  5173. )
  5174. then
  5175. begin
  5176. { change
  5177. movx %reg1,%reg2
  5178. mov %reg2,%reg3
  5179. dealloc %reg2
  5180. into
  5181. movx %reg,%reg3
  5182. }
  5183. TransferUsedRegs(TmpUsedRegs);
  5184. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5185. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5186. begin
  5187. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  5188. {$ifdef x86_64}
  5189. if (taicpu(p).opsize in [S_BL,S_WL]) and
  5190. (taicpu(hp1).opsize=S_Q) then
  5191. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  5192. else
  5193. {$endif x86_64}
  5194. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  5195. RemoveInstruction(hp1);
  5196. end;
  5197. end
  5198. else if reg_and_hp1_is_instr and
  5199. (taicpu(hp1).opcode = A_MOV) and
  5200. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5201. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  5202. (taicpu(hp1).opsize=S_B)) or
  5203. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  5204. (taicpu(hp1).opsize=S_W))
  5205. {$ifdef x86_64}
  5206. or ((taicpu(p).opsize=S_LQ) and
  5207. (taicpu(hp1).opsize=S_L))
  5208. {$endif x86_64}
  5209. ) and
  5210. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  5211. begin
  5212. { change
  5213. movx %reg1,%reg2
  5214. mov %reg2,%reg3
  5215. dealloc %reg2
  5216. into
  5217. mov %reg1,%reg3
  5218. if the second mov accesses only the bits stored in reg1
  5219. }
  5220. TransferUsedRegs(TmpUsedRegs);
  5221. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5222. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5223. begin
  5224. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  5225. if taicpu(p).oper[0]^.typ=top_reg then
  5226. begin
  5227. case taicpu(hp1).opsize of
  5228. S_B:
  5229. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  5230. S_W:
  5231. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  5232. S_L:
  5233. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  5234. else
  5235. Internalerror(2020102301);
  5236. end;
  5237. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  5238. end
  5239. else
  5240. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  5241. RemoveCurrentP(p);
  5242. result:=true;
  5243. exit;
  5244. end;
  5245. end
  5246. else if reg_and_hp1_is_instr and
  5247. (taicpu(p).oper[0]^.typ = top_reg) and
  5248. (
  5249. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  5250. ) and
  5251. (taicpu(hp1).oper[0]^.typ = top_const) and
  5252. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  5253. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5254. { Minimum shift value allowed is the bit difference between the sizes }
  5255. (taicpu(hp1).oper[0]^.val >=
  5256. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  5257. 8 * (
  5258. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  5259. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  5260. )
  5261. ) then
  5262. begin
  5263. { For:
  5264. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  5265. shl/sal ##, %reg1
  5266. Remove the movsx/movzx instruction if the shift overwrites the
  5267. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  5268. }
  5269. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  5270. RemoveCurrentP(p, hp1);
  5271. Result := True;
  5272. Exit;
  5273. end
  5274. else if taicpu(p).opcode=A_MOVZX then
  5275. begin
  5276. { removes superfluous And's after movzx's }
  5277. if reg_and_hp1_is_instr and
  5278. (taicpu(hp1).opcode = A_AND) and
  5279. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5280. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  5281. {$ifdef x86_64}
  5282. { check for implicit extension to 64 bit }
  5283. or
  5284. ((taicpu(p).opsize in [S_BL,S_WL]) and
  5285. (taicpu(hp1).opsize=S_Q) and
  5286. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  5287. )
  5288. {$endif x86_64}
  5289. )
  5290. then
  5291. begin
  5292. case taicpu(p).opsize Of
  5293. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  5294. if (taicpu(hp1).oper[0]^.val = $ff) then
  5295. begin
  5296. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  5297. RemoveInstruction(hp1);
  5298. Result:=true;
  5299. exit;
  5300. end;
  5301. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  5302. if (taicpu(hp1).oper[0]^.val = $ffff) then
  5303. begin
  5304. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  5305. RemoveInstruction(hp1);
  5306. Result:=true;
  5307. exit;
  5308. end;
  5309. {$ifdef x86_64}
  5310. S_LQ:
  5311. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  5312. begin
  5313. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  5314. RemoveInstruction(hp1);
  5315. Result:=true;
  5316. exit;
  5317. end;
  5318. {$endif x86_64}
  5319. else
  5320. ;
  5321. end;
  5322. { we cannot get rid of the and, but can we get rid of the movz ?}
  5323. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  5324. begin
  5325. case taicpu(p).opsize Of
  5326. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  5327. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  5328. begin
  5329. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  5330. RemoveCurrentP(p,hp1);
  5331. Result:=true;
  5332. exit;
  5333. end;
  5334. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  5335. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  5336. begin
  5337. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  5338. RemoveCurrentP(p,hp1);
  5339. Result:=true;
  5340. exit;
  5341. end;
  5342. {$ifdef x86_64}
  5343. S_LQ:
  5344. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  5345. begin
  5346. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  5347. RemoveCurrentP(p,hp1);
  5348. Result:=true;
  5349. exit;
  5350. end;
  5351. {$endif x86_64}
  5352. else
  5353. ;
  5354. end;
  5355. end;
  5356. end;
  5357. { changes some movzx constructs to faster synonyms (all examples
  5358. are given with eax/ax, but are also valid for other registers)}
  5359. if MatchOpType(taicpu(p),top_reg,top_reg) then
  5360. begin
  5361. case taicpu(p).opsize of
  5362. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  5363. (the machine code is equivalent to movzbl %al,%eax), but the
  5364. code generator still generates that assembler instruction and
  5365. it is silently converted. This should probably be checked.
  5366. [Kit] }
  5367. S_BW:
  5368. begin
  5369. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5370. (
  5371. not IsMOVZXAcceptable
  5372. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  5373. or (
  5374. (cs_opt_size in current_settings.optimizerswitches) and
  5375. (taicpu(p).oper[1]^.reg = NR_AX)
  5376. )
  5377. ) then
  5378. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  5379. begin
  5380. DebugMsg(SPeepholeOptimization + 'var7',p);
  5381. taicpu(p).opcode := A_AND;
  5382. taicpu(p).changeopsize(S_W);
  5383. taicpu(p).loadConst(0,$ff);
  5384. Result := True;
  5385. end
  5386. else if not IsMOVZXAcceptable and
  5387. GetNextInstruction(p, hp1) and
  5388. (tai(hp1).typ = ait_instruction) and
  5389. (taicpu(hp1).opcode = A_AND) and
  5390. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5391. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5392. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  5393. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  5394. begin
  5395. DebugMsg(SPeepholeOptimization + 'var8',p);
  5396. taicpu(p).opcode := A_MOV;
  5397. taicpu(p).changeopsize(S_W);
  5398. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  5399. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5400. Result := True;
  5401. end;
  5402. end;
  5403. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  5404. S_BL:
  5405. begin
  5406. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5407. (
  5408. not IsMOVZXAcceptable
  5409. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  5410. or (
  5411. (cs_opt_size in current_settings.optimizerswitches) and
  5412. (taicpu(p).oper[1]^.reg = NR_EAX)
  5413. )
  5414. ) then
  5415. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  5416. begin
  5417. DebugMsg(SPeepholeOptimization + 'var9',p);
  5418. taicpu(p).opcode := A_AND;
  5419. taicpu(p).changeopsize(S_L);
  5420. taicpu(p).loadConst(0,$ff);
  5421. Result := True;
  5422. end
  5423. else if not IsMOVZXAcceptable and
  5424. GetNextInstruction(p, hp1) and
  5425. (tai(hp1).typ = ait_instruction) and
  5426. (taicpu(hp1).opcode = A_AND) and
  5427. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5428. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5429. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  5430. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  5431. begin
  5432. DebugMsg(SPeepholeOptimization + 'var10',p);
  5433. taicpu(p).opcode := A_MOV;
  5434. taicpu(p).changeopsize(S_L);
  5435. { do not use R_SUBWHOLE
  5436. as movl %rdx,%eax
  5437. is invalid in assembler PM }
  5438. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  5439. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5440. Result := True;
  5441. end;
  5442. end;
  5443. {$endif i8086}
  5444. S_WL:
  5445. if not IsMOVZXAcceptable then
  5446. begin
  5447. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  5448. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  5449. begin
  5450. DebugMsg(SPeepholeOptimization + 'var11',p);
  5451. taicpu(p).opcode := A_AND;
  5452. taicpu(p).changeopsize(S_L);
  5453. taicpu(p).loadConst(0,$ffff);
  5454. Result := True;
  5455. end
  5456. else if GetNextInstruction(p, hp1) and
  5457. (tai(hp1).typ = ait_instruction) and
  5458. (taicpu(hp1).opcode = A_AND) and
  5459. (taicpu(hp1).oper[0]^.typ = top_const) and
  5460. (taicpu(hp1).oper[1]^.typ = top_reg) and
  5461. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5462. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  5463. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  5464. begin
  5465. DebugMsg(SPeepholeOptimization + 'var12',p);
  5466. taicpu(p).opcode := A_MOV;
  5467. taicpu(p).changeopsize(S_L);
  5468. { do not use R_SUBWHOLE
  5469. as movl %rdx,%eax
  5470. is invalid in assembler PM }
  5471. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  5472. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  5473. Result := True;
  5474. end;
  5475. end;
  5476. else
  5477. InternalError(2017050705);
  5478. end;
  5479. end
  5480. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  5481. begin
  5482. if GetNextInstruction(p, hp1) and
  5483. (tai(hp1).typ = ait_instruction) and
  5484. (taicpu(hp1).opcode = A_AND) and
  5485. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5486. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5487. begin
  5488. //taicpu(p).opcode := A_MOV;
  5489. case taicpu(p).opsize Of
  5490. S_BL:
  5491. begin
  5492. DebugMsg(SPeepholeOptimization + 'var13',p);
  5493. taicpu(hp1).changeopsize(S_L);
  5494. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5495. end;
  5496. S_WL:
  5497. begin
  5498. DebugMsg(SPeepholeOptimization + 'var14',p);
  5499. taicpu(hp1).changeopsize(S_L);
  5500. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  5501. end;
  5502. S_BW:
  5503. begin
  5504. DebugMsg(SPeepholeOptimization + 'var15',p);
  5505. taicpu(hp1).changeopsize(S_W);
  5506. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5507. end;
  5508. else
  5509. Internalerror(2017050704)
  5510. end;
  5511. Result := True;
  5512. end;
  5513. end;
  5514. end;
  5515. end;
  5516. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  5517. var
  5518. hp1 : tai;
  5519. MaskLength : Cardinal;
  5520. begin
  5521. Result:=false;
  5522. if GetNextInstruction(p, hp1) then
  5523. begin
  5524. if MatchOpType(taicpu(p),top_const,top_reg) and
  5525. MatchInstruction(hp1,A_AND,[]) and
  5526. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5527. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5528. { the second register must contain the first one, so compare their subreg types }
  5529. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  5530. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  5531. { change
  5532. and const1, reg
  5533. and const2, reg
  5534. to
  5535. and (const1 and const2), reg
  5536. }
  5537. begin
  5538. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  5539. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  5540. RemoveCurrentP(p, hp1);
  5541. Result:=true;
  5542. exit;
  5543. end
  5544. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5545. MatchInstruction(hp1,A_MOVZX,[]) and
  5546. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5547. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  5548. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5549. (((taicpu(p).opsize=S_W) and
  5550. (taicpu(hp1).opsize=S_BW)) or
  5551. ((taicpu(p).opsize=S_L) and
  5552. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  5553. {$ifdef x86_64}
  5554. or
  5555. ((taicpu(p).opsize=S_Q) and
  5556. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  5557. {$endif x86_64}
  5558. ) then
  5559. begin
  5560. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  5561. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  5562. ) or
  5563. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  5564. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  5565. then
  5566. begin
  5567. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  5568. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  5569. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  5570. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  5571. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  5572. }
  5573. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  5574. RemoveInstruction(hp1);
  5575. Exit;
  5576. end;
  5577. end
  5578. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5579. MatchInstruction(hp1,A_SHL,[]) and
  5580. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5581. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5582. begin
  5583. {$ifopt R+}
  5584. {$define RANGE_WAS_ON}
  5585. {$R-}
  5586. {$endif}
  5587. { get length of potential and mask }
  5588. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  5589. { really a mask? }
  5590. {$ifdef RANGE_WAS_ON}
  5591. {$R+}
  5592. {$endif}
  5593. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  5594. { unmasked part shifted out? }
  5595. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  5596. begin
  5597. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  5598. RemoveCurrentP(p, hp1);
  5599. Result:=true;
  5600. exit;
  5601. end;
  5602. end
  5603. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5604. MatchInstruction(hp1,A_MOVSX{$ifdef x86_64},A_MOVSXD{$endif x86_64},[]) and
  5605. (taicpu(hp1).oper[0]^.typ = top_reg) and
  5606. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) and
  5607. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5608. (((taicpu(p).opsize=S_W) and
  5609. (taicpu(hp1).opsize=S_BW)) or
  5610. ((taicpu(p).opsize=S_L) and
  5611. (taicpu(hp1).opsize in [S_WL,S_BL]))
  5612. {$ifdef x86_64}
  5613. or
  5614. ((taicpu(p).opsize=S_Q) and
  5615. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_LQ]))
  5616. {$endif x86_64}
  5617. ) then
  5618. begin
  5619. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  5620. ((taicpu(p).oper[0]^.val and $7f)=taicpu(p).oper[0]^.val)
  5621. ) or
  5622. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  5623. ((taicpu(p).oper[0]^.val and $7fff)=taicpu(p).oper[0]^.val))
  5624. {$ifdef x86_64}
  5625. or
  5626. (((taicpu(hp1).opsize)=S_LQ) and
  5627. ((taicpu(p).oper[0]^.val and $7fffffff)=taicpu(p).oper[0]^.val)
  5628. )
  5629. {$endif x86_64}
  5630. then
  5631. begin
  5632. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  5633. RemoveInstruction(hp1);
  5634. Exit;
  5635. end;
  5636. end
  5637. else if (taicpu(p).oper[1]^.typ = top_reg) and
  5638. (hp1.typ = ait_instruction) and
  5639. (taicpu(hp1).is_jmp) and
  5640. (taicpu(hp1).opcode<>A_JMP) and
  5641. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  5642. begin
  5643. { change
  5644. and x, reg
  5645. jxx
  5646. to
  5647. test x, reg
  5648. jxx
  5649. if reg is deallocated before the
  5650. jump, but only if it's a conditional jump (PFV)
  5651. }
  5652. taicpu(p).opcode := A_TEST;
  5653. Exit;
  5654. end;
  5655. end;
  5656. { Lone AND tests }
  5657. if MatchOpType(taicpu(p),top_const,top_reg) then
  5658. begin
  5659. {
  5660. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  5661. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  5662. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  5663. }
  5664. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  5665. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  5666. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  5667. begin
  5668. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5669. if taicpu(p).opsize = S_L then
  5670. begin
  5671. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  5672. Result := True;
  5673. end;
  5674. end;
  5675. end;
  5676. end;
  5677. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  5678. begin
  5679. Result:=false;
  5680. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  5681. begin
  5682. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  5683. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  5684. begin
  5685. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  5686. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  5687. taicpu(p).opcode:=A_ADD;
  5688. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  5689. result:=true;
  5690. end
  5691. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  5692. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  5693. begin
  5694. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  5695. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  5696. taicpu(p).opcode:=A_ADD;
  5697. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  5698. result:=true;
  5699. end;
  5700. end;
  5701. end;
  5702. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  5703. var
  5704. hp1: tai; NewRef: TReference;
  5705. begin
  5706. { Change:
  5707. subl/q $x,%reg1
  5708. movl/q %reg1,%reg2
  5709. To:
  5710. leal/q $-x(%reg1),%reg2
  5711. subl/q $x,%reg1
  5712. Breaks the dependency chain and potentially permits the removal of
  5713. a CMP instruction if one follows.
  5714. }
  5715. Result := False;
  5716. if not (cs_opt_size in current_settings.optimizerswitches) and
  5717. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5718. MatchOpType(taicpu(p),top_const,top_reg) and
  5719. GetNextInstruction(p, hp1) and
  5720. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5721. (taicpu(hp1).oper[1]^.typ = top_reg) and
  5722. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) then
  5723. begin
  5724. { Change the MOV instruction to a LEA instruction, and update the
  5725. first operand }
  5726. reference_reset(NewRef, 1, []);
  5727. NewRef.base := taicpu(p).oper[1]^.reg;
  5728. NewRef.scalefactor := 1;
  5729. NewRef.offset := -taicpu(p).oper[0]^.val;
  5730. taicpu(hp1).opcode := A_LEA;
  5731. taicpu(hp1).loadref(0, NewRef);
  5732. { Move what is now the LEA instruction to before the SUB instruction }
  5733. Asml.Remove(hp1);
  5734. Asml.InsertBefore(hp1, p);
  5735. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  5736. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  5737. Result := True;
  5738. end;
  5739. end;
  5740. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  5741. begin
  5742. { we can skip all instructions not messing with the stack pointer }
  5743. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  5744. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  5745. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  5746. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  5747. ({(taicpu(hp1).ops=0) or }
  5748. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  5749. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  5750. ) and }
  5751. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  5752. )
  5753. ) do
  5754. GetNextInstruction(hp1,hp1);
  5755. Result:=assigned(hp1);
  5756. end;
  5757. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  5758. var
  5759. hp1, hp2, hp3, hp4: tai;
  5760. begin
  5761. Result:=false;
  5762. { replace
  5763. leal(q) x(<stackpointer>),<stackpointer>
  5764. call procname
  5765. leal(q) -x(<stackpointer>),<stackpointer>
  5766. ret
  5767. by
  5768. jmp procname
  5769. but do it only on level 4 because it destroys stack back traces
  5770. }
  5771. if (cs_opt_level4 in current_settings.optimizerswitches) and
  5772. MatchOpType(taicpu(p),top_ref,top_reg) and
  5773. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  5774. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  5775. { the -8 or -24 are not required, but bail out early if possible,
  5776. higher values are unlikely }
  5777. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  5778. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  5779. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  5780. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  5781. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  5782. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  5783. GetNextInstruction(p, hp1) and
  5784. { Take a copy of hp1 }
  5785. SetAndTest(hp1, hp4) and
  5786. { trick to skip label }
  5787. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  5788. SkipSimpleInstructions(hp1) and
  5789. MatchInstruction(hp1,A_CALL,[S_NO]) and
  5790. GetNextInstruction(hp1, hp2) and
  5791. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  5792. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  5793. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  5794. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  5795. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  5796. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  5797. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  5798. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  5799. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  5800. GetNextInstruction(hp2, hp3) and
  5801. { trick to skip label }
  5802. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  5803. MatchInstruction(hp3,A_RET,[S_NO]) and
  5804. (taicpu(hp3).ops=0) then
  5805. begin
  5806. taicpu(hp1).opcode := A_JMP;
  5807. taicpu(hp1).is_jmp := true;
  5808. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  5809. RemoveCurrentP(p, hp4);
  5810. RemoveInstruction(hp2);
  5811. RemoveInstruction(hp3);
  5812. Result:=true;
  5813. end;
  5814. end;
  5815. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  5816. var
  5817. hp1, hp2, hp3, hp4: tai;
  5818. begin
  5819. Result:=false;
  5820. {$ifdef x86_64}
  5821. { replace
  5822. push %rax
  5823. call procname
  5824. pop %rcx
  5825. ret
  5826. by
  5827. jmp procname
  5828. but do it only on level 4 because it destroys stack back traces
  5829. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  5830. for all supported calling conventions
  5831. }
  5832. if (cs_opt_level4 in current_settings.optimizerswitches) and
  5833. MatchOpType(taicpu(p),top_reg) and
  5834. (taicpu(p).oper[0]^.reg=NR_RAX) and
  5835. GetNextInstruction(p, hp1) and
  5836. { Take a copy of hp1 }
  5837. SetAndTest(hp1, hp4) and
  5838. { trick to skip label }
  5839. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  5840. SkipSimpleInstructions(hp1) and
  5841. MatchInstruction(hp1,A_CALL,[S_NO]) and
  5842. GetNextInstruction(hp1, hp2) and
  5843. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  5844. MatchOpType(taicpu(hp2),top_reg) and
  5845. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  5846. GetNextInstruction(hp2, hp3) and
  5847. { trick to skip label }
  5848. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  5849. MatchInstruction(hp3,A_RET,[S_NO]) and
  5850. (taicpu(hp3).ops=0) then
  5851. begin
  5852. taicpu(hp1).opcode := A_JMP;
  5853. taicpu(hp1).is_jmp := true;
  5854. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  5855. RemoveCurrentP(p, hp4);
  5856. RemoveInstruction(hp2);
  5857. RemoveInstruction(hp3);
  5858. Result:=true;
  5859. end;
  5860. {$endif x86_64}
  5861. end;
  5862. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  5863. var
  5864. Value, RegName: string;
  5865. begin
  5866. Result:=false;
  5867. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  5868. begin
  5869. case taicpu(p).oper[0]^.val of
  5870. 0:
  5871. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  5872. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  5873. begin
  5874. { change "mov $0,%reg" into "xor %reg,%reg" }
  5875. taicpu(p).opcode := A_XOR;
  5876. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  5877. Result := True;
  5878. end;
  5879. $1..$FFFFFFFF:
  5880. begin
  5881. { Code size reduction by J. Gareth "Kit" Moreton }
  5882. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  5883. case taicpu(p).opsize of
  5884. S_Q:
  5885. begin
  5886. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  5887. Value := debug_tostr(taicpu(p).oper[0]^.val);
  5888. { The actual optimization }
  5889. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5890. taicpu(p).changeopsize(S_L);
  5891. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  5892. Result := True;
  5893. end;
  5894. else
  5895. { Do nothing };
  5896. end;
  5897. end;
  5898. -1:
  5899. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  5900. if (cs_opt_size in current_settings.optimizerswitches) and
  5901. (taicpu(p).opsize <> S_B) and
  5902. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  5903. begin
  5904. { change "mov $-1,%reg" into "or $-1,%reg" }
  5905. { NOTES:
  5906. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  5907. - This operation creates a false dependency on the register, so only do it when optimising for size
  5908. - 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
  5909. }
  5910. taicpu(p).opcode := A_OR;
  5911. Result := True;
  5912. end;
  5913. end;
  5914. end;
  5915. end;
  5916. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  5917. begin
  5918. Result := False;
  5919. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  5920. Exit;
  5921. { Convert:
  5922. movswl %ax,%eax -> cwtl
  5923. movslq %eax,%rax -> cdqe
  5924. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  5925. refer to the same opcode and depends only on the assembler's
  5926. current operand-size attribute. [Kit]
  5927. }
  5928. with taicpu(p) do
  5929. case opsize of
  5930. S_WL:
  5931. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  5932. begin
  5933. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  5934. opcode := A_CWDE;
  5935. clearop(0);
  5936. clearop(1);
  5937. ops := 0;
  5938. Result := True;
  5939. end;
  5940. {$ifdef x86_64}
  5941. S_LQ:
  5942. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  5943. begin
  5944. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  5945. opcode := A_CDQE;
  5946. clearop(0);
  5947. clearop(1);
  5948. ops := 0;
  5949. Result := True;
  5950. end;
  5951. {$endif x86_64}
  5952. else
  5953. ;
  5954. end;
  5955. end;
  5956. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  5957. begin
  5958. Result:=false;
  5959. { change "cmp $0, %reg" to "test %reg, %reg" }
  5960. if MatchOpType(taicpu(p),top_const,top_reg) and
  5961. (taicpu(p).oper[0]^.val = 0) then
  5962. begin
  5963. taicpu(p).opcode := A_TEST;
  5964. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5965. Result:=true;
  5966. end;
  5967. end;
  5968. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  5969. var
  5970. IsTestConstX : Boolean;
  5971. hp1,hp2 : tai;
  5972. begin
  5973. Result:=false;
  5974. { removes the line marked with (x) from the sequence
  5975. and/or/xor/add/sub/... $x, %y
  5976. test/or %y, %y | test $-1, %y (x)
  5977. j(n)z _Label
  5978. as the first instruction already adjusts the ZF
  5979. %y operand may also be a reference }
  5980. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  5981. MatchOperand(taicpu(p).oper[0]^,-1);
  5982. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  5983. GetLastInstruction(p, hp1) and
  5984. (tai(hp1).typ = ait_instruction) and
  5985. GetNextInstruction(p,hp2) and
  5986. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  5987. case taicpu(hp1).opcode Of
  5988. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  5989. begin
  5990. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  5991. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  5992. { and in case of carry for A(E)/B(E)/C/NC }
  5993. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  5994. ((taicpu(hp1).opcode <> A_ADD) and
  5995. (taicpu(hp1).opcode <> A_SUB))) then
  5996. begin
  5997. RemoveCurrentP(p, hp2);
  5998. Result:=true;
  5999. end;
  6000. end;
  6001. A_SHL, A_SAL, A_SHR, A_SAR:
  6002. begin
  6003. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  6004. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  6005. { therefore, it's only safe to do this optimization for }
  6006. { shifts by a (nonzero) constant }
  6007. (taicpu(hp1).oper[0]^.typ = top_const) and
  6008. (taicpu(hp1).oper[0]^.val <> 0) and
  6009. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  6010. { and in case of carry for A(E)/B(E)/C/NC }
  6011. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  6012. begin
  6013. RemoveCurrentP(p, hp2);
  6014. Result:=true;
  6015. end;
  6016. end;
  6017. A_DEC, A_INC, A_NEG:
  6018. begin
  6019. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  6020. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  6021. { and in case of carry for A(E)/B(E)/C/NC }
  6022. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  6023. begin
  6024. case taicpu(hp1).opcode of
  6025. A_DEC, A_INC:
  6026. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  6027. begin
  6028. case taicpu(hp1).opcode Of
  6029. A_DEC: taicpu(hp1).opcode := A_SUB;
  6030. A_INC: taicpu(hp1).opcode := A_ADD;
  6031. else
  6032. ;
  6033. end;
  6034. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  6035. taicpu(hp1).loadConst(0,1);
  6036. taicpu(hp1).ops:=2;
  6037. end;
  6038. else
  6039. ;
  6040. end;
  6041. RemoveCurrentP(p, hp2);
  6042. Result:=true;
  6043. end;
  6044. end
  6045. else
  6046. { change "test $-1,%reg" into "test %reg,%reg" }
  6047. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  6048. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  6049. end { case }
  6050. { change "test $-1,%reg" into "test %reg,%reg" }
  6051. else if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  6052. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  6053. end;
  6054. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  6055. var
  6056. hp1 : tai;
  6057. {$ifndef x86_64}
  6058. hp2 : taicpu;
  6059. {$endif x86_64}
  6060. begin
  6061. Result:=false;
  6062. {$ifndef x86_64}
  6063. { don't do this on modern CPUs, this really hurts them due to
  6064. broken call/ret pairing }
  6065. if (current_settings.optimizecputype < cpu_Pentium2) and
  6066. not(cs_create_pic in current_settings.moduleswitches) and
  6067. GetNextInstruction(p, hp1) and
  6068. MatchInstruction(hp1,A_JMP,[S_NO]) and
  6069. MatchOpType(taicpu(hp1),top_ref) and
  6070. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  6071. begin
  6072. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  6073. InsertLLItem(p.previous, p, hp2);
  6074. taicpu(p).opcode := A_JMP;
  6075. taicpu(p).is_jmp := true;
  6076. RemoveInstruction(hp1);
  6077. Result:=true;
  6078. end
  6079. else
  6080. {$endif x86_64}
  6081. { replace
  6082. call procname
  6083. ret
  6084. by
  6085. jmp procname
  6086. but do it only on level 4 because it destroys stack back traces
  6087. else if the subroutine is marked as no return, remove the ret
  6088. }
  6089. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  6090. (po_noreturn in current_procinfo.procdef.procoptions)) and
  6091. GetNextInstruction(p, hp1) and
  6092. MatchInstruction(hp1,A_RET,[S_NO]) and
  6093. (taicpu(hp1).ops=0) then
  6094. begin
  6095. if (cs_opt_level4 in current_settings.optimizerswitches) and
  6096. { we might destroy stack alignment here if we do not do a call }
  6097. (target_info.stackalign<=sizeof(SizeUInt)) then
  6098. begin
  6099. taicpu(p).opcode := A_JMP;
  6100. taicpu(p).is_jmp := true;
  6101. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  6102. end
  6103. else
  6104. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  6105. RemoveInstruction(hp1);
  6106. Result:=true;
  6107. end;
  6108. end;
  6109. {$ifdef x86_64}
  6110. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  6111. var
  6112. PreMessage: string;
  6113. begin
  6114. Result := False;
  6115. { Code size reduction by J. Gareth "Kit" Moreton }
  6116. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  6117. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  6118. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  6119. then
  6120. begin
  6121. { Has 64-bit register name and opcode suffix }
  6122. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  6123. { The actual optimization }
  6124. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  6125. if taicpu(p).opsize = S_BQ then
  6126. taicpu(p).changeopsize(S_BL)
  6127. else
  6128. taicpu(p).changeopsize(S_WL);
  6129. DebugMsg(SPeepholeOptimization + PreMessage +
  6130. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  6131. end;
  6132. end;
  6133. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  6134. var
  6135. PreMessage, RegName: string;
  6136. begin
  6137. { Code size reduction by J. Gareth "Kit" Moreton }
  6138. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  6139. as this removes the REX prefix }
  6140. Result := False;
  6141. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  6142. Exit;
  6143. if taicpu(p).oper[0]^.typ <> top_reg then
  6144. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  6145. InternalError(2018011500);
  6146. case taicpu(p).opsize of
  6147. S_Q:
  6148. begin
  6149. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  6150. begin
  6151. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  6152. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  6153. { The actual optimization }
  6154. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  6155. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  6156. taicpu(p).changeopsize(S_L);
  6157. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  6158. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  6159. end;
  6160. end;
  6161. else
  6162. ;
  6163. end;
  6164. end;
  6165. {$endif}
  6166. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  6167. var
  6168. OperIdx: Integer;
  6169. begin
  6170. for OperIdx := 0 to p.ops - 1 do
  6171. if p.oper[OperIdx]^.typ = top_ref then
  6172. optimize_ref(p.oper[OperIdx]^.ref^, False);
  6173. end;
  6174. end.