SimplifyCFG.cpp 230 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082
  1. //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Peephole optimize the CFG.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SetOperations.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/EHPersonalities.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/MemorySSA.h"
  28. #include "llvm/Analysis/MemorySSAUpdater.h"
  29. #include "llvm/Analysis/TargetTransformInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/Attributes.h"
  32. #include "llvm/IR/BasicBlock.h"
  33. #include "llvm/IR/CFG.h"
  34. #include "llvm/IR/CallSite.h"
  35. #include "llvm/IR/Constant.h"
  36. #include "llvm/IR/ConstantRange.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/InstrTypes.h"
  45. #include "llvm/IR/Instruction.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/IntrinsicInst.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/MDBuilder.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/NoFolder.h"
  54. #include "llvm/IR/Operator.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/Use.h"
  58. #include "llvm/IR/User.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/KnownBits.h"
  65. #include "llvm/Support/MathExtras.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  68. #include "llvm/Transforms/Utils/Local.h"
  69. #include "llvm/Transforms/Utils/ValueMapper.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <climits>
  73. #include <cstddef>
  74. #include <cstdint>
  75. #include <iterator>
  76. #include <map>
  77. #include <set>
  78. #include <tuple>
  79. #include <utility>
  80. #include <vector>
  81. using namespace llvm;
  82. using namespace PatternMatch;
  83. #define DEBUG_TYPE "simplifycfg"
  84. // Chosen as 2 so as to be cheap, but still to have enough power to fold
  85. // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
  86. // To catch this, we need to fold a compare and a select, hence '2' being the
  87. // minimum reasonable default.
  88. static cl::opt<unsigned> PHINodeFoldingThreshold(
  89. "phi-node-folding-threshold", cl::Hidden, cl::init(2),
  90. cl::desc(
  91. "Control the amount of phi node folding to perform (default = 2)"));
  92. static cl::opt<bool> DupRet(
  93. "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  94. cl::desc("Duplicate return instructions into unconditional branches"));
  95. static cl::opt<bool>
  96. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  97. cl::desc("Sink common instructions down to the end block"));
  98. static cl::opt<bool> HoistCondStores(
  99. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  100. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  101. static cl::opt<bool> MergeCondStores(
  102. "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
  103. cl::desc("Hoist conditional stores even if an unconditional store does not "
  104. "precede - hoist multiple conditional stores into a single "
  105. "predicated store"));
  106. static cl::opt<bool> MergeCondStoresAggressively(
  107. "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
  108. cl::desc("When merging conditional stores, do so even if the resultant "
  109. "basic blocks are unlikely to be if-converted as a result"));
  110. static cl::opt<bool> SpeculateOneExpensiveInst(
  111. "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
  112. cl::desc("Allow exactly one expensive instruction to be speculatively "
  113. "executed"));
  114. static cl::opt<unsigned> MaxSpeculationDepth(
  115. "max-speculation-depth", cl::Hidden, cl::init(10),
  116. cl::desc("Limit maximum recursion depth when calculating costs of "
  117. "speculatively executed instructions"));
  118. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  119. STATISTIC(NumLinearMaps,
  120. "Number of switch instructions turned into linear mapping");
  121. STATISTIC(NumLookupTables,
  122. "Number of switch instructions turned into lookup tables");
  123. STATISTIC(
  124. NumLookupTablesHoles,
  125. "Number of switch instructions turned into lookup tables (holes checked)");
  126. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  127. STATISTIC(NumSinkCommons,
  128. "Number of common instructions sunk down to the end block");
  129. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  130. namespace {
  131. // The first field contains the value that the switch produces when a certain
  132. // case group is selected, and the second field is a vector containing the
  133. // cases composing the case group.
  134. using SwitchCaseResultVectorTy =
  135. SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
  136. // The first field contains the phi node that generates a result of the switch
  137. // and the second field contains the value generated for a certain case in the
  138. // switch for that PHI.
  139. using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  140. /// ValueEqualityComparisonCase - Represents a case of a switch.
  141. struct ValueEqualityComparisonCase {
  142. ConstantInt *Value;
  143. BasicBlock *Dest;
  144. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  145. : Value(Value), Dest(Dest) {}
  146. bool operator<(ValueEqualityComparisonCase RHS) const {
  147. // Comparing pointers is ok as we only rely on the order for uniquing.
  148. return Value < RHS.Value;
  149. }
  150. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  151. };
  152. class SimplifyCFGOpt {
  153. const TargetTransformInfo &TTI;
  154. const DataLayout &DL;
  155. SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
  156. const SimplifyCFGOptions &Options;
  157. bool Resimplify;
  158. Value *isValueEqualityComparison(Instruction *TI);
  159. BasicBlock *GetValueEqualityComparisonCases(
  160. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
  161. bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
  162. BasicBlock *Pred,
  163. IRBuilder<> &Builder);
  164. bool FoldValueComparisonIntoPredecessors(Instruction *TI,
  165. IRBuilder<> &Builder);
  166. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  167. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  168. bool SimplifySingleResume(ResumeInst *RI);
  169. bool SimplifyCommonResume(ResumeInst *RI);
  170. bool SimplifyCleanupReturn(CleanupReturnInst *RI);
  171. bool SimplifyUnreachable(UnreachableInst *UI);
  172. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  173. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  174. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
  175. bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
  176. bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
  177. IRBuilder<> &Builder);
  178. public:
  179. SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
  180. SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
  181. const SimplifyCFGOptions &Opts)
  182. : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
  183. bool run(BasicBlock *BB);
  184. bool simplifyOnce(BasicBlock *BB);
  185. // Helper to set Resimplify and return change indication.
  186. bool requestResimplify() {
  187. Resimplify = true;
  188. return true;
  189. }
  190. };
  191. } // end anonymous namespace
  192. /// Return true if it is safe to merge these two
  193. /// terminator instructions together.
  194. static bool
  195. SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
  196. SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
  197. if (SI1 == SI2)
  198. return false; // Can't merge with self!
  199. // It is not safe to merge these two switch instructions if they have a common
  200. // successor, and if that successor has a PHI node, and if *that* PHI node has
  201. // conflicting incoming values from the two switch blocks.
  202. BasicBlock *SI1BB = SI1->getParent();
  203. BasicBlock *SI2BB = SI2->getParent();
  204. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  205. bool Fail = false;
  206. for (BasicBlock *Succ : successors(SI2BB))
  207. if (SI1Succs.count(Succ))
  208. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  209. PHINode *PN = cast<PHINode>(BBI);
  210. if (PN->getIncomingValueForBlock(SI1BB) !=
  211. PN->getIncomingValueForBlock(SI2BB)) {
  212. if (FailBlocks)
  213. FailBlocks->insert(Succ);
  214. Fail = true;
  215. }
  216. }
  217. return !Fail;
  218. }
  219. /// Return true if it is safe and profitable to merge these two terminator
  220. /// instructions together, where SI1 is an unconditional branch. PhiNodes will
  221. /// store all PHI nodes in common successors.
  222. static bool
  223. isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
  224. Instruction *Cond,
  225. SmallVectorImpl<PHINode *> &PhiNodes) {
  226. if (SI1 == SI2)
  227. return false; // Can't merge with self!
  228. assert(SI1->isUnconditional() && SI2->isConditional());
  229. // We fold the unconditional branch if we can easily update all PHI nodes in
  230. // common successors:
  231. // 1> We have a constant incoming value for the conditional branch;
  232. // 2> We have "Cond" as the incoming value for the unconditional branch;
  233. // 3> SI2->getCondition() and Cond have same operands.
  234. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  235. if (!Ci2)
  236. return false;
  237. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  238. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  239. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  240. Cond->getOperand(1) == Ci2->getOperand(0)))
  241. return false;
  242. BasicBlock *SI1BB = SI1->getParent();
  243. BasicBlock *SI2BB = SI2->getParent();
  244. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  245. for (BasicBlock *Succ : successors(SI2BB))
  246. if (SI1Succs.count(Succ))
  247. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  248. PHINode *PN = cast<PHINode>(BBI);
  249. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  250. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  251. return false;
  252. PhiNodes.push_back(PN);
  253. }
  254. return true;
  255. }
  256. /// Update PHI nodes in Succ to indicate that there will now be entries in it
  257. /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
  258. /// will be the same as those coming in from ExistPred, an existing predecessor
  259. /// of Succ.
  260. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  261. BasicBlock *ExistPred,
  262. MemorySSAUpdater *MSSAU = nullptr) {
  263. for (PHINode &PN : Succ->phis())
  264. PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
  265. if (MSSAU)
  266. if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
  267. MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
  268. }
  269. /// Compute an abstract "cost" of speculating the given instruction,
  270. /// which is assumed to be safe to speculate. TCC_Free means cheap,
  271. /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
  272. /// expensive.
  273. static unsigned ComputeSpeculationCost(const User *I,
  274. const TargetTransformInfo &TTI) {
  275. assert(isSafeToSpeculativelyExecute(I) &&
  276. "Instruction is not safe to speculatively execute!");
  277. return TTI.getUserCost(I);
  278. }
  279. /// If we have a merge point of an "if condition" as accepted above,
  280. /// return true if the specified value dominates the block. We
  281. /// don't handle the true generality of domination here, just a special case
  282. /// which works well enough for us.
  283. ///
  284. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  285. /// see if V (which must be an instruction) and its recursive operands
  286. /// that do not dominate BB have a combined cost lower than CostRemaining and
  287. /// are non-trapping. If both are true, the instruction is inserted into the
  288. /// set and true is returned.
  289. ///
  290. /// The cost for most non-trapping instructions is defined as 1 except for
  291. /// Select whose cost is 2.
  292. ///
  293. /// After this function returns, CostRemaining is decreased by the cost of
  294. /// V plus its non-dominating operands. If that cost is greater than
  295. /// CostRemaining, false is returned and CostRemaining is undefined.
  296. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  297. SmallPtrSetImpl<Instruction *> &AggressiveInsts,
  298. unsigned &CostRemaining,
  299. const TargetTransformInfo &TTI,
  300. unsigned Depth = 0) {
  301. // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
  302. // so limit the recursion depth.
  303. // TODO: While this recursion limit does prevent pathological behavior, it
  304. // would be better to track visited instructions to avoid cycles.
  305. if (Depth == MaxSpeculationDepth)
  306. return false;
  307. Instruction *I = dyn_cast<Instruction>(V);
  308. if (!I) {
  309. // Non-instructions all dominate instructions, but not all constantexprs
  310. // can be executed unconditionally.
  311. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  312. if (C->canTrap())
  313. return false;
  314. return true;
  315. }
  316. BasicBlock *PBB = I->getParent();
  317. // We don't want to allow weird loops that might have the "if condition" in
  318. // the bottom of this block.
  319. if (PBB == BB)
  320. return false;
  321. // If this instruction is defined in a block that contains an unconditional
  322. // branch to BB, then it must be in the 'conditional' part of the "if
  323. // statement". If not, it definitely dominates the region.
  324. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  325. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  326. return true;
  327. // If we have seen this instruction before, don't count it again.
  328. if (AggressiveInsts.count(I))
  329. return true;
  330. // Okay, it looks like the instruction IS in the "condition". Check to
  331. // see if it's a cheap instruction to unconditionally compute, and if it
  332. // only uses stuff defined outside of the condition. If so, hoist it out.
  333. if (!isSafeToSpeculativelyExecute(I))
  334. return false;
  335. unsigned Cost = ComputeSpeculationCost(I, TTI);
  336. // Allow exactly one instruction to be speculated regardless of its cost
  337. // (as long as it is safe to do so).
  338. // This is intended to flatten the CFG even if the instruction is a division
  339. // or other expensive operation. The speculation of an expensive instruction
  340. // is expected to be undone in CodeGenPrepare if the speculation has not
  341. // enabled further IR optimizations.
  342. if (Cost > CostRemaining &&
  343. (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0))
  344. return false;
  345. // Avoid unsigned wrap.
  346. CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
  347. // Okay, we can only really hoist these out if their operands do
  348. // not take us over the cost threshold.
  349. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  350. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
  351. Depth + 1))
  352. return false;
  353. // Okay, it's safe to do this! Remember this instruction.
  354. AggressiveInsts.insert(I);
  355. return true;
  356. }
  357. /// Extract ConstantInt from value, looking through IntToPtr
  358. /// and PointerNullValue. Return NULL if value is not a constant int.
  359. static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
  360. // Normal constant int.
  361. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  362. if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
  363. return CI;
  364. // This is some kind of pointer constant. Turn it into a pointer-sized
  365. // ConstantInt if possible.
  366. IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
  367. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  368. if (isa<ConstantPointerNull>(V))
  369. return ConstantInt::get(PtrTy, 0);
  370. // IntToPtr const int.
  371. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  372. if (CE->getOpcode() == Instruction::IntToPtr)
  373. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  374. // The constant is very likely to have the right type already.
  375. if (CI->getType() == PtrTy)
  376. return CI;
  377. else
  378. return cast<ConstantInt>(
  379. ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  380. }
  381. return nullptr;
  382. }
  383. namespace {
  384. /// Given a chain of or (||) or and (&&) comparison of a value against a
  385. /// constant, this will try to recover the information required for a switch
  386. /// structure.
  387. /// It will depth-first traverse the chain of comparison, seeking for patterns
  388. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  389. /// representing the different cases for the switch.
  390. /// Note that if the chain is composed of '||' it will build the set of elements
  391. /// that matches the comparisons (i.e. any of this value validate the chain)
  392. /// while for a chain of '&&' it will build the set elements that make the test
  393. /// fail.
  394. struct ConstantComparesGatherer {
  395. const DataLayout &DL;
  396. /// Value found for the switch comparison
  397. Value *CompValue = nullptr;
  398. /// Extra clause to be checked before the switch
  399. Value *Extra = nullptr;
  400. /// Set of integers to match in switch
  401. SmallVector<ConstantInt *, 8> Vals;
  402. /// Number of comparisons matched in the and/or chain
  403. unsigned UsedICmps = 0;
  404. /// Construct and compute the result for the comparison instruction Cond
  405. ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
  406. gather(Cond);
  407. }
  408. ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
  409. ConstantComparesGatherer &
  410. operator=(const ConstantComparesGatherer &) = delete;
  411. private:
  412. /// Try to set the current value used for the comparison, it succeeds only if
  413. /// it wasn't set before or if the new value is the same as the old one
  414. bool setValueOnce(Value *NewVal) {
  415. if (CompValue && CompValue != NewVal)
  416. return false;
  417. CompValue = NewVal;
  418. return (CompValue != nullptr);
  419. }
  420. /// Try to match Instruction "I" as a comparison against a constant and
  421. /// populates the array Vals with the set of values that match (or do not
  422. /// match depending on isEQ).
  423. /// Return false on failure. On success, the Value the comparison matched
  424. /// against is placed in CompValue.
  425. /// If CompValue is already set, the function is expected to fail if a match
  426. /// is found but the value compared to is different.
  427. bool matchInstruction(Instruction *I, bool isEQ) {
  428. // If this is an icmp against a constant, handle this as one of the cases.
  429. ICmpInst *ICI;
  430. ConstantInt *C;
  431. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  432. (C = GetConstantInt(I->getOperand(1), DL)))) {
  433. return false;
  434. }
  435. Value *RHSVal;
  436. const APInt *RHSC;
  437. // Pattern match a special case
  438. // (x & ~2^z) == y --> x == y || x == y|2^z
  439. // This undoes a transformation done by instcombine to fuse 2 compares.
  440. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
  441. // It's a little bit hard to see why the following transformations are
  442. // correct. Here is a CVC3 program to verify them for 64-bit values:
  443. /*
  444. ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
  445. x : BITVECTOR(64);
  446. y : BITVECTOR(64);
  447. z : BITVECTOR(64);
  448. mask : BITVECTOR(64) = BVSHL(ONE, z);
  449. QUERY( (y & ~mask = y) =>
  450. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  451. );
  452. QUERY( (y | mask = y) =>
  453. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  454. );
  455. */
  456. // Please note that each pattern must be a dual implication (<--> or
  457. // iff). One directional implication can create spurious matches. If the
  458. // implication is only one-way, an unsatisfiable condition on the left
  459. // side can imply a satisfiable condition on the right side. Dual
  460. // implication ensures that satisfiable conditions are transformed to
  461. // other satisfiable conditions and unsatisfiable conditions are
  462. // transformed to other unsatisfiable conditions.
  463. // Here is a concrete example of a unsatisfiable condition on the left
  464. // implying a satisfiable condition on the right:
  465. //
  466. // mask = (1 << z)
  467. // (x & ~mask) == y --> (x == y || x == (y | mask))
  468. //
  469. // Substituting y = 3, z = 0 yields:
  470. // (x & -2) == 3 --> (x == 3 || x == 2)
  471. // Pattern match a special case:
  472. /*
  473. QUERY( (y & ~mask = y) =>
  474. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  475. );
  476. */
  477. if (match(ICI->getOperand(0),
  478. m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
  479. APInt Mask = ~*RHSC;
  480. if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
  481. // If we already have a value for the switch, it has to match!
  482. if (!setValueOnce(RHSVal))
  483. return false;
  484. Vals.push_back(C);
  485. Vals.push_back(
  486. ConstantInt::get(C->getContext(),
  487. C->getValue() | Mask));
  488. UsedICmps++;
  489. return true;
  490. }
  491. }
  492. // Pattern match a special case:
  493. /*
  494. QUERY( (y | mask = y) =>
  495. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  496. );
  497. */
  498. if (match(ICI->getOperand(0),
  499. m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
  500. APInt Mask = *RHSC;
  501. if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
  502. // If we already have a value for the switch, it has to match!
  503. if (!setValueOnce(RHSVal))
  504. return false;
  505. Vals.push_back(C);
  506. Vals.push_back(ConstantInt::get(C->getContext(),
  507. C->getValue() & ~Mask));
  508. UsedICmps++;
  509. return true;
  510. }
  511. }
  512. // If we already have a value for the switch, it has to match!
  513. if (!setValueOnce(ICI->getOperand(0)))
  514. return false;
  515. UsedICmps++;
  516. Vals.push_back(C);
  517. return ICI->getOperand(0);
  518. }
  519. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  520. ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
  521. ICI->getPredicate(), C->getValue());
  522. // Shift the range if the compare is fed by an add. This is the range
  523. // compare idiom as emitted by instcombine.
  524. Value *CandidateVal = I->getOperand(0);
  525. if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
  526. Span = Span.subtract(*RHSC);
  527. CandidateVal = RHSVal;
  528. }
  529. // If this is an and/!= check, then we are looking to build the set of
  530. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  531. // x != 0 && x != 1.
  532. if (!isEQ)
  533. Span = Span.inverse();
  534. // If there are a ton of values, we don't want to make a ginormous switch.
  535. if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
  536. return false;
  537. }
  538. // If we already have a value for the switch, it has to match!
  539. if (!setValueOnce(CandidateVal))
  540. return false;
  541. // Add all values from the range to the set
  542. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  543. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  544. UsedICmps++;
  545. return true;
  546. }
  547. /// Given a potentially 'or'd or 'and'd together collection of icmp
  548. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  549. /// the value being compared, and stick the list constants into the Vals
  550. /// vector.
  551. /// One "Extra" case is allowed to differ from the other.
  552. void gather(Value *V) {
  553. Instruction *I = dyn_cast<Instruction>(V);
  554. bool isEQ = (I->getOpcode() == Instruction::Or);
  555. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  556. SmallVector<Value *, 8> DFT;
  557. SmallPtrSet<Value *, 8> Visited;
  558. // Initialize
  559. Visited.insert(V);
  560. DFT.push_back(V);
  561. while (!DFT.empty()) {
  562. V = DFT.pop_back_val();
  563. if (Instruction *I = dyn_cast<Instruction>(V)) {
  564. // If it is a || (or && depending on isEQ), process the operands.
  565. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  566. if (Visited.insert(I->getOperand(1)).second)
  567. DFT.push_back(I->getOperand(1));
  568. if (Visited.insert(I->getOperand(0)).second)
  569. DFT.push_back(I->getOperand(0));
  570. continue;
  571. }
  572. // Try to match the current instruction
  573. if (matchInstruction(I, isEQ))
  574. // Match succeed, continue the loop
  575. continue;
  576. }
  577. // One element of the sequence of || (or &&) could not be match as a
  578. // comparison against the same value as the others.
  579. // We allow only one "Extra" case to be checked before the switch
  580. if (!Extra) {
  581. Extra = V;
  582. continue;
  583. }
  584. // Failed to parse a proper sequence, abort now
  585. CompValue = nullptr;
  586. break;
  587. }
  588. }
  589. };
  590. } // end anonymous namespace
  591. static void EraseTerminatorAndDCECond(Instruction *TI,
  592. MemorySSAUpdater *MSSAU = nullptr) {
  593. Instruction *Cond = nullptr;
  594. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  595. Cond = dyn_cast<Instruction>(SI->getCondition());
  596. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  597. if (BI->isConditional())
  598. Cond = dyn_cast<Instruction>(BI->getCondition());
  599. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  600. Cond = dyn_cast<Instruction>(IBI->getAddress());
  601. }
  602. TI->eraseFromParent();
  603. if (Cond)
  604. RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
  605. }
  606. /// Return true if the specified terminator checks
  607. /// to see if a value is equal to constant integer value.
  608. Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
  609. Value *CV = nullptr;
  610. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  611. // Do not permit merging of large switch instructions into their
  612. // predecessors unless there is only one predecessor.
  613. if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
  614. CV = SI->getCondition();
  615. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  616. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  617. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  618. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  619. CV = ICI->getOperand(0);
  620. }
  621. // Unwrap any lossless ptrtoint cast.
  622. if (CV) {
  623. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  624. Value *Ptr = PTII->getPointerOperand();
  625. if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
  626. CV = Ptr;
  627. }
  628. }
  629. return CV;
  630. }
  631. /// Given a value comparison instruction,
  632. /// decode all of the 'cases' that it represents and return the 'default' block.
  633. BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
  634. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
  635. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  636. Cases.reserve(SI->getNumCases());
  637. for (auto Case : SI->cases())
  638. Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
  639. Case.getCaseSuccessor()));
  640. return SI->getDefaultDest();
  641. }
  642. BranchInst *BI = cast<BranchInst>(TI);
  643. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  644. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  645. Cases.push_back(ValueEqualityComparisonCase(
  646. GetConstantInt(ICI->getOperand(1), DL), Succ));
  647. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  648. }
  649. /// Given a vector of bb/value pairs, remove any entries
  650. /// in the list that match the specified block.
  651. static void
  652. EliminateBlockCases(BasicBlock *BB,
  653. std::vector<ValueEqualityComparisonCase> &Cases) {
  654. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  655. }
  656. /// Return true if there are any keys in C1 that exist in C2 as well.
  657. static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  658. std::vector<ValueEqualityComparisonCase> &C2) {
  659. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  660. // Make V1 be smaller than V2.
  661. if (V1->size() > V2->size())
  662. std::swap(V1, V2);
  663. if (V1->empty())
  664. return false;
  665. if (V1->size() == 1) {
  666. // Just scan V2.
  667. ConstantInt *TheVal = (*V1)[0].Value;
  668. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  669. if (TheVal == (*V2)[i].Value)
  670. return true;
  671. }
  672. // Otherwise, just sort both lists and compare element by element.
  673. array_pod_sort(V1->begin(), V1->end());
  674. array_pod_sort(V2->begin(), V2->end());
  675. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  676. while (i1 != e1 && i2 != e2) {
  677. if ((*V1)[i1].Value == (*V2)[i2].Value)
  678. return true;
  679. if ((*V1)[i1].Value < (*V2)[i2].Value)
  680. ++i1;
  681. else
  682. ++i2;
  683. }
  684. return false;
  685. }
  686. // Set branch weights on SwitchInst. This sets the metadata if there is at
  687. // least one non-zero weight.
  688. static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
  689. // Check that there is at least one non-zero weight. Otherwise, pass
  690. // nullptr to setMetadata which will erase the existing metadata.
  691. MDNode *N = nullptr;
  692. if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
  693. N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
  694. SI->setMetadata(LLVMContext::MD_prof, N);
  695. }
  696. // Similar to the above, but for branch and select instructions that take
  697. // exactly 2 weights.
  698. static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
  699. uint32_t FalseWeight) {
  700. assert(isa<BranchInst>(I) || isa<SelectInst>(I));
  701. // Check that there is at least one non-zero weight. Otherwise, pass
  702. // nullptr to setMetadata which will erase the existing metadata.
  703. MDNode *N = nullptr;
  704. if (TrueWeight || FalseWeight)
  705. N = MDBuilder(I->getParent()->getContext())
  706. .createBranchWeights(TrueWeight, FalseWeight);
  707. I->setMetadata(LLVMContext::MD_prof, N);
  708. }
  709. /// If TI is known to be a terminator instruction and its block is known to
  710. /// only have a single predecessor block, check to see if that predecessor is
  711. /// also a value comparison with the same value, and if that comparison
  712. /// determines the outcome of this comparison. If so, simplify TI. This does a
  713. /// very limited form of jump threading.
  714. bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
  715. Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
  716. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  717. if (!PredVal)
  718. return false; // Not a value comparison in predecessor.
  719. Value *ThisVal = isValueEqualityComparison(TI);
  720. assert(ThisVal && "This isn't a value comparison!!");
  721. if (ThisVal != PredVal)
  722. return false; // Different predicates.
  723. // TODO: Preserve branch weight metadata, similarly to how
  724. // FoldValueComparisonIntoPredecessors preserves it.
  725. // Find out information about when control will move from Pred to TI's block.
  726. std::vector<ValueEqualityComparisonCase> PredCases;
  727. BasicBlock *PredDef =
  728. GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
  729. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  730. // Find information about how control leaves this block.
  731. std::vector<ValueEqualityComparisonCase> ThisCases;
  732. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  733. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  734. // If TI's block is the default block from Pred's comparison, potentially
  735. // simplify TI based on this knowledge.
  736. if (PredDef == TI->getParent()) {
  737. // If we are here, we know that the value is none of those cases listed in
  738. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  739. // can simplify TI.
  740. if (!ValuesOverlap(PredCases, ThisCases))
  741. return false;
  742. if (isa<BranchInst>(TI)) {
  743. // Okay, one of the successors of this condbr is dead. Convert it to a
  744. // uncond br.
  745. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  746. // Insert the new branch.
  747. Instruction *NI = Builder.CreateBr(ThisDef);
  748. (void)NI;
  749. // Remove PHI node entries for the dead edge.
  750. ThisCases[0].Dest->removePredecessor(TI->getParent());
  751. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  752. << "Through successor TI: " << *TI << "Leaving: " << *NI
  753. << "\n");
  754. EraseTerminatorAndDCECond(TI);
  755. return true;
  756. }
  757. SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
  758. // Okay, TI has cases that are statically dead, prune them away.
  759. SmallPtrSet<Constant *, 16> DeadCases;
  760. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  761. DeadCases.insert(PredCases[i].Value);
  762. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  763. << "Through successor TI: " << *TI);
  764. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  765. --i;
  766. if (DeadCases.count(i->getCaseValue())) {
  767. i->getCaseSuccessor()->removePredecessor(TI->getParent());
  768. SI.removeCase(i);
  769. }
  770. }
  771. LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  772. return true;
  773. }
  774. // Otherwise, TI's block must correspond to some matched value. Find out
  775. // which value (or set of values) this is.
  776. ConstantInt *TIV = nullptr;
  777. BasicBlock *TIBB = TI->getParent();
  778. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  779. if (PredCases[i].Dest == TIBB) {
  780. if (TIV)
  781. return false; // Cannot handle multiple values coming to this block.
  782. TIV = PredCases[i].Value;
  783. }
  784. assert(TIV && "No edge from pred to succ?");
  785. // Okay, we found the one constant that our value can be if we get into TI's
  786. // BB. Find out which successor will unconditionally be branched to.
  787. BasicBlock *TheRealDest = nullptr;
  788. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  789. if (ThisCases[i].Value == TIV) {
  790. TheRealDest = ThisCases[i].Dest;
  791. break;
  792. }
  793. // If not handled by any explicit cases, it is handled by the default case.
  794. if (!TheRealDest)
  795. TheRealDest = ThisDef;
  796. // Remove PHI node entries for dead edges.
  797. BasicBlock *CheckEdge = TheRealDest;
  798. for (BasicBlock *Succ : successors(TIBB))
  799. if (Succ != CheckEdge)
  800. Succ->removePredecessor(TIBB);
  801. else
  802. CheckEdge = nullptr;
  803. // Insert the new branch.
  804. Instruction *NI = Builder.CreateBr(TheRealDest);
  805. (void)NI;
  806. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  807. << "Through successor TI: " << *TI << "Leaving: " << *NI
  808. << "\n");
  809. EraseTerminatorAndDCECond(TI);
  810. return true;
  811. }
  812. namespace {
  813. /// This class implements a stable ordering of constant
  814. /// integers that does not depend on their address. This is important for
  815. /// applications that sort ConstantInt's to ensure uniqueness.
  816. struct ConstantIntOrdering {
  817. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  818. return LHS->getValue().ult(RHS->getValue());
  819. }
  820. };
  821. } // end anonymous namespace
  822. static int ConstantIntSortPredicate(ConstantInt *const *P1,
  823. ConstantInt *const *P2) {
  824. const ConstantInt *LHS = *P1;
  825. const ConstantInt *RHS = *P2;
  826. if (LHS == RHS)
  827. return 0;
  828. return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
  829. }
  830. static inline bool HasBranchWeights(const Instruction *I) {
  831. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  832. if (ProfMD && ProfMD->getOperand(0))
  833. if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  834. return MDS->getString().equals("branch_weights");
  835. return false;
  836. }
  837. /// Get Weights of a given terminator, the default weight is at the front
  838. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  839. /// metadata.
  840. static void GetBranchWeights(Instruction *TI,
  841. SmallVectorImpl<uint64_t> &Weights) {
  842. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  843. assert(MD);
  844. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  845. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  846. Weights.push_back(CI->getValue().getZExtValue());
  847. }
  848. // If TI is a conditional eq, the default case is the false case,
  849. // and the corresponding branch-weight data is at index 2. We swap the
  850. // default weight to be the first entry.
  851. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  852. assert(Weights.size() == 2);
  853. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  854. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  855. std::swap(Weights.front(), Weights.back());
  856. }
  857. }
  858. /// Keep halving the weights until all can fit in uint32_t.
  859. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  860. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  861. if (Max > UINT_MAX) {
  862. unsigned Offset = 32 - countLeadingZeros(Max);
  863. for (uint64_t &I : Weights)
  864. I >>= Offset;
  865. }
  866. }
  867. /// The specified terminator is a value equality comparison instruction
  868. /// (either a switch or a branch on "X == c").
  869. /// See if any of the predecessors of the terminator block are value comparisons
  870. /// on the same value. If so, and if safe to do so, fold them together.
  871. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
  872. IRBuilder<> &Builder) {
  873. BasicBlock *BB = TI->getParent();
  874. Value *CV = isValueEqualityComparison(TI); // CondVal
  875. assert(CV && "Not a comparison?");
  876. bool Changed = false;
  877. SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
  878. while (!Preds.empty()) {
  879. BasicBlock *Pred = Preds.pop_back_val();
  880. // See if the predecessor is a comparison with the same value.
  881. Instruction *PTI = Pred->getTerminator();
  882. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  883. if (PCV == CV && TI != PTI) {
  884. SmallSetVector<BasicBlock*, 4> FailBlocks;
  885. if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
  886. for (auto *Succ : FailBlocks) {
  887. if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
  888. return false;
  889. }
  890. }
  891. // Figure out which 'cases' to copy from SI to PSI.
  892. std::vector<ValueEqualityComparisonCase> BBCases;
  893. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  894. std::vector<ValueEqualityComparisonCase> PredCases;
  895. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  896. // Based on whether the default edge from PTI goes to BB or not, fill in
  897. // PredCases and PredDefault with the new switch cases we would like to
  898. // build.
  899. SmallVector<BasicBlock *, 8> NewSuccessors;
  900. // Update the branch weight metadata along the way
  901. SmallVector<uint64_t, 8> Weights;
  902. bool PredHasWeights = HasBranchWeights(PTI);
  903. bool SuccHasWeights = HasBranchWeights(TI);
  904. if (PredHasWeights) {
  905. GetBranchWeights(PTI, Weights);
  906. // branch-weight metadata is inconsistent here.
  907. if (Weights.size() != 1 + PredCases.size())
  908. PredHasWeights = SuccHasWeights = false;
  909. } else if (SuccHasWeights)
  910. // If there are no predecessor weights but there are successor weights,
  911. // populate Weights with 1, which will later be scaled to the sum of
  912. // successor's weights
  913. Weights.assign(1 + PredCases.size(), 1);
  914. SmallVector<uint64_t, 8> SuccWeights;
  915. if (SuccHasWeights) {
  916. GetBranchWeights(TI, SuccWeights);
  917. // branch-weight metadata is inconsistent here.
  918. if (SuccWeights.size() != 1 + BBCases.size())
  919. PredHasWeights = SuccHasWeights = false;
  920. } else if (PredHasWeights)
  921. SuccWeights.assign(1 + BBCases.size(), 1);
  922. if (PredDefault == BB) {
  923. // If this is the default destination from PTI, only the edges in TI
  924. // that don't occur in PTI, or that branch to BB will be activated.
  925. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  926. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  927. if (PredCases[i].Dest != BB)
  928. PTIHandled.insert(PredCases[i].Value);
  929. else {
  930. // The default destination is BB, we don't need explicit targets.
  931. std::swap(PredCases[i], PredCases.back());
  932. if (PredHasWeights || SuccHasWeights) {
  933. // Increase weight for the default case.
  934. Weights[0] += Weights[i + 1];
  935. std::swap(Weights[i + 1], Weights.back());
  936. Weights.pop_back();
  937. }
  938. PredCases.pop_back();
  939. --i;
  940. --e;
  941. }
  942. // Reconstruct the new switch statement we will be building.
  943. if (PredDefault != BBDefault) {
  944. PredDefault->removePredecessor(Pred);
  945. PredDefault = BBDefault;
  946. NewSuccessors.push_back(BBDefault);
  947. }
  948. unsigned CasesFromPred = Weights.size();
  949. uint64_t ValidTotalSuccWeight = 0;
  950. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  951. if (!PTIHandled.count(BBCases[i].Value) &&
  952. BBCases[i].Dest != BBDefault) {
  953. PredCases.push_back(BBCases[i]);
  954. NewSuccessors.push_back(BBCases[i].Dest);
  955. if (SuccHasWeights || PredHasWeights) {
  956. // The default weight is at index 0, so weight for the ith case
  957. // should be at index i+1. Scale the cases from successor by
  958. // PredDefaultWeight (Weights[0]).
  959. Weights.push_back(Weights[0] * SuccWeights[i + 1]);
  960. ValidTotalSuccWeight += SuccWeights[i + 1];
  961. }
  962. }
  963. if (SuccHasWeights || PredHasWeights) {
  964. ValidTotalSuccWeight += SuccWeights[0];
  965. // Scale the cases from predecessor by ValidTotalSuccWeight.
  966. for (unsigned i = 1; i < CasesFromPred; ++i)
  967. Weights[i] *= ValidTotalSuccWeight;
  968. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  969. Weights[0] *= SuccWeights[0];
  970. }
  971. } else {
  972. // If this is not the default destination from PSI, only the edges
  973. // in SI that occur in PSI with a destination of BB will be
  974. // activated.
  975. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  976. std::map<ConstantInt *, uint64_t> WeightsForHandled;
  977. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  978. if (PredCases[i].Dest == BB) {
  979. PTIHandled.insert(PredCases[i].Value);
  980. if (PredHasWeights || SuccHasWeights) {
  981. WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
  982. std::swap(Weights[i + 1], Weights.back());
  983. Weights.pop_back();
  984. }
  985. std::swap(PredCases[i], PredCases.back());
  986. PredCases.pop_back();
  987. --i;
  988. --e;
  989. }
  990. // Okay, now we know which constants were sent to BB from the
  991. // predecessor. Figure out where they will all go now.
  992. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  993. if (PTIHandled.count(BBCases[i].Value)) {
  994. // If this is one we are capable of getting...
  995. if (PredHasWeights || SuccHasWeights)
  996. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  997. PredCases.push_back(BBCases[i]);
  998. NewSuccessors.push_back(BBCases[i].Dest);
  999. PTIHandled.erase(
  1000. BBCases[i].Value); // This constant is taken care of
  1001. }
  1002. // If there are any constants vectored to BB that TI doesn't handle,
  1003. // they must go to the default destination of TI.
  1004. for (ConstantInt *I : PTIHandled) {
  1005. if (PredHasWeights || SuccHasWeights)
  1006. Weights.push_back(WeightsForHandled[I]);
  1007. PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
  1008. NewSuccessors.push_back(BBDefault);
  1009. }
  1010. }
  1011. // Okay, at this point, we know which new successor Pred will get. Make
  1012. // sure we update the number of entries in the PHI nodes for these
  1013. // successors.
  1014. for (BasicBlock *NewSuccessor : NewSuccessors)
  1015. AddPredecessorToBlock(NewSuccessor, Pred, BB);
  1016. Builder.SetInsertPoint(PTI);
  1017. // Convert pointer to int before we switch.
  1018. if (CV->getType()->isPointerTy()) {
  1019. CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
  1020. "magicptr");
  1021. }
  1022. // Now that the successors are updated, create the new Switch instruction.
  1023. SwitchInst *NewSI =
  1024. Builder.CreateSwitch(CV, PredDefault, PredCases.size());
  1025. NewSI->setDebugLoc(PTI->getDebugLoc());
  1026. for (ValueEqualityComparisonCase &V : PredCases)
  1027. NewSI->addCase(V.Value, V.Dest);
  1028. if (PredHasWeights || SuccHasWeights) {
  1029. // Halve the weights if any of them cannot fit in an uint32_t
  1030. FitWeights(Weights);
  1031. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  1032. setBranchWeights(NewSI, MDWeights);
  1033. }
  1034. EraseTerminatorAndDCECond(PTI);
  1035. // Okay, last check. If BB is still a successor of PSI, then we must
  1036. // have an infinite loop case. If so, add an infinitely looping block
  1037. // to handle the case to preserve the behavior of the code.
  1038. BasicBlock *InfLoopBlock = nullptr;
  1039. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  1040. if (NewSI->getSuccessor(i) == BB) {
  1041. if (!InfLoopBlock) {
  1042. // Insert it at the end of the function, because it's either code,
  1043. // or it won't matter if it's hot. :)
  1044. InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
  1045. BB->getParent());
  1046. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  1047. }
  1048. NewSI->setSuccessor(i, InfLoopBlock);
  1049. }
  1050. Changed = true;
  1051. }
  1052. }
  1053. return Changed;
  1054. }
  1055. // If we would need to insert a select that uses the value of this invoke
  1056. // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
  1057. // can't hoist the invoke, as there is nowhere to put the select in this case.
  1058. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  1059. Instruction *I1, Instruction *I2) {
  1060. for (BasicBlock *Succ : successors(BB1)) {
  1061. for (const PHINode &PN : Succ->phis()) {
  1062. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1063. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1064. if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
  1065. return false;
  1066. }
  1067. }
  1068. }
  1069. return true;
  1070. }
  1071. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  1072. /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
  1073. /// in the two blocks up into the branch block. The caller of this function
  1074. /// guarantees that BI's block dominates BB1 and BB2.
  1075. static bool HoistThenElseCodeToIf(BranchInst *BI,
  1076. const TargetTransformInfo &TTI) {
  1077. // This does very trivial matching, with limited scanning, to find identical
  1078. // instructions in the two blocks. In particular, we don't want to get into
  1079. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  1080. // such, we currently just scan for obviously identical instructions in an
  1081. // identical order.
  1082. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  1083. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  1084. BasicBlock::iterator BB1_Itr = BB1->begin();
  1085. BasicBlock::iterator BB2_Itr = BB2->begin();
  1086. Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
  1087. // Skip debug info if it is not identical.
  1088. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1089. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1090. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1091. while (isa<DbgInfoIntrinsic>(I1))
  1092. I1 = &*BB1_Itr++;
  1093. while (isa<DbgInfoIntrinsic>(I2))
  1094. I2 = &*BB2_Itr++;
  1095. }
  1096. // FIXME: Can we define a safety predicate for CallBr?
  1097. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  1098. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
  1099. isa<CallBrInst>(I1))
  1100. return false;
  1101. BasicBlock *BIParent = BI->getParent();
  1102. bool Changed = false;
  1103. do {
  1104. // If we are hoisting the terminator instruction, don't move one (making a
  1105. // broken BB), instead clone it, and remove BI.
  1106. if (I1->isTerminator())
  1107. goto HoistTerminator;
  1108. // If we're going to hoist a call, make sure that the two instructions we're
  1109. // commoning/hoisting are both marked with musttail, or neither of them is
  1110. // marked as such. Otherwise, we might end up in a situation where we hoist
  1111. // from a block where the terminator is a `ret` to a block where the terminator
  1112. // is a `br`, and `musttail` calls expect to be followed by a return.
  1113. auto *C1 = dyn_cast<CallInst>(I1);
  1114. auto *C2 = dyn_cast<CallInst>(I2);
  1115. if (C1 && C2)
  1116. if (C1->isMustTailCall() != C2->isMustTailCall())
  1117. return Changed;
  1118. if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
  1119. return Changed;
  1120. if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
  1121. assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
  1122. // The debug location is an integral part of a debug info intrinsic
  1123. // and can't be separated from it or replaced. Instead of attempting
  1124. // to merge locations, simply hoist both copies of the intrinsic.
  1125. BIParent->getInstList().splice(BI->getIterator(),
  1126. BB1->getInstList(), I1);
  1127. BIParent->getInstList().splice(BI->getIterator(),
  1128. BB2->getInstList(), I2);
  1129. Changed = true;
  1130. } else {
  1131. // For a normal instruction, we just move one to right before the branch,
  1132. // then replace all uses of the other with the first. Finally, we remove
  1133. // the now redundant second instruction.
  1134. BIParent->getInstList().splice(BI->getIterator(),
  1135. BB1->getInstList(), I1);
  1136. if (!I2->use_empty())
  1137. I2->replaceAllUsesWith(I1);
  1138. I1->andIRFlags(I2);
  1139. unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
  1140. LLVMContext::MD_range,
  1141. LLVMContext::MD_fpmath,
  1142. LLVMContext::MD_invariant_load,
  1143. LLVMContext::MD_nonnull,
  1144. LLVMContext::MD_invariant_group,
  1145. LLVMContext::MD_align,
  1146. LLVMContext::MD_dereferenceable,
  1147. LLVMContext::MD_dereferenceable_or_null,
  1148. LLVMContext::MD_mem_parallel_loop_access,
  1149. LLVMContext::MD_access_group};
  1150. combineMetadata(I1, I2, KnownIDs, true);
  1151. // I1 and I2 are being combined into a single instruction. Its debug
  1152. // location is the merged locations of the original instructions.
  1153. I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
  1154. I2->eraseFromParent();
  1155. Changed = true;
  1156. }
  1157. I1 = &*BB1_Itr++;
  1158. I2 = &*BB2_Itr++;
  1159. // Skip debug info if it is not identical.
  1160. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1161. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1162. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1163. while (isa<DbgInfoIntrinsic>(I1))
  1164. I1 = &*BB1_Itr++;
  1165. while (isa<DbgInfoIntrinsic>(I2))
  1166. I2 = &*BB2_Itr++;
  1167. }
  1168. } while (I1->isIdenticalToWhenDefined(I2));
  1169. return true;
  1170. HoistTerminator:
  1171. // It may not be possible to hoist an invoke.
  1172. // FIXME: Can we define a safety predicate for CallBr?
  1173. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  1174. return Changed;
  1175. // TODO: callbr hoisting currently disabled pending further study.
  1176. if (isa<CallBrInst>(I1))
  1177. return Changed;
  1178. for (BasicBlock *Succ : successors(BB1)) {
  1179. for (PHINode &PN : Succ->phis()) {
  1180. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1181. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1182. if (BB1V == BB2V)
  1183. continue;
  1184. // Check for passingValueIsAlwaysUndefined here because we would rather
  1185. // eliminate undefined control flow then converting it to a select.
  1186. if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
  1187. passingValueIsAlwaysUndefined(BB2V, &PN))
  1188. return Changed;
  1189. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
  1190. return Changed;
  1191. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
  1192. return Changed;
  1193. }
  1194. }
  1195. // Okay, it is safe to hoist the terminator.
  1196. Instruction *NT = I1->clone();
  1197. BIParent->getInstList().insert(BI->getIterator(), NT);
  1198. if (!NT->getType()->isVoidTy()) {
  1199. I1->replaceAllUsesWith(NT);
  1200. I2->replaceAllUsesWith(NT);
  1201. NT->takeName(I1);
  1202. }
  1203. // Ensure terminator gets a debug location, even an unknown one, in case
  1204. // it involves inlinable calls.
  1205. NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
  1206. // PHIs created below will adopt NT's merged DebugLoc.
  1207. IRBuilder<NoFolder> Builder(NT);
  1208. // Hoisting one of the terminators from our successor is a great thing.
  1209. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1210. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1211. // nodes, so we insert select instruction to compute the final result.
  1212. std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
  1213. for (BasicBlock *Succ : successors(BB1)) {
  1214. for (PHINode &PN : Succ->phis()) {
  1215. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1216. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1217. if (BB1V == BB2V)
  1218. continue;
  1219. // These values do not agree. Insert a select instruction before NT
  1220. // that determines the right value.
  1221. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1222. if (!SI)
  1223. SI = cast<SelectInst>(
  1224. Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1225. BB1V->getName() + "." + BB2V->getName(), BI));
  1226. // Make the PHI node use the select for all incoming values for BB1/BB2
  1227. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  1228. if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
  1229. PN.setIncomingValue(i, SI);
  1230. }
  1231. }
  1232. // Update any PHI nodes in our new successors.
  1233. for (BasicBlock *Succ : successors(BB1))
  1234. AddPredecessorToBlock(Succ, BIParent, BB1);
  1235. EraseTerminatorAndDCECond(BI);
  1236. return true;
  1237. }
  1238. // All instructions in Insts belong to different blocks that all unconditionally
  1239. // branch to a common successor. Analyze each instruction and return true if it
  1240. // would be possible to sink them into their successor, creating one common
  1241. // instruction instead. For every value that would be required to be provided by
  1242. // PHI node (because an operand varies in each input block), add to PHIOperands.
  1243. static bool canSinkInstructions(
  1244. ArrayRef<Instruction *> Insts,
  1245. DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
  1246. // Prune out obviously bad instructions to move. Each instruction must have
  1247. // exactly zero or one use, and we check later that use is by a single, common
  1248. // PHI instruction in the successor.
  1249. bool HasUse = !Insts.front()->user_empty();
  1250. for (auto *I : Insts) {
  1251. // These instructions may change or break semantics if moved.
  1252. if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
  1253. I->getType()->isTokenTy())
  1254. return false;
  1255. // Conservatively return false if I is an inline-asm instruction. Sinking
  1256. // and merging inline-asm instructions can potentially create arguments
  1257. // that cannot satisfy the inline-asm constraints.
  1258. if (const auto *C = dyn_cast<CallBase>(I))
  1259. if (C->isInlineAsm())
  1260. return false;
  1261. // Each instruction must have zero or one use.
  1262. if (HasUse && !I->hasOneUse())
  1263. return false;
  1264. if (!HasUse && !I->user_empty())
  1265. return false;
  1266. }
  1267. const Instruction *I0 = Insts.front();
  1268. for (auto *I : Insts)
  1269. if (!I->isSameOperationAs(I0))
  1270. return false;
  1271. // All instructions in Insts are known to be the same opcode. If they have a
  1272. // use, check that the only user is a PHI or in the same block as the
  1273. // instruction, because if a user is in the same block as an instruction we're
  1274. // contemplating sinking, it must already be determined to be sinkable.
  1275. if (HasUse) {
  1276. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1277. auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
  1278. if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
  1279. auto *U = cast<Instruction>(*I->user_begin());
  1280. return (PNUse &&
  1281. PNUse->getParent() == Succ &&
  1282. PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
  1283. U->getParent() == I->getParent();
  1284. }))
  1285. return false;
  1286. }
  1287. // Because SROA can't handle speculating stores of selects, try not
  1288. // to sink loads or stores of allocas when we'd have to create a PHI for
  1289. // the address operand. Also, because it is likely that loads or stores
  1290. // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
  1291. // This can cause code churn which can have unintended consequences down
  1292. // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
  1293. // FIXME: This is a workaround for a deficiency in SROA - see
  1294. // https://llvm.org/bugs/show_bug.cgi?id=30188
  1295. if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1296. return isa<AllocaInst>(I->getOperand(1));
  1297. }))
  1298. return false;
  1299. if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1300. return isa<AllocaInst>(I->getOperand(0));
  1301. }))
  1302. return false;
  1303. for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
  1304. if (I0->getOperand(OI)->getType()->isTokenTy())
  1305. // Don't touch any operand of token type.
  1306. return false;
  1307. auto SameAsI0 = [&I0, OI](const Instruction *I) {
  1308. assert(I->getNumOperands() == I0->getNumOperands());
  1309. return I->getOperand(OI) == I0->getOperand(OI);
  1310. };
  1311. if (!all_of(Insts, SameAsI0)) {
  1312. if (!canReplaceOperandWithVariable(I0, OI))
  1313. // We can't create a PHI from this GEP.
  1314. return false;
  1315. // Don't create indirect calls! The called value is the final operand.
  1316. if (isa<CallBase>(I0) && OI == OE - 1) {
  1317. // FIXME: if the call was *already* indirect, we should do this.
  1318. return false;
  1319. }
  1320. for (auto *I : Insts)
  1321. PHIOperands[I].push_back(I->getOperand(OI));
  1322. }
  1323. }
  1324. return true;
  1325. }
  1326. // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
  1327. // instruction of every block in Blocks to their common successor, commoning
  1328. // into one instruction.
  1329. static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
  1330. auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
  1331. // canSinkLastInstruction returning true guarantees that every block has at
  1332. // least one non-terminator instruction.
  1333. SmallVector<Instruction*,4> Insts;
  1334. for (auto *BB : Blocks) {
  1335. Instruction *I = BB->getTerminator();
  1336. do {
  1337. I = I->getPrevNode();
  1338. } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
  1339. if (!isa<DbgInfoIntrinsic>(I))
  1340. Insts.push_back(I);
  1341. }
  1342. // The only checking we need to do now is that all users of all instructions
  1343. // are the same PHI node. canSinkLastInstruction should have checked this but
  1344. // it is slightly over-aggressive - it gets confused by commutative instructions
  1345. // so double-check it here.
  1346. Instruction *I0 = Insts.front();
  1347. if (!I0->user_empty()) {
  1348. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1349. if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
  1350. auto *U = cast<Instruction>(*I->user_begin());
  1351. return U == PNUse;
  1352. }))
  1353. return false;
  1354. }
  1355. // We don't need to do any more checking here; canSinkLastInstruction should
  1356. // have done it all for us.
  1357. SmallVector<Value*, 4> NewOperands;
  1358. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
  1359. // This check is different to that in canSinkLastInstruction. There, we
  1360. // cared about the global view once simplifycfg (and instcombine) have
  1361. // completed - it takes into account PHIs that become trivially
  1362. // simplifiable. However here we need a more local view; if an operand
  1363. // differs we create a PHI and rely on instcombine to clean up the very
  1364. // small mess we may make.
  1365. bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
  1366. return I->getOperand(O) != I0->getOperand(O);
  1367. });
  1368. if (!NeedPHI) {
  1369. NewOperands.push_back(I0->getOperand(O));
  1370. continue;
  1371. }
  1372. // Create a new PHI in the successor block and populate it.
  1373. auto *Op = I0->getOperand(O);
  1374. assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
  1375. auto *PN = PHINode::Create(Op->getType(), Insts.size(),
  1376. Op->getName() + ".sink", &BBEnd->front());
  1377. for (auto *I : Insts)
  1378. PN->addIncoming(I->getOperand(O), I->getParent());
  1379. NewOperands.push_back(PN);
  1380. }
  1381. // Arbitrarily use I0 as the new "common" instruction; remap its operands
  1382. // and move it to the start of the successor block.
  1383. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
  1384. I0->getOperandUse(O).set(NewOperands[O]);
  1385. I0->moveBefore(&*BBEnd->getFirstInsertionPt());
  1386. // Update metadata and IR flags, and merge debug locations.
  1387. for (auto *I : Insts)
  1388. if (I != I0) {
  1389. // The debug location for the "common" instruction is the merged locations
  1390. // of all the commoned instructions. We start with the original location
  1391. // of the "common" instruction and iteratively merge each location in the
  1392. // loop below.
  1393. // This is an N-way merge, which will be inefficient if I0 is a CallInst.
  1394. // However, as N-way merge for CallInst is rare, so we use simplified API
  1395. // instead of using complex API for N-way merge.
  1396. I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
  1397. combineMetadataForCSE(I0, I, true);
  1398. I0->andIRFlags(I);
  1399. }
  1400. if (!I0->user_empty()) {
  1401. // canSinkLastInstruction checked that all instructions were used by
  1402. // one and only one PHI node. Find that now, RAUW it to our common
  1403. // instruction and nuke it.
  1404. auto *PN = cast<PHINode>(*I0->user_begin());
  1405. PN->replaceAllUsesWith(I0);
  1406. PN->eraseFromParent();
  1407. }
  1408. // Finally nuke all instructions apart from the common instruction.
  1409. for (auto *I : Insts)
  1410. if (I != I0)
  1411. I->eraseFromParent();
  1412. return true;
  1413. }
  1414. namespace {
  1415. // LockstepReverseIterator - Iterates through instructions
  1416. // in a set of blocks in reverse order from the first non-terminator.
  1417. // For example (assume all blocks have size n):
  1418. // LockstepReverseIterator I([B1, B2, B3]);
  1419. // *I-- = [B1[n], B2[n], B3[n]];
  1420. // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
  1421. // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
  1422. // ...
  1423. class LockstepReverseIterator {
  1424. ArrayRef<BasicBlock*> Blocks;
  1425. SmallVector<Instruction*,4> Insts;
  1426. bool Fail;
  1427. public:
  1428. LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
  1429. reset();
  1430. }
  1431. void reset() {
  1432. Fail = false;
  1433. Insts.clear();
  1434. for (auto *BB : Blocks) {
  1435. Instruction *Inst = BB->getTerminator();
  1436. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1437. Inst = Inst->getPrevNode();
  1438. if (!Inst) {
  1439. // Block wasn't big enough.
  1440. Fail = true;
  1441. return;
  1442. }
  1443. Insts.push_back(Inst);
  1444. }
  1445. }
  1446. bool isValid() const {
  1447. return !Fail;
  1448. }
  1449. void operator--() {
  1450. if (Fail)
  1451. return;
  1452. for (auto *&Inst : Insts) {
  1453. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1454. Inst = Inst->getPrevNode();
  1455. // Already at beginning of block.
  1456. if (!Inst) {
  1457. Fail = true;
  1458. return;
  1459. }
  1460. }
  1461. }
  1462. ArrayRef<Instruction*> operator * () const {
  1463. return Insts;
  1464. }
  1465. };
  1466. } // end anonymous namespace
  1467. /// Check whether BB's predecessors end with unconditional branches. If it is
  1468. /// true, sink any common code from the predecessors to BB.
  1469. /// We also allow one predecessor to end with conditional branch (but no more
  1470. /// than one).
  1471. static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) {
  1472. // We support two situations:
  1473. // (1) all incoming arcs are unconditional
  1474. // (2) one incoming arc is conditional
  1475. //
  1476. // (2) is very common in switch defaults and
  1477. // else-if patterns;
  1478. //
  1479. // if (a) f(1);
  1480. // else if (b) f(2);
  1481. //
  1482. // produces:
  1483. //
  1484. // [if]
  1485. // / \
  1486. // [f(1)] [if]
  1487. // | | \
  1488. // | | |
  1489. // | [f(2)]|
  1490. // \ | /
  1491. // [ end ]
  1492. //
  1493. // [end] has two unconditional predecessor arcs and one conditional. The
  1494. // conditional refers to the implicit empty 'else' arc. This conditional
  1495. // arc can also be caused by an empty default block in a switch.
  1496. //
  1497. // In this case, we attempt to sink code from all *unconditional* arcs.
  1498. // If we can sink instructions from these arcs (determined during the scan
  1499. // phase below) we insert a common successor for all unconditional arcs and
  1500. // connect that to [end], to enable sinking:
  1501. //
  1502. // [if]
  1503. // / \
  1504. // [x(1)] [if]
  1505. // | | \
  1506. // | | \
  1507. // | [x(2)] |
  1508. // \ / |
  1509. // [sink.split] |
  1510. // \ /
  1511. // [ end ]
  1512. //
  1513. SmallVector<BasicBlock*,4> UnconditionalPreds;
  1514. Instruction *Cond = nullptr;
  1515. for (auto *B : predecessors(BB)) {
  1516. auto *T = B->getTerminator();
  1517. if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
  1518. UnconditionalPreds.push_back(B);
  1519. else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
  1520. Cond = T;
  1521. else
  1522. return false;
  1523. }
  1524. if (UnconditionalPreds.size() < 2)
  1525. return false;
  1526. bool Changed = false;
  1527. // We take a two-step approach to tail sinking. First we scan from the end of
  1528. // each block upwards in lockstep. If the n'th instruction from the end of each
  1529. // block can be sunk, those instructions are added to ValuesToSink and we
  1530. // carry on. If we can sink an instruction but need to PHI-merge some operands
  1531. // (because they're not identical in each instruction) we add these to
  1532. // PHIOperands.
  1533. unsigned ScanIdx = 0;
  1534. SmallPtrSet<Value*,4> InstructionsToSink;
  1535. DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
  1536. LockstepReverseIterator LRI(UnconditionalPreds);
  1537. while (LRI.isValid() &&
  1538. canSinkInstructions(*LRI, PHIOperands)) {
  1539. LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
  1540. << "\n");
  1541. InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
  1542. ++ScanIdx;
  1543. --LRI;
  1544. }
  1545. auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
  1546. unsigned NumPHIdValues = 0;
  1547. for (auto *I : *LRI)
  1548. for (auto *V : PHIOperands[I])
  1549. if (InstructionsToSink.count(V) == 0)
  1550. ++NumPHIdValues;
  1551. LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
  1552. unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
  1553. if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
  1554. NumPHIInsts++;
  1555. return NumPHIInsts <= 1;
  1556. };
  1557. if (ScanIdx > 0 && Cond) {
  1558. // Check if we would actually sink anything first! This mutates the CFG and
  1559. // adds an extra block. The goal in doing this is to allow instructions that
  1560. // couldn't be sunk before to be sunk - obviously, speculatable instructions
  1561. // (such as trunc, add) can be sunk and predicated already. So we check that
  1562. // we're going to sink at least one non-speculatable instruction.
  1563. LRI.reset();
  1564. unsigned Idx = 0;
  1565. bool Profitable = false;
  1566. while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
  1567. if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
  1568. Profitable = true;
  1569. break;
  1570. }
  1571. --LRI;
  1572. ++Idx;
  1573. }
  1574. if (!Profitable)
  1575. return false;
  1576. LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
  1577. // We have a conditional edge and we're going to sink some instructions.
  1578. // Insert a new block postdominating all blocks we're going to sink from.
  1579. if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split"))
  1580. // Edges couldn't be split.
  1581. return false;
  1582. Changed = true;
  1583. }
  1584. // Now that we've analyzed all potential sinking candidates, perform the
  1585. // actual sink. We iteratively sink the last non-terminator of the source
  1586. // blocks into their common successor unless doing so would require too
  1587. // many PHI instructions to be generated (currently only one PHI is allowed
  1588. // per sunk instruction).
  1589. //
  1590. // We can use InstructionsToSink to discount values needing PHI-merging that will
  1591. // actually be sunk in a later iteration. This allows us to be more
  1592. // aggressive in what we sink. This does allow a false positive where we
  1593. // sink presuming a later value will also be sunk, but stop half way through
  1594. // and never actually sink it which means we produce more PHIs than intended.
  1595. // This is unlikely in practice though.
  1596. for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
  1597. LLVM_DEBUG(dbgs() << "SINK: Sink: "
  1598. << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
  1599. << "\n");
  1600. // Because we've sunk every instruction in turn, the current instruction to
  1601. // sink is always at index 0.
  1602. LRI.reset();
  1603. if (!ProfitableToSinkInstruction(LRI)) {
  1604. // Too many PHIs would be created.
  1605. LLVM_DEBUG(
  1606. dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
  1607. break;
  1608. }
  1609. if (!sinkLastInstruction(UnconditionalPreds))
  1610. return Changed;
  1611. NumSinkCommons++;
  1612. Changed = true;
  1613. }
  1614. return Changed;
  1615. }
  1616. /// Determine if we can hoist sink a sole store instruction out of a
  1617. /// conditional block.
  1618. ///
  1619. /// We are looking for code like the following:
  1620. /// BrBB:
  1621. /// store i32 %add, i32* %arrayidx2
  1622. /// ... // No other stores or function calls (we could be calling a memory
  1623. /// ... // function).
  1624. /// %cmp = icmp ult %x, %y
  1625. /// br i1 %cmp, label %EndBB, label %ThenBB
  1626. /// ThenBB:
  1627. /// store i32 %add5, i32* %arrayidx2
  1628. /// br label EndBB
  1629. /// EndBB:
  1630. /// ...
  1631. /// We are going to transform this into:
  1632. /// BrBB:
  1633. /// store i32 %add, i32* %arrayidx2
  1634. /// ... //
  1635. /// %cmp = icmp ult %x, %y
  1636. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1637. /// store i32 %add.add5, i32* %arrayidx2
  1638. /// ...
  1639. ///
  1640. /// \return The pointer to the value of the previous store if the store can be
  1641. /// hoisted into the predecessor block. 0 otherwise.
  1642. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1643. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1644. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1645. if (!StoreToHoist)
  1646. return nullptr;
  1647. // Volatile or atomic.
  1648. if (!StoreToHoist->isSimple())
  1649. return nullptr;
  1650. Value *StorePtr = StoreToHoist->getPointerOperand();
  1651. // Look for a store to the same pointer in BrBB.
  1652. unsigned MaxNumInstToLookAt = 9;
  1653. for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) {
  1654. if (!MaxNumInstToLookAt)
  1655. break;
  1656. --MaxNumInstToLookAt;
  1657. // Could be calling an instruction that affects memory like free().
  1658. if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1659. return nullptr;
  1660. if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
  1661. // Found the previous store make sure it stores to the same location.
  1662. if (SI->getPointerOperand() == StorePtr)
  1663. // Found the previous store, return its value operand.
  1664. return SI->getValueOperand();
  1665. return nullptr; // Unknown store.
  1666. }
  1667. }
  1668. return nullptr;
  1669. }
  1670. /// Speculate a conditional basic block flattening the CFG.
  1671. ///
  1672. /// Note that this is a very risky transform currently. Speculating
  1673. /// instructions like this is most often not desirable. Instead, there is an MI
  1674. /// pass which can do it with full awareness of the resource constraints.
  1675. /// However, some cases are "obvious" and we should do directly. An example of
  1676. /// this is speculating a single, reasonably cheap instruction.
  1677. ///
  1678. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1679. /// it makes very common but simplistic optimizations such as are common in
  1680. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1681. /// modeling their effects with easier to reason about SSA value graphs.
  1682. ///
  1683. ///
  1684. /// An illustration of this transform is turning this IR:
  1685. /// \code
  1686. /// BB:
  1687. /// %cmp = icmp ult %x, %y
  1688. /// br i1 %cmp, label %EndBB, label %ThenBB
  1689. /// ThenBB:
  1690. /// %sub = sub %x, %y
  1691. /// br label BB2
  1692. /// EndBB:
  1693. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1694. /// ...
  1695. /// \endcode
  1696. ///
  1697. /// Into this IR:
  1698. /// \code
  1699. /// BB:
  1700. /// %cmp = icmp ult %x, %y
  1701. /// %sub = sub %x, %y
  1702. /// %cond = select i1 %cmp, 0, %sub
  1703. /// ...
  1704. /// \endcode
  1705. ///
  1706. /// \returns true if the conditional block is removed.
  1707. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1708. const TargetTransformInfo &TTI) {
  1709. // Be conservative for now. FP select instruction can often be expensive.
  1710. Value *BrCond = BI->getCondition();
  1711. if (isa<FCmpInst>(BrCond))
  1712. return false;
  1713. BasicBlock *BB = BI->getParent();
  1714. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1715. // If ThenBB is actually on the false edge of the conditional branch, remember
  1716. // to swap the select operands later.
  1717. bool Invert = false;
  1718. if (ThenBB != BI->getSuccessor(0)) {
  1719. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1720. Invert = true;
  1721. }
  1722. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1723. // Keep a count of how many times instructions are used within ThenBB when
  1724. // they are candidates for sinking into ThenBB. Specifically:
  1725. // - They are defined in BB, and
  1726. // - They have no side effects, and
  1727. // - All of their uses are in ThenBB.
  1728. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1729. SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
  1730. unsigned SpeculationCost = 0;
  1731. Value *SpeculatedStoreValue = nullptr;
  1732. StoreInst *SpeculatedStore = nullptr;
  1733. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1734. BBE = std::prev(ThenBB->end());
  1735. BBI != BBE; ++BBI) {
  1736. Instruction *I = &*BBI;
  1737. // Skip debug info.
  1738. if (isa<DbgInfoIntrinsic>(I)) {
  1739. SpeculatedDbgIntrinsics.push_back(I);
  1740. continue;
  1741. }
  1742. // Only speculatively execute a single instruction (not counting the
  1743. // terminator) for now.
  1744. ++SpeculationCost;
  1745. if (SpeculationCost > 1)
  1746. return false;
  1747. // Don't hoist the instruction if it's unsafe or expensive.
  1748. if (!isSafeToSpeculativelyExecute(I) &&
  1749. !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
  1750. I, BB, ThenBB, EndBB))))
  1751. return false;
  1752. if (!SpeculatedStoreValue &&
  1753. ComputeSpeculationCost(I, TTI) >
  1754. PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
  1755. return false;
  1756. // Store the store speculation candidate.
  1757. if (SpeculatedStoreValue)
  1758. SpeculatedStore = cast<StoreInst>(I);
  1759. // Do not hoist the instruction if any of its operands are defined but not
  1760. // used in BB. The transformation will prevent the operand from
  1761. // being sunk into the use block.
  1762. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
  1763. Instruction *OpI = dyn_cast<Instruction>(*i);
  1764. if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
  1765. continue; // Not a candidate for sinking.
  1766. ++SinkCandidateUseCounts[OpI];
  1767. }
  1768. }
  1769. // Consider any sink candidates which are only used in ThenBB as costs for
  1770. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1771. // and so iteration order isn't significant.
  1772. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
  1773. I = SinkCandidateUseCounts.begin(),
  1774. E = SinkCandidateUseCounts.end();
  1775. I != E; ++I)
  1776. if (I->first->hasNUses(I->second)) {
  1777. ++SpeculationCost;
  1778. if (SpeculationCost > 1)
  1779. return false;
  1780. }
  1781. // Check that the PHI nodes can be converted to selects.
  1782. bool HaveRewritablePHIs = false;
  1783. for (PHINode &PN : EndBB->phis()) {
  1784. Value *OrigV = PN.getIncomingValueForBlock(BB);
  1785. Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
  1786. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1787. // Skip PHIs which are trivial.
  1788. if (ThenV == OrigV)
  1789. continue;
  1790. // Don't convert to selects if we could remove undefined behavior instead.
  1791. if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
  1792. passingValueIsAlwaysUndefined(ThenV, &PN))
  1793. return false;
  1794. HaveRewritablePHIs = true;
  1795. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1796. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1797. if (!OrigCE && !ThenCE)
  1798. continue; // Known safe and cheap.
  1799. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
  1800. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
  1801. return false;
  1802. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
  1803. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
  1804. unsigned MaxCost =
  1805. 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
  1806. if (OrigCost + ThenCost > MaxCost)
  1807. return false;
  1808. // Account for the cost of an unfolded ConstantExpr which could end up
  1809. // getting expanded into Instructions.
  1810. // FIXME: This doesn't account for how many operations are combined in the
  1811. // constant expression.
  1812. ++SpeculationCost;
  1813. if (SpeculationCost > 1)
  1814. return false;
  1815. }
  1816. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1817. // as well.
  1818. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1819. return false;
  1820. // If we get here, we can hoist the instruction and if-convert.
  1821. LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1822. // Insert a select of the value of the speculated store.
  1823. if (SpeculatedStoreValue) {
  1824. IRBuilder<NoFolder> Builder(BI);
  1825. Value *TrueV = SpeculatedStore->getValueOperand();
  1826. Value *FalseV = SpeculatedStoreValue;
  1827. if (Invert)
  1828. std::swap(TrueV, FalseV);
  1829. Value *S = Builder.CreateSelect(
  1830. BrCond, TrueV, FalseV, "spec.store.select", BI);
  1831. SpeculatedStore->setOperand(0, S);
  1832. SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
  1833. SpeculatedStore->getDebugLoc());
  1834. }
  1835. // Metadata can be dependent on the condition we are hoisting above.
  1836. // Conservatively strip all metadata on the instruction.
  1837. for (auto &I : *ThenBB)
  1838. I.dropUnknownNonDebugMetadata();
  1839. // Hoist the instructions.
  1840. BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
  1841. ThenBB->begin(), std::prev(ThenBB->end()));
  1842. // Insert selects and rewrite the PHI operands.
  1843. IRBuilder<NoFolder> Builder(BI);
  1844. for (PHINode &PN : EndBB->phis()) {
  1845. unsigned OrigI = PN.getBasicBlockIndex(BB);
  1846. unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
  1847. Value *OrigV = PN.getIncomingValue(OrigI);
  1848. Value *ThenV = PN.getIncomingValue(ThenI);
  1849. // Skip PHIs which are trivial.
  1850. if (OrigV == ThenV)
  1851. continue;
  1852. // Create a select whose true value is the speculatively executed value and
  1853. // false value is the preexisting value. Swap them if the branch
  1854. // destinations were inverted.
  1855. Value *TrueV = ThenV, *FalseV = OrigV;
  1856. if (Invert)
  1857. std::swap(TrueV, FalseV);
  1858. Value *V = Builder.CreateSelect(
  1859. BrCond, TrueV, FalseV, "spec.select", BI);
  1860. PN.setIncomingValue(OrigI, V);
  1861. PN.setIncomingValue(ThenI, V);
  1862. }
  1863. // Remove speculated dbg intrinsics.
  1864. // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
  1865. // dbg value for the different flows and inserting it after the select.
  1866. for (Instruction *I : SpeculatedDbgIntrinsics)
  1867. I->eraseFromParent();
  1868. ++NumSpeculations;
  1869. return true;
  1870. }
  1871. /// Return true if we can thread a branch across this block.
  1872. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1873. unsigned Size = 0;
  1874. for (Instruction &I : BB->instructionsWithoutDebug()) {
  1875. if (Size > 10)
  1876. return false; // Don't clone large BB's.
  1877. ++Size;
  1878. // We can only support instructions that do not define values that are
  1879. // live outside of the current basic block.
  1880. for (User *U : I.users()) {
  1881. Instruction *UI = cast<Instruction>(U);
  1882. if (UI->getParent() != BB || isa<PHINode>(UI))
  1883. return false;
  1884. }
  1885. // Looks ok, continue checking.
  1886. }
  1887. return true;
  1888. }
  1889. /// If we have a conditional branch on a PHI node value that is defined in the
  1890. /// same block as the branch and if any PHI entries are constants, thread edges
  1891. /// corresponding to that entry to be branches to their ultimate destination.
  1892. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
  1893. AssumptionCache *AC) {
  1894. BasicBlock *BB = BI->getParent();
  1895. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1896. // NOTE: we currently cannot transform this case if the PHI node is used
  1897. // outside of the block.
  1898. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1899. return false;
  1900. // Degenerate case of a single entry PHI.
  1901. if (PN->getNumIncomingValues() == 1) {
  1902. FoldSingleEntryPHINodes(PN->getParent());
  1903. return true;
  1904. }
  1905. // Now we know that this block has multiple preds and two succs.
  1906. if (!BlockIsSimpleEnoughToThreadThrough(BB))
  1907. return false;
  1908. // Can't fold blocks that contain noduplicate or convergent calls.
  1909. if (any_of(*BB, [](const Instruction &I) {
  1910. const CallInst *CI = dyn_cast<CallInst>(&I);
  1911. return CI && (CI->cannotDuplicate() || CI->isConvergent());
  1912. }))
  1913. return false;
  1914. // Okay, this is a simple enough basic block. See if any phi values are
  1915. // constants.
  1916. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1917. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1918. if (!CB || !CB->getType()->isIntegerTy(1))
  1919. continue;
  1920. // Okay, we now know that all edges from PredBB should be revectored to
  1921. // branch to RealDest.
  1922. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1923. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1924. if (RealDest == BB)
  1925. continue; // Skip self loops.
  1926. // Skip if the predecessor's terminator is an indirect branch.
  1927. if (isa<IndirectBrInst>(PredBB->getTerminator()))
  1928. continue;
  1929. // The dest block might have PHI nodes, other predecessors and other
  1930. // difficult cases. Instead of being smart about this, just insert a new
  1931. // block that jumps to the destination block, effectively splitting
  1932. // the edge we are about to create.
  1933. BasicBlock *EdgeBB =
  1934. BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
  1935. RealDest->getParent(), RealDest);
  1936. BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
  1937. CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
  1938. // Update PHI nodes.
  1939. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1940. // BB may have instructions that are being threaded over. Clone these
  1941. // instructions into EdgeBB. We know that there will be no uses of the
  1942. // cloned instructions outside of EdgeBB.
  1943. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1944. DenseMap<Value *, Value *> TranslateMap; // Track translated values.
  1945. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1946. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1947. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1948. continue;
  1949. }
  1950. // Clone the instruction.
  1951. Instruction *N = BBI->clone();
  1952. if (BBI->hasName())
  1953. N->setName(BBI->getName() + ".c");
  1954. // Update operands due to translation.
  1955. for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
  1956. DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
  1957. if (PI != TranslateMap.end())
  1958. *i = PI->second;
  1959. }
  1960. // Check for trivial simplification.
  1961. if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
  1962. if (!BBI->use_empty())
  1963. TranslateMap[&*BBI] = V;
  1964. if (!N->mayHaveSideEffects()) {
  1965. N->deleteValue(); // Instruction folded away, don't need actual inst
  1966. N = nullptr;
  1967. }
  1968. } else {
  1969. if (!BBI->use_empty())
  1970. TranslateMap[&*BBI] = N;
  1971. }
  1972. // Insert the new instruction into its new home.
  1973. if (N)
  1974. EdgeBB->getInstList().insert(InsertPt, N);
  1975. // Register the new instruction with the assumption cache if necessary.
  1976. if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
  1977. if (II->getIntrinsicID() == Intrinsic::assume)
  1978. AC->registerAssumption(II);
  1979. }
  1980. // Loop over all of the edges from PredBB to BB, changing them to branch
  1981. // to EdgeBB instead.
  1982. Instruction *PredBBTI = PredBB->getTerminator();
  1983. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1984. if (PredBBTI->getSuccessor(i) == BB) {
  1985. BB->removePredecessor(PredBB);
  1986. PredBBTI->setSuccessor(i, EdgeBB);
  1987. }
  1988. // Recurse, simplifying any other constants.
  1989. return FoldCondBranchOnPHI(BI, DL, AC) || true;
  1990. }
  1991. return false;
  1992. }
  1993. /// Given a BB that starts with the specified two-entry PHI node,
  1994. /// see if we can eliminate it.
  1995. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
  1996. const DataLayout &DL) {
  1997. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1998. // statement", which has a very simple dominance structure. Basically, we
  1999. // are trying to find the condition that is being branched on, which
  2000. // subsequently causes this merge to happen. We really want control
  2001. // dependence information for this check, but simplifycfg can't keep it up
  2002. // to date, and this catches most of the cases we care about anyway.
  2003. BasicBlock *BB = PN->getParent();
  2004. const Function *Fn = BB->getParent();
  2005. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  2006. return false;
  2007. BasicBlock *IfTrue, *IfFalse;
  2008. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  2009. if (!IfCond ||
  2010. // Don't bother if the branch will be constant folded trivially.
  2011. isa<ConstantInt>(IfCond))
  2012. return false;
  2013. // Okay, we found that we can merge this two-entry phi node into a select.
  2014. // Doing so would require us to fold *all* two entry phi nodes in this block.
  2015. // At some point this becomes non-profitable (particularly if the target
  2016. // doesn't support cmov's). Only do this transformation if there are two or
  2017. // fewer PHI nodes in this block.
  2018. unsigned NumPhis = 0;
  2019. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  2020. if (NumPhis > 2)
  2021. return false;
  2022. // Loop over the PHI's seeing if we can promote them all to select
  2023. // instructions. While we are at it, keep track of the instructions
  2024. // that need to be moved to the dominating block.
  2025. SmallPtrSet<Instruction *, 4> AggressiveInsts;
  2026. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  2027. MaxCostVal1 = PHINodeFoldingThreshold;
  2028. MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
  2029. MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
  2030. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  2031. PHINode *PN = cast<PHINode>(II++);
  2032. if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
  2033. PN->replaceAllUsesWith(V);
  2034. PN->eraseFromParent();
  2035. continue;
  2036. }
  2037. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
  2038. MaxCostVal0, TTI) ||
  2039. !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
  2040. MaxCostVal1, TTI))
  2041. return false;
  2042. }
  2043. // If we folded the first phi, PN dangles at this point. Refresh it. If
  2044. // we ran out of PHIs then we simplified them all.
  2045. PN = dyn_cast<PHINode>(BB->begin());
  2046. if (!PN)
  2047. return true;
  2048. // Don't fold i1 branches on PHIs which contain binary operators. These can
  2049. // often be turned into switches and other things.
  2050. if (PN->getType()->isIntegerTy(1) &&
  2051. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  2052. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  2053. isa<BinaryOperator>(IfCond)))
  2054. return false;
  2055. // If all PHI nodes are promotable, check to make sure that all instructions
  2056. // in the predecessor blocks can be promoted as well. If not, we won't be able
  2057. // to get rid of the control flow, so it's not worth promoting to select
  2058. // instructions.
  2059. BasicBlock *DomBlock = nullptr;
  2060. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  2061. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  2062. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  2063. IfBlock1 = nullptr;
  2064. } else {
  2065. DomBlock = *pred_begin(IfBlock1);
  2066. for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
  2067. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2068. // This is not an aggressive instruction that we can promote.
  2069. // Because of this, we won't be able to get rid of the control flow, so
  2070. // the xform is not worth it.
  2071. return false;
  2072. }
  2073. }
  2074. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  2075. IfBlock2 = nullptr;
  2076. } else {
  2077. DomBlock = *pred_begin(IfBlock2);
  2078. for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
  2079. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2080. // This is not an aggressive instruction that we can promote.
  2081. // Because of this, we won't be able to get rid of the control flow, so
  2082. // the xform is not worth it.
  2083. return false;
  2084. }
  2085. }
  2086. LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
  2087. << " T: " << IfTrue->getName()
  2088. << " F: " << IfFalse->getName() << "\n");
  2089. // If we can still promote the PHI nodes after this gauntlet of tests,
  2090. // do all of the PHI's now.
  2091. Instruction *InsertPt = DomBlock->getTerminator();
  2092. IRBuilder<NoFolder> Builder(InsertPt);
  2093. // Move all 'aggressive' instructions, which are defined in the
  2094. // conditional parts of the if's up to the dominating block.
  2095. if (IfBlock1)
  2096. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
  2097. if (IfBlock2)
  2098. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
  2099. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  2100. // Change the PHI node into a select instruction.
  2101. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  2102. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  2103. Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
  2104. PN->replaceAllUsesWith(Sel);
  2105. Sel->takeName(PN);
  2106. PN->eraseFromParent();
  2107. }
  2108. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  2109. // has been flattened. Change DomBlock to jump directly to our new block to
  2110. // avoid other simplifycfg's kicking in on the diamond.
  2111. Instruction *OldTI = DomBlock->getTerminator();
  2112. Builder.SetInsertPoint(OldTI);
  2113. Builder.CreateBr(BB);
  2114. OldTI->eraseFromParent();
  2115. return true;
  2116. }
  2117. /// If we found a conditional branch that goes to two returning blocks,
  2118. /// try to merge them together into one return,
  2119. /// introducing a select if the return values disagree.
  2120. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  2121. IRBuilder<> &Builder) {
  2122. assert(BI->isConditional() && "Must be a conditional branch");
  2123. BasicBlock *TrueSucc = BI->getSuccessor(0);
  2124. BasicBlock *FalseSucc = BI->getSuccessor(1);
  2125. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  2126. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  2127. // Check to ensure both blocks are empty (just a return) or optionally empty
  2128. // with PHI nodes. If there are other instructions, merging would cause extra
  2129. // computation on one path or the other.
  2130. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  2131. return false;
  2132. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  2133. return false;
  2134. Builder.SetInsertPoint(BI);
  2135. // Okay, we found a branch that is going to two return nodes. If
  2136. // there is no return value for this function, just change the
  2137. // branch into a return.
  2138. if (FalseRet->getNumOperands() == 0) {
  2139. TrueSucc->removePredecessor(BI->getParent());
  2140. FalseSucc->removePredecessor(BI->getParent());
  2141. Builder.CreateRetVoid();
  2142. EraseTerminatorAndDCECond(BI);
  2143. return true;
  2144. }
  2145. // Otherwise, figure out what the true and false return values are
  2146. // so we can insert a new select instruction.
  2147. Value *TrueValue = TrueRet->getReturnValue();
  2148. Value *FalseValue = FalseRet->getReturnValue();
  2149. // Unwrap any PHI nodes in the return blocks.
  2150. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  2151. if (TVPN->getParent() == TrueSucc)
  2152. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  2153. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  2154. if (FVPN->getParent() == FalseSucc)
  2155. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  2156. // In order for this transformation to be safe, we must be able to
  2157. // unconditionally execute both operands to the return. This is
  2158. // normally the case, but we could have a potentially-trapping
  2159. // constant expression that prevents this transformation from being
  2160. // safe.
  2161. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  2162. if (TCV->canTrap())
  2163. return false;
  2164. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  2165. if (FCV->canTrap())
  2166. return false;
  2167. // Okay, we collected all the mapped values and checked them for sanity, and
  2168. // defined to really do this transformation. First, update the CFG.
  2169. TrueSucc->removePredecessor(BI->getParent());
  2170. FalseSucc->removePredecessor(BI->getParent());
  2171. // Insert select instructions where needed.
  2172. Value *BrCond = BI->getCondition();
  2173. if (TrueValue) {
  2174. // Insert a select if the results differ.
  2175. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  2176. } else if (isa<UndefValue>(TrueValue)) {
  2177. TrueValue = FalseValue;
  2178. } else {
  2179. TrueValue =
  2180. Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
  2181. }
  2182. }
  2183. Value *RI =
  2184. !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  2185. (void)RI;
  2186. LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  2187. << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: "
  2188. << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
  2189. EraseTerminatorAndDCECond(BI);
  2190. return true;
  2191. }
  2192. /// Return true if the given instruction is available
  2193. /// in its predecessor block. If yes, the instruction will be removed.
  2194. static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) {
  2195. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  2196. return false;
  2197. for (Instruction &I : *PB) {
  2198. Instruction *PBI = &I;
  2199. // Check whether Inst and PBI generate the same value.
  2200. if (Inst->isIdenticalTo(PBI)) {
  2201. Inst->replaceAllUsesWith(PBI);
  2202. Inst->eraseFromParent();
  2203. return true;
  2204. }
  2205. }
  2206. return false;
  2207. }
  2208. /// Return true if either PBI or BI has branch weight available, and store
  2209. /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
  2210. /// not have branch weight, use 1:1 as its weight.
  2211. static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
  2212. uint64_t &PredTrueWeight,
  2213. uint64_t &PredFalseWeight,
  2214. uint64_t &SuccTrueWeight,
  2215. uint64_t &SuccFalseWeight) {
  2216. bool PredHasWeights =
  2217. PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
  2218. bool SuccHasWeights =
  2219. BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
  2220. if (PredHasWeights || SuccHasWeights) {
  2221. if (!PredHasWeights)
  2222. PredTrueWeight = PredFalseWeight = 1;
  2223. if (!SuccHasWeights)
  2224. SuccTrueWeight = SuccFalseWeight = 1;
  2225. return true;
  2226. } else {
  2227. return false;
  2228. }
  2229. }
  2230. /// If this basic block is simple enough, and if a predecessor branches to us
  2231. /// and one of our successors, fold the block into the predecessor and use
  2232. /// logical operations to pick the right destination.
  2233. bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU,
  2234. unsigned BonusInstThreshold) {
  2235. BasicBlock *BB = BI->getParent();
  2236. const unsigned PredCount = pred_size(BB);
  2237. Instruction *Cond = nullptr;
  2238. if (BI->isConditional())
  2239. Cond = dyn_cast<Instruction>(BI->getCondition());
  2240. else {
  2241. // For unconditional branch, check for a simple CFG pattern, where
  2242. // BB has a single predecessor and BB's successor is also its predecessor's
  2243. // successor. If such pattern exists, check for CSE between BB and its
  2244. // predecessor.
  2245. if (BasicBlock *PB = BB->getSinglePredecessor())
  2246. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  2247. if (PBI->isConditional() &&
  2248. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  2249. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  2250. for (auto I = BB->instructionsWithoutDebug().begin(),
  2251. E = BB->instructionsWithoutDebug().end();
  2252. I != E;) {
  2253. Instruction *Curr = &*I++;
  2254. if (isa<CmpInst>(Curr)) {
  2255. Cond = Curr;
  2256. break;
  2257. }
  2258. // Quit if we can't remove this instruction.
  2259. if (!tryCSEWithPredecessor(Curr, PB))
  2260. return false;
  2261. }
  2262. }
  2263. if (!Cond)
  2264. return false;
  2265. }
  2266. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  2267. Cond->getParent() != BB || !Cond->hasOneUse())
  2268. return false;
  2269. // Make sure the instruction after the condition is the cond branch.
  2270. BasicBlock::iterator CondIt = ++Cond->getIterator();
  2271. // Ignore dbg intrinsics.
  2272. while (isa<DbgInfoIntrinsic>(CondIt))
  2273. ++CondIt;
  2274. if (&*CondIt != BI)
  2275. return false;
  2276. // Only allow this transformation if computing the condition doesn't involve
  2277. // too many instructions and these involved instructions can be executed
  2278. // unconditionally. We denote all involved instructions except the condition
  2279. // as "bonus instructions", and only allow this transformation when the
  2280. // number of the bonus instructions we'll need to create when cloning into
  2281. // each predecessor does not exceed a certain threshold.
  2282. unsigned NumBonusInsts = 0;
  2283. for (auto I = BB->begin(); Cond != &*I; ++I) {
  2284. // Ignore dbg intrinsics.
  2285. if (isa<DbgInfoIntrinsic>(I))
  2286. continue;
  2287. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
  2288. return false;
  2289. // I has only one use and can be executed unconditionally.
  2290. Instruction *User = dyn_cast<Instruction>(I->user_back());
  2291. if (User == nullptr || User->getParent() != BB)
  2292. return false;
  2293. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  2294. // to use any other instruction, User must be an instruction between next(I)
  2295. // and Cond.
  2296. // Account for the cost of duplicating this instruction into each
  2297. // predecessor.
  2298. NumBonusInsts += PredCount;
  2299. // Early exits once we reach the limit.
  2300. if (NumBonusInsts > BonusInstThreshold)
  2301. return false;
  2302. }
  2303. // Cond is known to be a compare or binary operator. Check to make sure that
  2304. // neither operand is a potentially-trapping constant expression.
  2305. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  2306. if (CE->canTrap())
  2307. return false;
  2308. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  2309. if (CE->canTrap())
  2310. return false;
  2311. // Finally, don't infinitely unroll conditional loops.
  2312. BasicBlock *TrueDest = BI->getSuccessor(0);
  2313. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  2314. if (TrueDest == BB || FalseDest == BB)
  2315. return false;
  2316. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2317. BasicBlock *PredBlock = *PI;
  2318. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  2319. // Check that we have two conditional branches. If there is a PHI node in
  2320. // the common successor, verify that the same value flows in from both
  2321. // blocks.
  2322. SmallVector<PHINode *, 4> PHIs;
  2323. if (!PBI || PBI->isUnconditional() ||
  2324. (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
  2325. (!BI->isConditional() &&
  2326. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  2327. continue;
  2328. // Determine if the two branches share a common destination.
  2329. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  2330. bool InvertPredCond = false;
  2331. if (BI->isConditional()) {
  2332. if (PBI->getSuccessor(0) == TrueDest) {
  2333. Opc = Instruction::Or;
  2334. } else if (PBI->getSuccessor(1) == FalseDest) {
  2335. Opc = Instruction::And;
  2336. } else if (PBI->getSuccessor(0) == FalseDest) {
  2337. Opc = Instruction::And;
  2338. InvertPredCond = true;
  2339. } else if (PBI->getSuccessor(1) == TrueDest) {
  2340. Opc = Instruction::Or;
  2341. InvertPredCond = true;
  2342. } else {
  2343. continue;
  2344. }
  2345. } else {
  2346. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  2347. continue;
  2348. }
  2349. LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  2350. IRBuilder<> Builder(PBI);
  2351. // If we need to invert the condition in the pred block to match, do so now.
  2352. if (InvertPredCond) {
  2353. Value *NewCond = PBI->getCondition();
  2354. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  2355. CmpInst *CI = cast<CmpInst>(NewCond);
  2356. CI->setPredicate(CI->getInversePredicate());
  2357. } else {
  2358. NewCond =
  2359. Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
  2360. }
  2361. PBI->setCondition(NewCond);
  2362. PBI->swapSuccessors();
  2363. }
  2364. // If we have bonus instructions, clone them into the predecessor block.
  2365. // Note that there may be multiple predecessor blocks, so we cannot move
  2366. // bonus instructions to a predecessor block.
  2367. ValueToValueMapTy VMap; // maps original values to cloned values
  2368. // We already make sure Cond is the last instruction before BI. Therefore,
  2369. // all instructions before Cond other than DbgInfoIntrinsic are bonus
  2370. // instructions.
  2371. for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
  2372. if (isa<DbgInfoIntrinsic>(BonusInst))
  2373. continue;
  2374. Instruction *NewBonusInst = BonusInst->clone();
  2375. RemapInstruction(NewBonusInst, VMap,
  2376. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2377. VMap[&*BonusInst] = NewBonusInst;
  2378. // If we moved a load, we cannot any longer claim any knowledge about
  2379. // its potential value. The previous information might have been valid
  2380. // only given the branch precondition.
  2381. // For an analogous reason, we must also drop all the metadata whose
  2382. // semantics we don't understand.
  2383. NewBonusInst->dropUnknownNonDebugMetadata();
  2384. PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
  2385. NewBonusInst->takeName(&*BonusInst);
  2386. BonusInst->setName(BonusInst->getName() + ".old");
  2387. }
  2388. // Clone Cond into the predecessor basic block, and or/and the
  2389. // two conditions together.
  2390. Instruction *CondInPred = Cond->clone();
  2391. RemapInstruction(CondInPred, VMap,
  2392. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2393. PredBlock->getInstList().insert(PBI->getIterator(), CondInPred);
  2394. CondInPred->takeName(Cond);
  2395. Cond->setName(CondInPred->getName() + ".old");
  2396. if (BI->isConditional()) {
  2397. Instruction *NewCond = cast<Instruction>(
  2398. Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
  2399. PBI->setCondition(NewCond);
  2400. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2401. bool HasWeights =
  2402. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2403. SuccTrueWeight, SuccFalseWeight);
  2404. SmallVector<uint64_t, 8> NewWeights;
  2405. if (PBI->getSuccessor(0) == BB) {
  2406. if (HasWeights) {
  2407. // PBI: br i1 %x, BB, FalseDest
  2408. // BI: br i1 %y, TrueDest, FalseDest
  2409. // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  2410. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  2411. // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  2412. // TrueWeight for PBI * FalseWeight for BI.
  2413. // We assume that total weights of a BranchInst can fit into 32 bits.
  2414. // Therefore, we will not have overflow using 64-bit arithmetic.
  2415. NewWeights.push_back(PredFalseWeight *
  2416. (SuccFalseWeight + SuccTrueWeight) +
  2417. PredTrueWeight * SuccFalseWeight);
  2418. }
  2419. AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU);
  2420. PBI->setSuccessor(0, TrueDest);
  2421. }
  2422. if (PBI->getSuccessor(1) == BB) {
  2423. if (HasWeights) {
  2424. // PBI: br i1 %x, TrueDest, BB
  2425. // BI: br i1 %y, TrueDest, FalseDest
  2426. // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2427. // FalseWeight for PBI * TrueWeight for BI.
  2428. NewWeights.push_back(PredTrueWeight *
  2429. (SuccFalseWeight + SuccTrueWeight) +
  2430. PredFalseWeight * SuccTrueWeight);
  2431. // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2432. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2433. }
  2434. AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU);
  2435. PBI->setSuccessor(1, FalseDest);
  2436. }
  2437. if (NewWeights.size() == 2) {
  2438. // Halve the weights if any of them cannot fit in an uint32_t
  2439. FitWeights(NewWeights);
  2440. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
  2441. NewWeights.end());
  2442. setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
  2443. } else
  2444. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2445. } else {
  2446. // Update PHI nodes in the common successors.
  2447. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2448. ConstantInt *PBI_C = cast<ConstantInt>(
  2449. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2450. assert(PBI_C->getType()->isIntegerTy(1));
  2451. Instruction *MergedCond = nullptr;
  2452. if (PBI->getSuccessor(0) == TrueDest) {
  2453. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2454. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2455. // is false: !PBI_Cond and BI_Value
  2456. Instruction *NotCond = cast<Instruction>(
  2457. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2458. MergedCond = cast<Instruction>(
  2459. Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
  2460. "and.cond"));
  2461. if (PBI_C->isOne())
  2462. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2463. Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
  2464. } else {
  2465. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2466. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2467. // is false: PBI_Cond and BI_Value
  2468. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2469. Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
  2470. if (PBI_C->isOne()) {
  2471. Instruction *NotCond = cast<Instruction>(
  2472. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2473. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2474. Instruction::Or, NotCond, MergedCond, "or.cond"));
  2475. }
  2476. }
  2477. // Update PHI Node.
  2478. PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond);
  2479. }
  2480. // PBI is changed to branch to TrueDest below. Remove itself from
  2481. // potential phis from all other successors.
  2482. if (MSSAU)
  2483. MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest);
  2484. // Change PBI from Conditional to Unconditional.
  2485. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2486. EraseTerminatorAndDCECond(PBI, MSSAU);
  2487. PBI = New_PBI;
  2488. }
  2489. // If BI was a loop latch, it may have had associated loop metadata.
  2490. // We need to copy it to the new latch, that is, PBI.
  2491. if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
  2492. PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
  2493. // TODO: If BB is reachable from all paths through PredBlock, then we
  2494. // could replace PBI's branch probabilities with BI's.
  2495. // Copy any debug value intrinsics into the end of PredBlock.
  2496. for (Instruction &I : *BB)
  2497. if (isa<DbgInfoIntrinsic>(I))
  2498. I.clone()->insertBefore(PBI);
  2499. return true;
  2500. }
  2501. return false;
  2502. }
  2503. // If there is only one store in BB1 and BB2, return it, otherwise return
  2504. // nullptr.
  2505. static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
  2506. StoreInst *S = nullptr;
  2507. for (auto *BB : {BB1, BB2}) {
  2508. if (!BB)
  2509. continue;
  2510. for (auto &I : *BB)
  2511. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  2512. if (S)
  2513. // Multiple stores seen.
  2514. return nullptr;
  2515. else
  2516. S = SI;
  2517. }
  2518. }
  2519. return S;
  2520. }
  2521. static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
  2522. Value *AlternativeV = nullptr) {
  2523. // PHI is going to be a PHI node that allows the value V that is defined in
  2524. // BB to be referenced in BB's only successor.
  2525. //
  2526. // If AlternativeV is nullptr, the only value we care about in PHI is V. It
  2527. // doesn't matter to us what the other operand is (it'll never get used). We
  2528. // could just create a new PHI with an undef incoming value, but that could
  2529. // increase register pressure if EarlyCSE/InstCombine can't fold it with some
  2530. // other PHI. So here we directly look for some PHI in BB's successor with V
  2531. // as an incoming operand. If we find one, we use it, else we create a new
  2532. // one.
  2533. //
  2534. // If AlternativeV is not nullptr, we care about both incoming values in PHI.
  2535. // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
  2536. // where OtherBB is the single other predecessor of BB's only successor.
  2537. PHINode *PHI = nullptr;
  2538. BasicBlock *Succ = BB->getSingleSuccessor();
  2539. for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
  2540. if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
  2541. PHI = cast<PHINode>(I);
  2542. if (!AlternativeV)
  2543. break;
  2544. assert(Succ->hasNPredecessors(2));
  2545. auto PredI = pred_begin(Succ);
  2546. BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
  2547. if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
  2548. break;
  2549. PHI = nullptr;
  2550. }
  2551. if (PHI)
  2552. return PHI;
  2553. // If V is not an instruction defined in BB, just return it.
  2554. if (!AlternativeV &&
  2555. (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
  2556. return V;
  2557. PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
  2558. PHI->addIncoming(V, BB);
  2559. for (BasicBlock *PredBB : predecessors(Succ))
  2560. if (PredBB != BB)
  2561. PHI->addIncoming(
  2562. AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
  2563. return PHI;
  2564. }
  2565. static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
  2566. BasicBlock *QTB, BasicBlock *QFB,
  2567. BasicBlock *PostBB, Value *Address,
  2568. bool InvertPCond, bool InvertQCond,
  2569. const DataLayout &DL) {
  2570. auto IsaBitcastOfPointerType = [](const Instruction &I) {
  2571. return Operator::getOpcode(&I) == Instruction::BitCast &&
  2572. I.getType()->isPointerTy();
  2573. };
  2574. // If we're not in aggressive mode, we only optimize if we have some
  2575. // confidence that by optimizing we'll allow P and/or Q to be if-converted.
  2576. auto IsWorthwhile = [&](BasicBlock *BB) {
  2577. if (!BB)
  2578. return true;
  2579. // Heuristic: if the block can be if-converted/phi-folded and the
  2580. // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
  2581. // thread this store.
  2582. unsigned N = 0;
  2583. for (auto &I : BB->instructionsWithoutDebug()) {
  2584. // Cheap instructions viable for folding.
  2585. if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
  2586. isa<StoreInst>(I))
  2587. ++N;
  2588. // Free instructions.
  2589. else if (I.isTerminator() || IsaBitcastOfPointerType(I))
  2590. continue;
  2591. else
  2592. return false;
  2593. }
  2594. // The store we want to merge is counted in N, so add 1 to make sure
  2595. // we're counting the instructions that would be left.
  2596. return N <= (PHINodeFoldingThreshold + 1);
  2597. };
  2598. if (!MergeCondStoresAggressively &&
  2599. (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
  2600. !IsWorthwhile(QFB)))
  2601. return false;
  2602. // For every pointer, there must be exactly two stores, one coming from
  2603. // PTB or PFB, and the other from QTB or QFB. We don't support more than one
  2604. // store (to any address) in PTB,PFB or QTB,QFB.
  2605. // FIXME: We could relax this restriction with a bit more work and performance
  2606. // testing.
  2607. StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
  2608. StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
  2609. if (!PStore || !QStore)
  2610. return false;
  2611. // Now check the stores are compatible.
  2612. if (!QStore->isUnordered() || !PStore->isUnordered())
  2613. return false;
  2614. // Check that sinking the store won't cause program behavior changes. Sinking
  2615. // the store out of the Q blocks won't change any behavior as we're sinking
  2616. // from a block to its unconditional successor. But we're moving a store from
  2617. // the P blocks down through the middle block (QBI) and past both QFB and QTB.
  2618. // So we need to check that there are no aliasing loads or stores in
  2619. // QBI, QTB and QFB. We also need to check there are no conflicting memory
  2620. // operations between PStore and the end of its parent block.
  2621. //
  2622. // The ideal way to do this is to query AliasAnalysis, but we don't
  2623. // preserve AA currently so that is dangerous. Be super safe and just
  2624. // check there are no other memory operations at all.
  2625. for (auto &I : *QFB->getSinglePredecessor())
  2626. if (I.mayReadOrWriteMemory())
  2627. return false;
  2628. for (auto &I : *QFB)
  2629. if (&I != QStore && I.mayReadOrWriteMemory())
  2630. return false;
  2631. if (QTB)
  2632. for (auto &I : *QTB)
  2633. if (&I != QStore && I.mayReadOrWriteMemory())
  2634. return false;
  2635. for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
  2636. I != E; ++I)
  2637. if (&*I != PStore && I->mayReadOrWriteMemory())
  2638. return false;
  2639. // If PostBB has more than two predecessors, we need to split it so we can
  2640. // sink the store.
  2641. if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
  2642. // We know that QFB's only successor is PostBB. And QFB has a single
  2643. // predecessor. If QTB exists, then its only successor is also PostBB.
  2644. // If QTB does not exist, then QFB's only predecessor has a conditional
  2645. // branch to QFB and PostBB.
  2646. BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
  2647. BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
  2648. "condstore.split");
  2649. if (!NewBB)
  2650. return false;
  2651. PostBB = NewBB;
  2652. }
  2653. // OK, we're going to sink the stores to PostBB. The store has to be
  2654. // conditional though, so first create the predicate.
  2655. Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
  2656. ->getCondition();
  2657. Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
  2658. ->getCondition();
  2659. Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
  2660. PStore->getParent());
  2661. Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
  2662. QStore->getParent(), PPHI);
  2663. IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
  2664. Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
  2665. Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
  2666. if (InvertPCond)
  2667. PPred = QB.CreateNot(PPred);
  2668. if (InvertQCond)
  2669. QPred = QB.CreateNot(QPred);
  2670. Value *CombinedPred = QB.CreateOr(PPred, QPred);
  2671. auto *T =
  2672. SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
  2673. QB.SetInsertPoint(T);
  2674. StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
  2675. AAMDNodes AAMD;
  2676. PStore->getAAMetadata(AAMD, /*Merge=*/false);
  2677. PStore->getAAMetadata(AAMD, /*Merge=*/true);
  2678. SI->setAAMetadata(AAMD);
  2679. unsigned PAlignment = PStore->getAlignment();
  2680. unsigned QAlignment = QStore->getAlignment();
  2681. unsigned TypeAlignment =
  2682. DL.getABITypeAlignment(SI->getValueOperand()->getType());
  2683. unsigned MinAlignment;
  2684. unsigned MaxAlignment;
  2685. std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
  2686. // Choose the minimum alignment. If we could prove both stores execute, we
  2687. // could use biggest one. In this case, though, we only know that one of the
  2688. // stores executes. And we don't know it's safe to take the alignment from a
  2689. // store that doesn't execute.
  2690. if (MinAlignment != 0) {
  2691. // Choose the minimum of all non-zero alignments.
  2692. SI->setAlignment(MinAlignment);
  2693. } else if (MaxAlignment != 0) {
  2694. // Choose the minimal alignment between the non-zero alignment and the ABI
  2695. // default alignment for the type of the stored value.
  2696. SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
  2697. } else {
  2698. // If both alignments are zero, use ABI default alignment for the type of
  2699. // the stored value.
  2700. SI->setAlignment(TypeAlignment);
  2701. }
  2702. QStore->eraseFromParent();
  2703. PStore->eraseFromParent();
  2704. return true;
  2705. }
  2706. static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
  2707. const DataLayout &DL) {
  2708. // The intention here is to find diamonds or triangles (see below) where each
  2709. // conditional block contains a store to the same address. Both of these
  2710. // stores are conditional, so they can't be unconditionally sunk. But it may
  2711. // be profitable to speculatively sink the stores into one merged store at the
  2712. // end, and predicate the merged store on the union of the two conditions of
  2713. // PBI and QBI.
  2714. //
  2715. // This can reduce the number of stores executed if both of the conditions are
  2716. // true, and can allow the blocks to become small enough to be if-converted.
  2717. // This optimization will also chain, so that ladders of test-and-set
  2718. // sequences can be if-converted away.
  2719. //
  2720. // We only deal with simple diamonds or triangles:
  2721. //
  2722. // PBI or PBI or a combination of the two
  2723. // / \ | \
  2724. // PTB PFB | PFB
  2725. // \ / | /
  2726. // QBI QBI
  2727. // / \ | \
  2728. // QTB QFB | QFB
  2729. // \ / | /
  2730. // PostBB PostBB
  2731. //
  2732. // We model triangles as a type of diamond with a nullptr "true" block.
  2733. // Triangles are canonicalized so that the fallthrough edge is represented by
  2734. // a true condition, as in the diagram above.
  2735. BasicBlock *PTB = PBI->getSuccessor(0);
  2736. BasicBlock *PFB = PBI->getSuccessor(1);
  2737. BasicBlock *QTB = QBI->getSuccessor(0);
  2738. BasicBlock *QFB = QBI->getSuccessor(1);
  2739. BasicBlock *PostBB = QFB->getSingleSuccessor();
  2740. // Make sure we have a good guess for PostBB. If QTB's only successor is
  2741. // QFB, then QFB is a better PostBB.
  2742. if (QTB->getSingleSuccessor() == QFB)
  2743. PostBB = QFB;
  2744. // If we couldn't find a good PostBB, stop.
  2745. if (!PostBB)
  2746. return false;
  2747. bool InvertPCond = false, InvertQCond = false;
  2748. // Canonicalize fallthroughs to the true branches.
  2749. if (PFB == QBI->getParent()) {
  2750. std::swap(PFB, PTB);
  2751. InvertPCond = true;
  2752. }
  2753. if (QFB == PostBB) {
  2754. std::swap(QFB, QTB);
  2755. InvertQCond = true;
  2756. }
  2757. // From this point on we can assume PTB or QTB may be fallthroughs but PFB
  2758. // and QFB may not. Model fallthroughs as a nullptr block.
  2759. if (PTB == QBI->getParent())
  2760. PTB = nullptr;
  2761. if (QTB == PostBB)
  2762. QTB = nullptr;
  2763. // Legality bailouts. We must have at least the non-fallthrough blocks and
  2764. // the post-dominating block, and the non-fallthroughs must only have one
  2765. // predecessor.
  2766. auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
  2767. return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
  2768. };
  2769. if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
  2770. !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
  2771. return false;
  2772. if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
  2773. (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
  2774. return false;
  2775. if (!QBI->getParent()->hasNUses(2))
  2776. return false;
  2777. // OK, this is a sequence of two diamonds or triangles.
  2778. // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
  2779. SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
  2780. for (auto *BB : {PTB, PFB}) {
  2781. if (!BB)
  2782. continue;
  2783. for (auto &I : *BB)
  2784. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2785. PStoreAddresses.insert(SI->getPointerOperand());
  2786. }
  2787. for (auto *BB : {QTB, QFB}) {
  2788. if (!BB)
  2789. continue;
  2790. for (auto &I : *BB)
  2791. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2792. QStoreAddresses.insert(SI->getPointerOperand());
  2793. }
  2794. set_intersect(PStoreAddresses, QStoreAddresses);
  2795. // set_intersect mutates PStoreAddresses in place. Rename it here to make it
  2796. // clear what it contains.
  2797. auto &CommonAddresses = PStoreAddresses;
  2798. bool Changed = false;
  2799. for (auto *Address : CommonAddresses)
  2800. Changed |= mergeConditionalStoreToAddress(
  2801. PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
  2802. return Changed;
  2803. }
  2804. /// If we have a conditional branch as a predecessor of another block,
  2805. /// this function tries to simplify it. We know
  2806. /// that PBI and BI are both conditional branches, and BI is in one of the
  2807. /// successor blocks of PBI - PBI branches to BI.
  2808. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
  2809. const DataLayout &DL) {
  2810. assert(PBI->isConditional() && BI->isConditional());
  2811. BasicBlock *BB = BI->getParent();
  2812. // If this block ends with a branch instruction, and if there is a
  2813. // predecessor that ends on a branch of the same condition, make
  2814. // this conditional branch redundant.
  2815. if (PBI->getCondition() == BI->getCondition() &&
  2816. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2817. // Okay, the outcome of this conditional branch is statically
  2818. // knowable. If this block had a single pred, handle specially.
  2819. if (BB->getSinglePredecessor()) {
  2820. // Turn this into a branch on constant.
  2821. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2822. BI->setCondition(
  2823. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
  2824. return true; // Nuke the branch on constant.
  2825. }
  2826. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2827. // in the constant and simplify the block result. Subsequent passes of
  2828. // simplifycfg will thread the block.
  2829. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2830. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2831. PHINode *NewPN = PHINode::Create(
  2832. Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
  2833. BI->getCondition()->getName() + ".pr", &BB->front());
  2834. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2835. // predecessor, compute the PHI'd conditional value for all of the preds.
  2836. // Any predecessor where the condition is not computable we keep symbolic.
  2837. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2838. BasicBlock *P = *PI;
  2839. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
  2840. PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
  2841. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2842. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2843. NewPN->addIncoming(
  2844. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
  2845. P);
  2846. } else {
  2847. NewPN->addIncoming(BI->getCondition(), P);
  2848. }
  2849. }
  2850. BI->setCondition(NewPN);
  2851. return true;
  2852. }
  2853. }
  2854. if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2855. if (CE->canTrap())
  2856. return false;
  2857. // If both branches are conditional and both contain stores to the same
  2858. // address, remove the stores from the conditionals and create a conditional
  2859. // merged store at the end.
  2860. if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
  2861. return true;
  2862. // If this is a conditional branch in an empty block, and if any
  2863. // predecessors are a conditional branch to one of our destinations,
  2864. // fold the conditions into logical ops and one cond br.
  2865. // Ignore dbg intrinsics.
  2866. if (&*BB->instructionsWithoutDebug().begin() != BI)
  2867. return false;
  2868. int PBIOp, BIOp;
  2869. if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
  2870. PBIOp = 0;
  2871. BIOp = 0;
  2872. } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
  2873. PBIOp = 0;
  2874. BIOp = 1;
  2875. } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
  2876. PBIOp = 1;
  2877. BIOp = 0;
  2878. } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
  2879. PBIOp = 1;
  2880. BIOp = 1;
  2881. } else {
  2882. return false;
  2883. }
  2884. // Check to make sure that the other destination of this branch
  2885. // isn't BB itself. If so, this is an infinite loop that will
  2886. // keep getting unwound.
  2887. if (PBI->getSuccessor(PBIOp) == BB)
  2888. return false;
  2889. // Do not perform this transformation if it would require
  2890. // insertion of a large number of select instructions. For targets
  2891. // without predication/cmovs, this is a big pessimization.
  2892. // Also do not perform this transformation if any phi node in the common
  2893. // destination block can trap when reached by BB or PBB (PR17073). In that
  2894. // case, it would be unsafe to hoist the operation into a select instruction.
  2895. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2896. unsigned NumPhis = 0;
  2897. for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
  2898. ++II, ++NumPhis) {
  2899. if (NumPhis > 2) // Disable this xform.
  2900. return false;
  2901. PHINode *PN = cast<PHINode>(II);
  2902. Value *BIV = PN->getIncomingValueForBlock(BB);
  2903. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2904. if (CE->canTrap())
  2905. return false;
  2906. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2907. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2908. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2909. if (CE->canTrap())
  2910. return false;
  2911. }
  2912. // Finally, if everything is ok, fold the branches to logical ops.
  2913. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2914. LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2915. << "AND: " << *BI->getParent());
  2916. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2917. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2918. // exits. We don't *know* that the program avoids the infinite loop
  2919. // (even though that seems likely). If we do this xform naively, we'll end up
  2920. // recursively unpeeling the loop. Since we know that (after the xform is
  2921. // done) that the block *is* infinite if reached, we just make it an obviously
  2922. // infinite loop with no cond branch.
  2923. if (OtherDest == BB) {
  2924. // Insert it at the end of the function, because it's either code,
  2925. // or it won't matter if it's hot. :)
  2926. BasicBlock *InfLoopBlock =
  2927. BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
  2928. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2929. OtherDest = InfLoopBlock;
  2930. }
  2931. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  2932. // BI may have other predecessors. Because of this, we leave
  2933. // it alone, but modify PBI.
  2934. // Make sure we get to CommonDest on True&True directions.
  2935. Value *PBICond = PBI->getCondition();
  2936. IRBuilder<NoFolder> Builder(PBI);
  2937. if (PBIOp)
  2938. PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
  2939. Value *BICond = BI->getCondition();
  2940. if (BIOp)
  2941. BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
  2942. // Merge the conditions.
  2943. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2944. // Modify PBI to branch on the new condition to the new dests.
  2945. PBI->setCondition(Cond);
  2946. PBI->setSuccessor(0, CommonDest);
  2947. PBI->setSuccessor(1, OtherDest);
  2948. // Update branch weight for PBI.
  2949. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2950. uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
  2951. bool HasWeights =
  2952. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2953. SuccTrueWeight, SuccFalseWeight);
  2954. if (HasWeights) {
  2955. PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2956. PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  2957. SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2958. SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2959. // The weight to CommonDest should be PredCommon * SuccTotal +
  2960. // PredOther * SuccCommon.
  2961. // The weight to OtherDest should be PredOther * SuccOther.
  2962. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
  2963. PredOther * SuccCommon,
  2964. PredOther * SuccOther};
  2965. // Halve the weights if any of them cannot fit in an uint32_t
  2966. FitWeights(NewWeights);
  2967. setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
  2968. }
  2969. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2970. // block that are identical to the entries for BI's block.
  2971. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2972. // We know that the CommonDest already had an edge from PBI to
  2973. // it. If it has PHIs though, the PHIs may have different
  2974. // entries for BB and PBI's BB. If so, insert a select to make
  2975. // them agree.
  2976. for (PHINode &PN : CommonDest->phis()) {
  2977. Value *BIV = PN.getIncomingValueForBlock(BB);
  2978. unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
  2979. Value *PBIV = PN.getIncomingValue(PBBIdx);
  2980. if (BIV != PBIV) {
  2981. // Insert a select in PBI to pick the right value.
  2982. SelectInst *NV = cast<SelectInst>(
  2983. Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
  2984. PN.setIncomingValue(PBBIdx, NV);
  2985. // Although the select has the same condition as PBI, the original branch
  2986. // weights for PBI do not apply to the new select because the select's
  2987. // 'logical' edges are incoming edges of the phi that is eliminated, not
  2988. // the outgoing edges of PBI.
  2989. if (HasWeights) {
  2990. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2991. uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  2992. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2993. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2994. // The weight to PredCommonDest should be PredCommon * SuccTotal.
  2995. // The weight to PredOtherDest should be PredOther * SuccCommon.
  2996. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
  2997. PredOther * SuccCommon};
  2998. FitWeights(NewWeights);
  2999. setBranchWeights(NV, NewWeights[0], NewWeights[1]);
  3000. }
  3001. }
  3002. }
  3003. LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  3004. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  3005. // This basic block is probably dead. We know it has at least
  3006. // one fewer predecessor.
  3007. return true;
  3008. }
  3009. // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
  3010. // true or to FalseBB if Cond is false.
  3011. // Takes care of updating the successors and removing the old terminator.
  3012. // Also makes sure not to introduce new successors by assuming that edges to
  3013. // non-successor TrueBBs and FalseBBs aren't reachable.
  3014. static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
  3015. BasicBlock *TrueBB, BasicBlock *FalseBB,
  3016. uint32_t TrueWeight,
  3017. uint32_t FalseWeight) {
  3018. // Remove any superfluous successor edges from the CFG.
  3019. // First, figure out which successors to preserve.
  3020. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  3021. // successor.
  3022. BasicBlock *KeepEdge1 = TrueBB;
  3023. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  3024. // Then remove the rest.
  3025. for (BasicBlock *Succ : successors(OldTerm)) {
  3026. // Make sure only to keep exactly one copy of each edge.
  3027. if (Succ == KeepEdge1)
  3028. KeepEdge1 = nullptr;
  3029. else if (Succ == KeepEdge2)
  3030. KeepEdge2 = nullptr;
  3031. else
  3032. Succ->removePredecessor(OldTerm->getParent(),
  3033. /*KeepOneInputPHIs=*/true);
  3034. }
  3035. IRBuilder<> Builder(OldTerm);
  3036. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  3037. // Insert an appropriate new terminator.
  3038. if (!KeepEdge1 && !KeepEdge2) {
  3039. if (TrueBB == FalseBB)
  3040. // We were only looking for one successor, and it was present.
  3041. // Create an unconditional branch to it.
  3042. Builder.CreateBr(TrueBB);
  3043. else {
  3044. // We found both of the successors we were looking for.
  3045. // Create a conditional branch sharing the condition of the select.
  3046. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  3047. if (TrueWeight != FalseWeight)
  3048. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3049. }
  3050. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  3051. // Neither of the selected blocks were successors, so this
  3052. // terminator must be unreachable.
  3053. new UnreachableInst(OldTerm->getContext(), OldTerm);
  3054. } else {
  3055. // One of the selected values was a successor, but the other wasn't.
  3056. // Insert an unconditional branch to the one that was found;
  3057. // the edge to the one that wasn't must be unreachable.
  3058. if (!KeepEdge1)
  3059. // Only TrueBB was found.
  3060. Builder.CreateBr(TrueBB);
  3061. else
  3062. // Only FalseBB was found.
  3063. Builder.CreateBr(FalseBB);
  3064. }
  3065. EraseTerminatorAndDCECond(OldTerm);
  3066. return true;
  3067. }
  3068. // Replaces
  3069. // (switch (select cond, X, Y)) on constant X, Y
  3070. // with a branch - conditional if X and Y lead to distinct BBs,
  3071. // unconditional otherwise.
  3072. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  3073. // Check for constant integer values in the select.
  3074. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  3075. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  3076. if (!TrueVal || !FalseVal)
  3077. return false;
  3078. // Find the relevant condition and destinations.
  3079. Value *Condition = Select->getCondition();
  3080. BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
  3081. BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
  3082. // Get weight for TrueBB and FalseBB.
  3083. uint32_t TrueWeight = 0, FalseWeight = 0;
  3084. SmallVector<uint64_t, 8> Weights;
  3085. bool HasWeights = HasBranchWeights(SI);
  3086. if (HasWeights) {
  3087. GetBranchWeights(SI, Weights);
  3088. if (Weights.size() == 1 + SI->getNumCases()) {
  3089. TrueWeight =
  3090. (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
  3091. FalseWeight =
  3092. (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
  3093. }
  3094. }
  3095. // Perform the actual simplification.
  3096. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
  3097. FalseWeight);
  3098. }
  3099. // Replaces
  3100. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  3101. // blockaddress(@fn, BlockB)))
  3102. // with
  3103. // (br cond, BlockA, BlockB).
  3104. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  3105. // Check that both operands of the select are block addresses.
  3106. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  3107. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  3108. if (!TBA || !FBA)
  3109. return false;
  3110. // Extract the actual blocks.
  3111. BasicBlock *TrueBB = TBA->getBasicBlock();
  3112. BasicBlock *FalseBB = FBA->getBasicBlock();
  3113. // Perform the actual simplification.
  3114. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
  3115. 0);
  3116. }
  3117. /// This is called when we find an icmp instruction
  3118. /// (a seteq/setne with a constant) as the only instruction in a
  3119. /// block that ends with an uncond branch. We are looking for a very specific
  3120. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  3121. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  3122. /// default value goes to an uncond block with a seteq in it, we get something
  3123. /// like:
  3124. ///
  3125. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  3126. /// DEFAULT:
  3127. /// %tmp = icmp eq i8 %A, 92
  3128. /// br label %end
  3129. /// end:
  3130. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  3131. ///
  3132. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  3133. /// the PHI, merging the third icmp into the switch.
  3134. bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
  3135. ICmpInst *ICI, IRBuilder<> &Builder) {
  3136. BasicBlock *BB = ICI->getParent();
  3137. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  3138. // complex.
  3139. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
  3140. return false;
  3141. Value *V = ICI->getOperand(0);
  3142. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  3143. // The pattern we're looking for is where our only predecessor is a switch on
  3144. // 'V' and this block is the default case for the switch. In this case we can
  3145. // fold the compared value into the switch to simplify things.
  3146. BasicBlock *Pred = BB->getSinglePredecessor();
  3147. if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
  3148. return false;
  3149. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  3150. if (SI->getCondition() != V)
  3151. return false;
  3152. // If BB is reachable on a non-default case, then we simply know the value of
  3153. // V in this block. Substitute it and constant fold the icmp instruction
  3154. // away.
  3155. if (SI->getDefaultDest() != BB) {
  3156. ConstantInt *VVal = SI->findCaseDest(BB);
  3157. assert(VVal && "Should have a unique destination value");
  3158. ICI->setOperand(0, VVal);
  3159. if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
  3160. ICI->replaceAllUsesWith(V);
  3161. ICI->eraseFromParent();
  3162. }
  3163. // BB is now empty, so it is likely to simplify away.
  3164. return requestResimplify();
  3165. }
  3166. // Ok, the block is reachable from the default dest. If the constant we're
  3167. // comparing exists in one of the other edges, then we can constant fold ICI
  3168. // and zap it.
  3169. if (SI->findCaseValue(Cst) != SI->case_default()) {
  3170. Value *V;
  3171. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3172. V = ConstantInt::getFalse(BB->getContext());
  3173. else
  3174. V = ConstantInt::getTrue(BB->getContext());
  3175. ICI->replaceAllUsesWith(V);
  3176. ICI->eraseFromParent();
  3177. // BB is now empty, so it is likely to simplify away.
  3178. return requestResimplify();
  3179. }
  3180. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  3181. // the block.
  3182. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  3183. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  3184. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  3185. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  3186. return false;
  3187. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  3188. // true in the PHI.
  3189. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  3190. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  3191. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3192. std::swap(DefaultCst, NewCst);
  3193. // Replace ICI (which is used by the PHI for the default value) with true or
  3194. // false depending on if it is EQ or NE.
  3195. ICI->replaceAllUsesWith(DefaultCst);
  3196. ICI->eraseFromParent();
  3197. // Okay, the switch goes to this block on a default value. Add an edge from
  3198. // the switch to the merge point on the compared value.
  3199. BasicBlock *NewBB =
  3200. BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
  3201. {
  3202. SwitchInstProfUpdateWrapper SIW(*SI);
  3203. auto W0 = SIW.getSuccessorWeight(0);
  3204. SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
  3205. if (W0) {
  3206. NewW = ((uint64_t(*W0) + 1) >> 1);
  3207. SIW.setSuccessorWeight(0, *NewW);
  3208. }
  3209. SIW.addCase(Cst, NewBB, NewW);
  3210. }
  3211. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  3212. Builder.SetInsertPoint(NewBB);
  3213. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  3214. Builder.CreateBr(SuccBlock);
  3215. PHIUse->addIncoming(NewCst, NewBB);
  3216. return true;
  3217. }
  3218. /// The specified branch is a conditional branch.
  3219. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  3220. /// fold it into a switch instruction if so.
  3221. static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
  3222. const DataLayout &DL) {
  3223. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  3224. if (!Cond)
  3225. return false;
  3226. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  3227. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  3228. // 'setne's and'ed together, collect them.
  3229. // Try to gather values from a chain of and/or to be turned into a switch
  3230. ConstantComparesGatherer ConstantCompare(Cond, DL);
  3231. // Unpack the result
  3232. SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
  3233. Value *CompVal = ConstantCompare.CompValue;
  3234. unsigned UsedICmps = ConstantCompare.UsedICmps;
  3235. Value *ExtraCase = ConstantCompare.Extra;
  3236. // If we didn't have a multiply compared value, fail.
  3237. if (!CompVal)
  3238. return false;
  3239. // Avoid turning single icmps into a switch.
  3240. if (UsedICmps <= 1)
  3241. return false;
  3242. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  3243. // There might be duplicate constants in the list, which the switch
  3244. // instruction can't handle, remove them now.
  3245. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  3246. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  3247. // If Extra was used, we require at least two switch values to do the
  3248. // transformation. A switch with one value is just a conditional branch.
  3249. if (ExtraCase && Values.size() < 2)
  3250. return false;
  3251. // TODO: Preserve branch weight metadata, similarly to how
  3252. // FoldValueComparisonIntoPredecessors preserves it.
  3253. // Figure out which block is which destination.
  3254. BasicBlock *DefaultBB = BI->getSuccessor(1);
  3255. BasicBlock *EdgeBB = BI->getSuccessor(0);
  3256. if (!TrueWhenEqual)
  3257. std::swap(DefaultBB, EdgeBB);
  3258. BasicBlock *BB = BI->getParent();
  3259. LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  3260. << " cases into SWITCH. BB is:\n"
  3261. << *BB);
  3262. // If there are any extra values that couldn't be folded into the switch
  3263. // then we evaluate them with an explicit branch first. Split the block
  3264. // right before the condbr to handle it.
  3265. if (ExtraCase) {
  3266. BasicBlock *NewBB =
  3267. BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
  3268. // Remove the uncond branch added to the old block.
  3269. Instruction *OldTI = BB->getTerminator();
  3270. Builder.SetInsertPoint(OldTI);
  3271. if (TrueWhenEqual)
  3272. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  3273. else
  3274. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  3275. OldTI->eraseFromParent();
  3276. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  3277. // for the edge we just added.
  3278. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  3279. LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  3280. << "\nEXTRABB = " << *BB);
  3281. BB = NewBB;
  3282. }
  3283. Builder.SetInsertPoint(BI);
  3284. // Convert pointer to int before we switch.
  3285. if (CompVal->getType()->isPointerTy()) {
  3286. CompVal = Builder.CreatePtrToInt(
  3287. CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
  3288. }
  3289. // Create the new switch instruction now.
  3290. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  3291. // Add all of the 'cases' to the switch instruction.
  3292. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  3293. New->addCase(Values[i], EdgeBB);
  3294. // We added edges from PI to the EdgeBB. As such, if there were any
  3295. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  3296. // the number of edges added.
  3297. for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
  3298. PHINode *PN = cast<PHINode>(BBI);
  3299. Value *InVal = PN->getIncomingValueForBlock(BB);
  3300. for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
  3301. PN->addIncoming(InVal, BB);
  3302. }
  3303. // Erase the old branch instruction.
  3304. EraseTerminatorAndDCECond(BI);
  3305. LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  3306. return true;
  3307. }
  3308. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  3309. if (isa<PHINode>(RI->getValue()))
  3310. return SimplifyCommonResume(RI);
  3311. else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
  3312. RI->getValue() == RI->getParent()->getFirstNonPHI())
  3313. // The resume must unwind the exception that caused control to branch here.
  3314. return SimplifySingleResume(RI);
  3315. return false;
  3316. }
  3317. // Simplify resume that is shared by several landing pads (phi of landing pad).
  3318. bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
  3319. BasicBlock *BB = RI->getParent();
  3320. // Check that there are no other instructions except for debug intrinsics
  3321. // between the phi of landing pads (RI->getValue()) and resume instruction.
  3322. BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
  3323. E = RI->getIterator();
  3324. while (++I != E)
  3325. if (!isa<DbgInfoIntrinsic>(I))
  3326. return false;
  3327. SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
  3328. auto *PhiLPInst = cast<PHINode>(RI->getValue());
  3329. // Check incoming blocks to see if any of them are trivial.
  3330. for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
  3331. Idx++) {
  3332. auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
  3333. auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
  3334. // If the block has other successors, we can not delete it because
  3335. // it has other dependents.
  3336. if (IncomingBB->getUniqueSuccessor() != BB)
  3337. continue;
  3338. auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
  3339. // Not the landing pad that caused the control to branch here.
  3340. if (IncomingValue != LandingPad)
  3341. continue;
  3342. bool isTrivial = true;
  3343. I = IncomingBB->getFirstNonPHI()->getIterator();
  3344. E = IncomingBB->getTerminator()->getIterator();
  3345. while (++I != E)
  3346. if (!isa<DbgInfoIntrinsic>(I)) {
  3347. isTrivial = false;
  3348. break;
  3349. }
  3350. if (isTrivial)
  3351. TrivialUnwindBlocks.insert(IncomingBB);
  3352. }
  3353. // If no trivial unwind blocks, don't do any simplifications.
  3354. if (TrivialUnwindBlocks.empty())
  3355. return false;
  3356. // Turn all invokes that unwind here into calls.
  3357. for (auto *TrivialBB : TrivialUnwindBlocks) {
  3358. // Blocks that will be simplified should be removed from the phi node.
  3359. // Note there could be multiple edges to the resume block, and we need
  3360. // to remove them all.
  3361. while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
  3362. BB->removePredecessor(TrivialBB, true);
  3363. for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
  3364. PI != PE;) {
  3365. BasicBlock *Pred = *PI++;
  3366. removeUnwindEdge(Pred);
  3367. }
  3368. // In each SimplifyCFG run, only the current processed block can be erased.
  3369. // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
  3370. // of erasing TrivialBB, we only remove the branch to the common resume
  3371. // block so that we can later erase the resume block since it has no
  3372. // predecessors.
  3373. TrivialBB->getTerminator()->eraseFromParent();
  3374. new UnreachableInst(RI->getContext(), TrivialBB);
  3375. }
  3376. // Delete the resume block if all its predecessors have been removed.
  3377. if (pred_empty(BB))
  3378. BB->eraseFromParent();
  3379. return !TrivialUnwindBlocks.empty();
  3380. }
  3381. // Simplify resume that is only used by a single (non-phi) landing pad.
  3382. bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
  3383. BasicBlock *BB = RI->getParent();
  3384. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  3385. assert(RI->getValue() == LPInst &&
  3386. "Resume must unwind the exception that caused control to here");
  3387. // Check that there are no other instructions except for debug intrinsics.
  3388. BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
  3389. while (++I != E)
  3390. if (!isa<DbgInfoIntrinsic>(I))
  3391. return false;
  3392. // Turn all invokes that unwind here into calls and delete the basic block.
  3393. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3394. BasicBlock *Pred = *PI++;
  3395. removeUnwindEdge(Pred);
  3396. }
  3397. // The landingpad is now unreachable. Zap it.
  3398. if (LoopHeaders)
  3399. LoopHeaders->erase(BB);
  3400. BB->eraseFromParent();
  3401. return true;
  3402. }
  3403. static bool removeEmptyCleanup(CleanupReturnInst *RI) {
  3404. // If this is a trivial cleanup pad that executes no instructions, it can be
  3405. // eliminated. If the cleanup pad continues to the caller, any predecessor
  3406. // that is an EH pad will be updated to continue to the caller and any
  3407. // predecessor that terminates with an invoke instruction will have its invoke
  3408. // instruction converted to a call instruction. If the cleanup pad being
  3409. // simplified does not continue to the caller, each predecessor will be
  3410. // updated to continue to the unwind destination of the cleanup pad being
  3411. // simplified.
  3412. BasicBlock *BB = RI->getParent();
  3413. CleanupPadInst *CPInst = RI->getCleanupPad();
  3414. if (CPInst->getParent() != BB)
  3415. // This isn't an empty cleanup.
  3416. return false;
  3417. // We cannot kill the pad if it has multiple uses. This typically arises
  3418. // from unreachable basic blocks.
  3419. if (!CPInst->hasOneUse())
  3420. return false;
  3421. // Check that there are no other instructions except for benign intrinsics.
  3422. BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
  3423. while (++I != E) {
  3424. auto *II = dyn_cast<IntrinsicInst>(I);
  3425. if (!II)
  3426. return false;
  3427. Intrinsic::ID IntrinsicID = II->getIntrinsicID();
  3428. switch (IntrinsicID) {
  3429. case Intrinsic::dbg_declare:
  3430. case Intrinsic::dbg_value:
  3431. case Intrinsic::dbg_label:
  3432. case Intrinsic::lifetime_end:
  3433. break;
  3434. default:
  3435. return false;
  3436. }
  3437. }
  3438. // If the cleanup return we are simplifying unwinds to the caller, this will
  3439. // set UnwindDest to nullptr.
  3440. BasicBlock *UnwindDest = RI->getUnwindDest();
  3441. Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
  3442. // We're about to remove BB from the control flow. Before we do, sink any
  3443. // PHINodes into the unwind destination. Doing this before changing the
  3444. // control flow avoids some potentially slow checks, since we can currently
  3445. // be certain that UnwindDest and BB have no common predecessors (since they
  3446. // are both EH pads).
  3447. if (UnwindDest) {
  3448. // First, go through the PHI nodes in UnwindDest and update any nodes that
  3449. // reference the block we are removing
  3450. for (BasicBlock::iterator I = UnwindDest->begin(),
  3451. IE = DestEHPad->getIterator();
  3452. I != IE; ++I) {
  3453. PHINode *DestPN = cast<PHINode>(I);
  3454. int Idx = DestPN->getBasicBlockIndex(BB);
  3455. // Since BB unwinds to UnwindDest, it has to be in the PHI node.
  3456. assert(Idx != -1);
  3457. // This PHI node has an incoming value that corresponds to a control
  3458. // path through the cleanup pad we are removing. If the incoming
  3459. // value is in the cleanup pad, it must be a PHINode (because we
  3460. // verified above that the block is otherwise empty). Otherwise, the
  3461. // value is either a constant or a value that dominates the cleanup
  3462. // pad being removed.
  3463. //
  3464. // Because BB and UnwindDest are both EH pads, all of their
  3465. // predecessors must unwind to these blocks, and since no instruction
  3466. // can have multiple unwind destinations, there will be no overlap in
  3467. // incoming blocks between SrcPN and DestPN.
  3468. Value *SrcVal = DestPN->getIncomingValue(Idx);
  3469. PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
  3470. // Remove the entry for the block we are deleting.
  3471. DestPN->removeIncomingValue(Idx, false);
  3472. if (SrcPN && SrcPN->getParent() == BB) {
  3473. // If the incoming value was a PHI node in the cleanup pad we are
  3474. // removing, we need to merge that PHI node's incoming values into
  3475. // DestPN.
  3476. for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
  3477. SrcIdx != SrcE; ++SrcIdx) {
  3478. DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
  3479. SrcPN->getIncomingBlock(SrcIdx));
  3480. }
  3481. } else {
  3482. // Otherwise, the incoming value came from above BB and
  3483. // so we can just reuse it. We must associate all of BB's
  3484. // predecessors with this value.
  3485. for (auto *pred : predecessors(BB)) {
  3486. DestPN->addIncoming(SrcVal, pred);
  3487. }
  3488. }
  3489. }
  3490. // Sink any remaining PHI nodes directly into UnwindDest.
  3491. Instruction *InsertPt = DestEHPad;
  3492. for (BasicBlock::iterator I = BB->begin(),
  3493. IE = BB->getFirstNonPHI()->getIterator();
  3494. I != IE;) {
  3495. // The iterator must be incremented here because the instructions are
  3496. // being moved to another block.
  3497. PHINode *PN = cast<PHINode>(I++);
  3498. if (PN->use_empty())
  3499. // If the PHI node has no uses, just leave it. It will be erased
  3500. // when we erase BB below.
  3501. continue;
  3502. // Otherwise, sink this PHI node into UnwindDest.
  3503. // Any predecessors to UnwindDest which are not already represented
  3504. // must be back edges which inherit the value from the path through
  3505. // BB. In this case, the PHI value must reference itself.
  3506. for (auto *pred : predecessors(UnwindDest))
  3507. if (pred != BB)
  3508. PN->addIncoming(PN, pred);
  3509. PN->moveBefore(InsertPt);
  3510. }
  3511. }
  3512. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3513. // The iterator must be updated here because we are removing this pred.
  3514. BasicBlock *PredBB = *PI++;
  3515. if (UnwindDest == nullptr) {
  3516. removeUnwindEdge(PredBB);
  3517. } else {
  3518. Instruction *TI = PredBB->getTerminator();
  3519. TI->replaceUsesOfWith(BB, UnwindDest);
  3520. }
  3521. }
  3522. // The cleanup pad is now unreachable. Zap it.
  3523. BB->eraseFromParent();
  3524. return true;
  3525. }
  3526. // Try to merge two cleanuppads together.
  3527. static bool mergeCleanupPad(CleanupReturnInst *RI) {
  3528. // Skip any cleanuprets which unwind to caller, there is nothing to merge
  3529. // with.
  3530. BasicBlock *UnwindDest = RI->getUnwindDest();
  3531. if (!UnwindDest)
  3532. return false;
  3533. // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
  3534. // be safe to merge without code duplication.
  3535. if (UnwindDest->getSinglePredecessor() != RI->getParent())
  3536. return false;
  3537. // Verify that our cleanuppad's unwind destination is another cleanuppad.
  3538. auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
  3539. if (!SuccessorCleanupPad)
  3540. return false;
  3541. CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
  3542. // Replace any uses of the successor cleanupad with the predecessor pad
  3543. // The only cleanuppad uses should be this cleanupret, it's cleanupret and
  3544. // funclet bundle operands.
  3545. SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
  3546. // Remove the old cleanuppad.
  3547. SuccessorCleanupPad->eraseFromParent();
  3548. // Now, we simply replace the cleanupret with a branch to the unwind
  3549. // destination.
  3550. BranchInst::Create(UnwindDest, RI->getParent());
  3551. RI->eraseFromParent();
  3552. return true;
  3553. }
  3554. bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
  3555. // It is possible to transiantly have an undef cleanuppad operand because we
  3556. // have deleted some, but not all, dead blocks.
  3557. // Eventually, this block will be deleted.
  3558. if (isa<UndefValue>(RI->getOperand(0)))
  3559. return false;
  3560. if (mergeCleanupPad(RI))
  3561. return true;
  3562. if (removeEmptyCleanup(RI))
  3563. return true;
  3564. return false;
  3565. }
  3566. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  3567. BasicBlock *BB = RI->getParent();
  3568. if (!BB->getFirstNonPHIOrDbg()->isTerminator())
  3569. return false;
  3570. // Find predecessors that end with branches.
  3571. SmallVector<BasicBlock *, 8> UncondBranchPreds;
  3572. SmallVector<BranchInst *, 8> CondBranchPreds;
  3573. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  3574. BasicBlock *P = *PI;
  3575. Instruction *PTI = P->getTerminator();
  3576. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  3577. if (BI->isUnconditional())
  3578. UncondBranchPreds.push_back(P);
  3579. else
  3580. CondBranchPreds.push_back(BI);
  3581. }
  3582. }
  3583. // If we found some, do the transformation!
  3584. if (!UncondBranchPreds.empty() && DupRet) {
  3585. while (!UncondBranchPreds.empty()) {
  3586. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  3587. LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
  3588. << "INTO UNCOND BRANCH PRED: " << *Pred);
  3589. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  3590. }
  3591. // If we eliminated all predecessors of the block, delete the block now.
  3592. if (pred_empty(BB)) {
  3593. // We know there are no successors, so just nuke the block.
  3594. if (LoopHeaders)
  3595. LoopHeaders->erase(BB);
  3596. BB->eraseFromParent();
  3597. }
  3598. return true;
  3599. }
  3600. // Check out all of the conditional branches going to this return
  3601. // instruction. If any of them just select between returns, change the
  3602. // branch itself into a select/return pair.
  3603. while (!CondBranchPreds.empty()) {
  3604. BranchInst *BI = CondBranchPreds.pop_back_val();
  3605. // Check to see if the non-BB successor is also a return block.
  3606. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  3607. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  3608. SimplifyCondBranchToTwoReturns(BI, Builder))
  3609. return true;
  3610. }
  3611. return false;
  3612. }
  3613. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  3614. BasicBlock *BB = UI->getParent();
  3615. bool Changed = false;
  3616. // If there are any instructions immediately before the unreachable that can
  3617. // be removed, do so.
  3618. while (UI->getIterator() != BB->begin()) {
  3619. BasicBlock::iterator BBI = UI->getIterator();
  3620. --BBI;
  3621. // Do not delete instructions that can have side effects which might cause
  3622. // the unreachable to not be reachable; specifically, calls and volatile
  3623. // operations may have this effect.
  3624. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
  3625. break;
  3626. if (BBI->mayHaveSideEffects()) {
  3627. if (auto *SI = dyn_cast<StoreInst>(BBI)) {
  3628. if (SI->isVolatile())
  3629. break;
  3630. } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
  3631. if (LI->isVolatile())
  3632. break;
  3633. } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  3634. if (RMWI->isVolatile())
  3635. break;
  3636. } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  3637. if (CXI->isVolatile())
  3638. break;
  3639. } else if (isa<CatchPadInst>(BBI)) {
  3640. // A catchpad may invoke exception object constructors and such, which
  3641. // in some languages can be arbitrary code, so be conservative by
  3642. // default.
  3643. // For CoreCLR, it just involves a type test, so can be removed.
  3644. if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
  3645. EHPersonality::CoreCLR)
  3646. break;
  3647. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  3648. !isa<LandingPadInst>(BBI)) {
  3649. break;
  3650. }
  3651. // Note that deleting LandingPad's here is in fact okay, although it
  3652. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  3653. // all the predecessors of this block will be the unwind edges of Invokes,
  3654. // and we can therefore guarantee this block will be erased.
  3655. }
  3656. // Delete this instruction (any uses are guaranteed to be dead)
  3657. if (!BBI->use_empty())
  3658. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  3659. BBI->eraseFromParent();
  3660. Changed = true;
  3661. }
  3662. // If the unreachable instruction is the first in the block, take a gander
  3663. // at all of the predecessors of this instruction, and simplify them.
  3664. if (&BB->front() != UI)
  3665. return Changed;
  3666. SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
  3667. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  3668. Instruction *TI = Preds[i]->getTerminator();
  3669. IRBuilder<> Builder(TI);
  3670. if (auto *BI = dyn_cast<BranchInst>(TI)) {
  3671. if (BI->isUnconditional()) {
  3672. if (BI->getSuccessor(0) == BB) {
  3673. new UnreachableInst(TI->getContext(), TI);
  3674. TI->eraseFromParent();
  3675. Changed = true;
  3676. }
  3677. } else {
  3678. Value* Cond = BI->getCondition();
  3679. if (BI->getSuccessor(0) == BB) {
  3680. Builder.CreateAssumption(Builder.CreateNot(Cond));
  3681. Builder.CreateBr(BI->getSuccessor(1));
  3682. EraseTerminatorAndDCECond(BI);
  3683. } else if (BI->getSuccessor(1) == BB) {
  3684. Builder.CreateAssumption(Cond);
  3685. Builder.CreateBr(BI->getSuccessor(0));
  3686. EraseTerminatorAndDCECond(BI);
  3687. Changed = true;
  3688. }
  3689. }
  3690. } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  3691. SwitchInstProfUpdateWrapper SU(*SI);
  3692. for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
  3693. if (i->getCaseSuccessor() != BB) {
  3694. ++i;
  3695. continue;
  3696. }
  3697. BB->removePredecessor(SU->getParent());
  3698. i = SU.removeCase(i);
  3699. e = SU->case_end();
  3700. Changed = true;
  3701. }
  3702. } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
  3703. if (II->getUnwindDest() == BB) {
  3704. removeUnwindEdge(TI->getParent());
  3705. Changed = true;
  3706. }
  3707. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
  3708. if (CSI->getUnwindDest() == BB) {
  3709. removeUnwindEdge(TI->getParent());
  3710. Changed = true;
  3711. continue;
  3712. }
  3713. for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
  3714. E = CSI->handler_end();
  3715. I != E; ++I) {
  3716. if (*I == BB) {
  3717. CSI->removeHandler(I);
  3718. --I;
  3719. --E;
  3720. Changed = true;
  3721. }
  3722. }
  3723. if (CSI->getNumHandlers() == 0) {
  3724. BasicBlock *CatchSwitchBB = CSI->getParent();
  3725. if (CSI->hasUnwindDest()) {
  3726. // Redirect preds to the unwind dest
  3727. CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
  3728. } else {
  3729. // Rewrite all preds to unwind to caller (or from invoke to call).
  3730. SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
  3731. for (BasicBlock *EHPred : EHPreds)
  3732. removeUnwindEdge(EHPred);
  3733. }
  3734. // The catchswitch is no longer reachable.
  3735. new UnreachableInst(CSI->getContext(), CSI);
  3736. CSI->eraseFromParent();
  3737. Changed = true;
  3738. }
  3739. } else if (isa<CleanupReturnInst>(TI)) {
  3740. new UnreachableInst(TI->getContext(), TI);
  3741. TI->eraseFromParent();
  3742. Changed = true;
  3743. }
  3744. }
  3745. // If this block is now dead, remove it.
  3746. if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
  3747. // We know there are no successors, so just nuke the block.
  3748. if (LoopHeaders)
  3749. LoopHeaders->erase(BB);
  3750. BB->eraseFromParent();
  3751. return true;
  3752. }
  3753. return Changed;
  3754. }
  3755. static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
  3756. assert(Cases.size() >= 1);
  3757. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  3758. for (size_t I = 1, E = Cases.size(); I != E; ++I) {
  3759. if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
  3760. return false;
  3761. }
  3762. return true;
  3763. }
  3764. /// Turn a switch with two reachable destinations into an integer range
  3765. /// comparison and branch.
  3766. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  3767. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3768. bool HasDefault =
  3769. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3770. // Partition the cases into two sets with different destinations.
  3771. BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
  3772. BasicBlock *DestB = nullptr;
  3773. SmallVector<ConstantInt *, 16> CasesA;
  3774. SmallVector<ConstantInt *, 16> CasesB;
  3775. for (auto Case : SI->cases()) {
  3776. BasicBlock *Dest = Case.getCaseSuccessor();
  3777. if (!DestA)
  3778. DestA = Dest;
  3779. if (Dest == DestA) {
  3780. CasesA.push_back(Case.getCaseValue());
  3781. continue;
  3782. }
  3783. if (!DestB)
  3784. DestB = Dest;
  3785. if (Dest == DestB) {
  3786. CasesB.push_back(Case.getCaseValue());
  3787. continue;
  3788. }
  3789. return false; // More than two destinations.
  3790. }
  3791. assert(DestA && DestB &&
  3792. "Single-destination switch should have been folded.");
  3793. assert(DestA != DestB);
  3794. assert(DestB != SI->getDefaultDest());
  3795. assert(!CasesB.empty() && "There must be non-default cases.");
  3796. assert(!CasesA.empty() || HasDefault);
  3797. // Figure out if one of the sets of cases form a contiguous range.
  3798. SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
  3799. BasicBlock *ContiguousDest = nullptr;
  3800. BasicBlock *OtherDest = nullptr;
  3801. if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
  3802. ContiguousCases = &CasesA;
  3803. ContiguousDest = DestA;
  3804. OtherDest = DestB;
  3805. } else if (CasesAreContiguous(CasesB)) {
  3806. ContiguousCases = &CasesB;
  3807. ContiguousDest = DestB;
  3808. OtherDest = DestA;
  3809. } else
  3810. return false;
  3811. // Start building the compare and branch.
  3812. Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
  3813. Constant *NumCases =
  3814. ConstantInt::get(Offset->getType(), ContiguousCases->size());
  3815. Value *Sub = SI->getCondition();
  3816. if (!Offset->isNullValue())
  3817. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
  3818. Value *Cmp;
  3819. // If NumCases overflowed, then all possible values jump to the successor.
  3820. if (NumCases->isNullValue() && !ContiguousCases->empty())
  3821. Cmp = ConstantInt::getTrue(SI->getContext());
  3822. else
  3823. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  3824. BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
  3825. // Update weight for the newly-created conditional branch.
  3826. if (HasBranchWeights(SI)) {
  3827. SmallVector<uint64_t, 8> Weights;
  3828. GetBranchWeights(SI, Weights);
  3829. if (Weights.size() == 1 + SI->getNumCases()) {
  3830. uint64_t TrueWeight = 0;
  3831. uint64_t FalseWeight = 0;
  3832. for (size_t I = 0, E = Weights.size(); I != E; ++I) {
  3833. if (SI->getSuccessor(I) == ContiguousDest)
  3834. TrueWeight += Weights[I];
  3835. else
  3836. FalseWeight += Weights[I];
  3837. }
  3838. while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
  3839. TrueWeight /= 2;
  3840. FalseWeight /= 2;
  3841. }
  3842. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3843. }
  3844. }
  3845. // Prune obsolete incoming values off the successors' PHI nodes.
  3846. for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3847. unsigned PreviousEdges = ContiguousCases->size();
  3848. if (ContiguousDest == SI->getDefaultDest())
  3849. ++PreviousEdges;
  3850. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3851. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3852. }
  3853. for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3854. unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
  3855. if (OtherDest == SI->getDefaultDest())
  3856. ++PreviousEdges;
  3857. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3858. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3859. }
  3860. // Drop the switch.
  3861. SI->eraseFromParent();
  3862. return true;
  3863. }
  3864. /// Compute masked bits for the condition of a switch
  3865. /// and use it to remove dead cases.
  3866. static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
  3867. const DataLayout &DL) {
  3868. Value *Cond = SI->getCondition();
  3869. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  3870. KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
  3871. // We can also eliminate cases by determining that their values are outside of
  3872. // the limited range of the condition based on how many significant (non-sign)
  3873. // bits are in the condition value.
  3874. unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
  3875. unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
  3876. // Gather dead cases.
  3877. SmallVector<ConstantInt *, 8> DeadCases;
  3878. for (auto &Case : SI->cases()) {
  3879. const APInt &CaseVal = Case.getCaseValue()->getValue();
  3880. if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
  3881. (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
  3882. DeadCases.push_back(Case.getCaseValue());
  3883. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
  3884. << " is dead.\n");
  3885. }
  3886. }
  3887. // If we can prove that the cases must cover all possible values, the
  3888. // default destination becomes dead and we can remove it. If we know some
  3889. // of the bits in the value, we can use that to more precisely compute the
  3890. // number of possible unique case values.
  3891. bool HasDefault =
  3892. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3893. const unsigned NumUnknownBits =
  3894. Bits - (Known.Zero | Known.One).countPopulation();
  3895. assert(NumUnknownBits <= Bits);
  3896. if (HasDefault && DeadCases.empty() &&
  3897. NumUnknownBits < 64 /* avoid overflow */ &&
  3898. SI->getNumCases() == (1ULL << NumUnknownBits)) {
  3899. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
  3900. BasicBlock *NewDefault =
  3901. SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
  3902. SI->setDefaultDest(&*NewDefault);
  3903. SplitBlock(&*NewDefault, &NewDefault->front());
  3904. auto *OldTI = NewDefault->getTerminator();
  3905. new UnreachableInst(SI->getContext(), OldTI);
  3906. EraseTerminatorAndDCECond(OldTI);
  3907. return true;
  3908. }
  3909. if (DeadCases.empty())
  3910. return false;
  3911. SwitchInstProfUpdateWrapper SIW(*SI);
  3912. for (ConstantInt *DeadCase : DeadCases) {
  3913. SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
  3914. assert(CaseI != SI->case_default() &&
  3915. "Case was not found. Probably mistake in DeadCases forming.");
  3916. // Prune unused values from PHI nodes.
  3917. CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
  3918. SIW.removeCase(CaseI);
  3919. }
  3920. return true;
  3921. }
  3922. /// If BB would be eligible for simplification by
  3923. /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  3924. /// by an unconditional branch), look at the phi node for BB in the successor
  3925. /// block and see if the incoming value is equal to CaseValue. If so, return
  3926. /// the phi node, and set PhiIndex to BB's index in the phi node.
  3927. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  3928. BasicBlock *BB, int *PhiIndex) {
  3929. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  3930. return nullptr; // BB must be empty to be a candidate for simplification.
  3931. if (!BB->getSinglePredecessor())
  3932. return nullptr; // BB must be dominated by the switch.
  3933. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  3934. if (!Branch || !Branch->isUnconditional())
  3935. return nullptr; // Terminator must be unconditional branch.
  3936. BasicBlock *Succ = Branch->getSuccessor(0);
  3937. for (PHINode &PHI : Succ->phis()) {
  3938. int Idx = PHI.getBasicBlockIndex(BB);
  3939. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  3940. Value *InValue = PHI.getIncomingValue(Idx);
  3941. if (InValue != CaseValue)
  3942. continue;
  3943. *PhiIndex = Idx;
  3944. return &PHI;
  3945. }
  3946. return nullptr;
  3947. }
  3948. /// Try to forward the condition of a switch instruction to a phi node
  3949. /// dominated by the switch, if that would mean that some of the destination
  3950. /// blocks of the switch can be folded away. Return true if a change is made.
  3951. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  3952. using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
  3953. ForwardingNodesMap ForwardingNodes;
  3954. BasicBlock *SwitchBlock = SI->getParent();
  3955. bool Changed = false;
  3956. for (auto &Case : SI->cases()) {
  3957. ConstantInt *CaseValue = Case.getCaseValue();
  3958. BasicBlock *CaseDest = Case.getCaseSuccessor();
  3959. // Replace phi operands in successor blocks that are using the constant case
  3960. // value rather than the switch condition variable:
  3961. // switchbb:
  3962. // switch i32 %x, label %default [
  3963. // i32 17, label %succ
  3964. // ...
  3965. // succ:
  3966. // %r = phi i32 ... [ 17, %switchbb ] ...
  3967. // -->
  3968. // %r = phi i32 ... [ %x, %switchbb ] ...
  3969. for (PHINode &Phi : CaseDest->phis()) {
  3970. // This only works if there is exactly 1 incoming edge from the switch to
  3971. // a phi. If there is >1, that means multiple cases of the switch map to 1
  3972. // value in the phi, and that phi value is not the switch condition. Thus,
  3973. // this transform would not make sense (the phi would be invalid because
  3974. // a phi can't have different incoming values from the same block).
  3975. int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
  3976. if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
  3977. count(Phi.blocks(), SwitchBlock) == 1) {
  3978. Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
  3979. Changed = true;
  3980. }
  3981. }
  3982. // Collect phi nodes that are indirectly using this switch's case constants.
  3983. int PhiIdx;
  3984. if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
  3985. ForwardingNodes[Phi].push_back(PhiIdx);
  3986. }
  3987. for (auto &ForwardingNode : ForwardingNodes) {
  3988. PHINode *Phi = ForwardingNode.first;
  3989. SmallVectorImpl<int> &Indexes = ForwardingNode.second;
  3990. if (Indexes.size() < 2)
  3991. continue;
  3992. for (int Index : Indexes)
  3993. Phi->setIncomingValue(Index, SI->getCondition());
  3994. Changed = true;
  3995. }
  3996. return Changed;
  3997. }
  3998. /// Return true if the backend will be able to handle
  3999. /// initializing an array of constants like C.
  4000. static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
  4001. if (C->isThreadDependent())
  4002. return false;
  4003. if (C->isDLLImportDependent())
  4004. return false;
  4005. if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
  4006. !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
  4007. !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
  4008. return false;
  4009. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  4010. if (!CE->isGEPWithNoNotionalOverIndexing())
  4011. return false;
  4012. if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
  4013. return false;
  4014. }
  4015. if (!TTI.shouldBuildLookupTablesForConstant(C))
  4016. return false;
  4017. return true;
  4018. }
  4019. /// If V is a Constant, return it. Otherwise, try to look up
  4020. /// its constant value in ConstantPool, returning 0 if it's not there.
  4021. static Constant *
  4022. LookupConstant(Value *V,
  4023. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4024. if (Constant *C = dyn_cast<Constant>(V))
  4025. return C;
  4026. return ConstantPool.lookup(V);
  4027. }
  4028. /// Try to fold instruction I into a constant. This works for
  4029. /// simple instructions such as binary operations where both operands are
  4030. /// constant or can be replaced by constants from the ConstantPool. Returns the
  4031. /// resulting constant on success, 0 otherwise.
  4032. static Constant *
  4033. ConstantFold(Instruction *I, const DataLayout &DL,
  4034. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4035. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  4036. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  4037. if (!A)
  4038. return nullptr;
  4039. if (A->isAllOnesValue())
  4040. return LookupConstant(Select->getTrueValue(), ConstantPool);
  4041. if (A->isNullValue())
  4042. return LookupConstant(Select->getFalseValue(), ConstantPool);
  4043. return nullptr;
  4044. }
  4045. SmallVector<Constant *, 4> COps;
  4046. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  4047. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  4048. COps.push_back(A);
  4049. else
  4050. return nullptr;
  4051. }
  4052. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  4053. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  4054. COps[1], DL);
  4055. }
  4056. return ConstantFoldInstOperands(I, COps, DL);
  4057. }
  4058. /// Try to determine the resulting constant values in phi nodes
  4059. /// at the common destination basic block, *CommonDest, for one of the case
  4060. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  4061. /// case), of a switch instruction SI.
  4062. static bool
  4063. GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
  4064. BasicBlock **CommonDest,
  4065. SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
  4066. const DataLayout &DL, const TargetTransformInfo &TTI) {
  4067. // The block from which we enter the common destination.
  4068. BasicBlock *Pred = SI->getParent();
  4069. // If CaseDest is empty except for some side-effect free instructions through
  4070. // which we can constant-propagate the CaseVal, continue to its successor.
  4071. SmallDenseMap<Value *, Constant *> ConstantPool;
  4072. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  4073. for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
  4074. if (I.isTerminator()) {
  4075. // If the terminator is a simple branch, continue to the next block.
  4076. if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
  4077. return false;
  4078. Pred = CaseDest;
  4079. CaseDest = I.getSuccessor(0);
  4080. } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
  4081. // Instruction is side-effect free and constant.
  4082. // If the instruction has uses outside this block or a phi node slot for
  4083. // the block, it is not safe to bypass the instruction since it would then
  4084. // no longer dominate all its uses.
  4085. for (auto &Use : I.uses()) {
  4086. User *User = Use.getUser();
  4087. if (Instruction *I = dyn_cast<Instruction>(User))
  4088. if (I->getParent() == CaseDest)
  4089. continue;
  4090. if (PHINode *Phi = dyn_cast<PHINode>(User))
  4091. if (Phi->getIncomingBlock(Use) == CaseDest)
  4092. continue;
  4093. return false;
  4094. }
  4095. ConstantPool.insert(std::make_pair(&I, C));
  4096. } else {
  4097. break;
  4098. }
  4099. }
  4100. // If we did not have a CommonDest before, use the current one.
  4101. if (!*CommonDest)
  4102. *CommonDest = CaseDest;
  4103. // If the destination isn't the common one, abort.
  4104. if (CaseDest != *CommonDest)
  4105. return false;
  4106. // Get the values for this case from phi nodes in the destination block.
  4107. for (PHINode &PHI : (*CommonDest)->phis()) {
  4108. int Idx = PHI.getBasicBlockIndex(Pred);
  4109. if (Idx == -1)
  4110. continue;
  4111. Constant *ConstVal =
  4112. LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
  4113. if (!ConstVal)
  4114. return false;
  4115. // Be conservative about which kinds of constants we support.
  4116. if (!ValidLookupTableConstant(ConstVal, TTI))
  4117. return false;
  4118. Res.push_back(std::make_pair(&PHI, ConstVal));
  4119. }
  4120. return Res.size() > 0;
  4121. }
  4122. // Helper function used to add CaseVal to the list of cases that generate
  4123. // Result. Returns the updated number of cases that generate this result.
  4124. static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
  4125. SwitchCaseResultVectorTy &UniqueResults,
  4126. Constant *Result) {
  4127. for (auto &I : UniqueResults) {
  4128. if (I.first == Result) {
  4129. I.second.push_back(CaseVal);
  4130. return I.second.size();
  4131. }
  4132. }
  4133. UniqueResults.push_back(
  4134. std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
  4135. return 1;
  4136. }
  4137. // Helper function that initializes a map containing
  4138. // results for the PHI node of the common destination block for a switch
  4139. // instruction. Returns false if multiple PHI nodes have been found or if
  4140. // there is not a common destination block for the switch.
  4141. static bool
  4142. InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
  4143. SwitchCaseResultVectorTy &UniqueResults,
  4144. Constant *&DefaultResult, const DataLayout &DL,
  4145. const TargetTransformInfo &TTI,
  4146. uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
  4147. for (auto &I : SI->cases()) {
  4148. ConstantInt *CaseVal = I.getCaseValue();
  4149. // Resulting value at phi nodes for this case value.
  4150. SwitchCaseResultsTy Results;
  4151. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  4152. DL, TTI))
  4153. return false;
  4154. // Only one value per case is permitted.
  4155. if (Results.size() > 1)
  4156. return false;
  4157. // Add the case->result mapping to UniqueResults.
  4158. const uintptr_t NumCasesForResult =
  4159. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  4160. // Early out if there are too many cases for this result.
  4161. if (NumCasesForResult > MaxCasesPerResult)
  4162. return false;
  4163. // Early out if there are too many unique results.
  4164. if (UniqueResults.size() > MaxUniqueResults)
  4165. return false;
  4166. // Check the PHI consistency.
  4167. if (!PHI)
  4168. PHI = Results[0].first;
  4169. else if (PHI != Results[0].first)
  4170. return false;
  4171. }
  4172. // Find the default result value.
  4173. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  4174. BasicBlock *DefaultDest = SI->getDefaultDest();
  4175. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  4176. DL, TTI);
  4177. // If the default value is not found abort unless the default destination
  4178. // is unreachable.
  4179. DefaultResult =
  4180. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  4181. if ((!DefaultResult &&
  4182. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  4183. return false;
  4184. return true;
  4185. }
  4186. // Helper function that checks if it is possible to transform a switch with only
  4187. // two cases (or two cases + default) that produces a result into a select.
  4188. // Example:
  4189. // switch (a) {
  4190. // case 10: %0 = icmp eq i32 %a, 10
  4191. // return 10; %1 = select i1 %0, i32 10, i32 4
  4192. // case 20: ----> %2 = icmp eq i32 %a, 20
  4193. // return 2; %3 = select i1 %2, i32 2, i32 %1
  4194. // default:
  4195. // return 4;
  4196. // }
  4197. static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  4198. Constant *DefaultResult, Value *Condition,
  4199. IRBuilder<> &Builder) {
  4200. assert(ResultVector.size() == 2 &&
  4201. "We should have exactly two unique results at this point");
  4202. // If we are selecting between only two cases transform into a simple
  4203. // select or a two-way select if default is possible.
  4204. if (ResultVector[0].second.size() == 1 &&
  4205. ResultVector[1].second.size() == 1) {
  4206. ConstantInt *const FirstCase = ResultVector[0].second[0];
  4207. ConstantInt *const SecondCase = ResultVector[1].second[0];
  4208. bool DefaultCanTrigger = DefaultResult;
  4209. Value *SelectValue = ResultVector[1].first;
  4210. if (DefaultCanTrigger) {
  4211. Value *const ValueCompare =
  4212. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  4213. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  4214. DefaultResult, "switch.select");
  4215. }
  4216. Value *const ValueCompare =
  4217. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  4218. return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
  4219. SelectValue, "switch.select");
  4220. }
  4221. return nullptr;
  4222. }
  4223. // Helper function to cleanup a switch instruction that has been converted into
  4224. // a select, fixing up PHI nodes and basic blocks.
  4225. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  4226. Value *SelectValue,
  4227. IRBuilder<> &Builder) {
  4228. BasicBlock *SelectBB = SI->getParent();
  4229. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  4230. PHI->removeIncomingValue(SelectBB);
  4231. PHI->addIncoming(SelectValue, SelectBB);
  4232. Builder.CreateBr(PHI->getParent());
  4233. // Remove the switch.
  4234. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4235. BasicBlock *Succ = SI->getSuccessor(i);
  4236. if (Succ == PHI->getParent())
  4237. continue;
  4238. Succ->removePredecessor(SelectBB);
  4239. }
  4240. SI->eraseFromParent();
  4241. }
  4242. /// If the switch is only used to initialize one or more
  4243. /// phi nodes in a common successor block with only two different
  4244. /// constant values, replace the switch with select.
  4245. static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  4246. const DataLayout &DL,
  4247. const TargetTransformInfo &TTI) {
  4248. Value *const Cond = SI->getCondition();
  4249. PHINode *PHI = nullptr;
  4250. BasicBlock *CommonDest = nullptr;
  4251. Constant *DefaultResult;
  4252. SwitchCaseResultVectorTy UniqueResults;
  4253. // Collect all the cases that will deliver the same value from the switch.
  4254. if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
  4255. DL, TTI, 2, 1))
  4256. return false;
  4257. // Selects choose between maximum two values.
  4258. if (UniqueResults.size() != 2)
  4259. return false;
  4260. assert(PHI != nullptr && "PHI for value select not found");
  4261. Builder.SetInsertPoint(SI);
  4262. Value *SelectValue =
  4263. ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
  4264. if (SelectValue) {
  4265. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  4266. return true;
  4267. }
  4268. // The switch couldn't be converted into a select.
  4269. return false;
  4270. }
  4271. namespace {
  4272. /// This class represents a lookup table that can be used to replace a switch.
  4273. class SwitchLookupTable {
  4274. public:
  4275. /// Create a lookup table to use as a switch replacement with the contents
  4276. /// of Values, using DefaultValue to fill any holes in the table.
  4277. SwitchLookupTable(
  4278. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4279. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4280. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
  4281. /// Build instructions with Builder to retrieve the value at
  4282. /// the position given by Index in the lookup table.
  4283. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  4284. /// Return true if a table with TableSize elements of
  4285. /// type ElementType would fit in a target-legal register.
  4286. static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
  4287. Type *ElementType);
  4288. private:
  4289. // Depending on the contents of the table, it can be represented in
  4290. // different ways.
  4291. enum {
  4292. // For tables where each element contains the same value, we just have to
  4293. // store that single value and return it for each lookup.
  4294. SingleValueKind,
  4295. // For tables where there is a linear relationship between table index
  4296. // and values. We calculate the result with a simple multiplication
  4297. // and addition instead of a table lookup.
  4298. LinearMapKind,
  4299. // For small tables with integer elements, we can pack them into a bitmap
  4300. // that fits into a target-legal register. Values are retrieved by
  4301. // shift and mask operations.
  4302. BitMapKind,
  4303. // The table is stored as an array of values. Values are retrieved by load
  4304. // instructions from the table.
  4305. ArrayKind
  4306. } Kind;
  4307. // For SingleValueKind, this is the single value.
  4308. Constant *SingleValue = nullptr;
  4309. // For BitMapKind, this is the bitmap.
  4310. ConstantInt *BitMap = nullptr;
  4311. IntegerType *BitMapElementTy = nullptr;
  4312. // For LinearMapKind, these are the constants used to derive the value.
  4313. ConstantInt *LinearOffset = nullptr;
  4314. ConstantInt *LinearMultiplier = nullptr;
  4315. // For ArrayKind, this is the array.
  4316. GlobalVariable *Array = nullptr;
  4317. };
  4318. } // end anonymous namespace
  4319. SwitchLookupTable::SwitchLookupTable(
  4320. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4321. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4322. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
  4323. assert(Values.size() && "Can't build lookup table without values!");
  4324. assert(TableSize >= Values.size() && "Can't fit values in table!");
  4325. // If all values in the table are equal, this is that value.
  4326. SingleValue = Values.begin()->second;
  4327. Type *ValueType = Values.begin()->second->getType();
  4328. // Build up the table contents.
  4329. SmallVector<Constant *, 64> TableContents(TableSize);
  4330. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  4331. ConstantInt *CaseVal = Values[I].first;
  4332. Constant *CaseRes = Values[I].second;
  4333. assert(CaseRes->getType() == ValueType);
  4334. uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
  4335. TableContents[Idx] = CaseRes;
  4336. if (CaseRes != SingleValue)
  4337. SingleValue = nullptr;
  4338. }
  4339. // Fill in any holes in the table with the default result.
  4340. if (Values.size() < TableSize) {
  4341. assert(DefaultValue &&
  4342. "Need a default value to fill the lookup table holes.");
  4343. assert(DefaultValue->getType() == ValueType);
  4344. for (uint64_t I = 0; I < TableSize; ++I) {
  4345. if (!TableContents[I])
  4346. TableContents[I] = DefaultValue;
  4347. }
  4348. if (DefaultValue != SingleValue)
  4349. SingleValue = nullptr;
  4350. }
  4351. // If each element in the table contains the same value, we only need to store
  4352. // that single value.
  4353. if (SingleValue) {
  4354. Kind = SingleValueKind;
  4355. return;
  4356. }
  4357. // Check if we can derive the value with a linear transformation from the
  4358. // table index.
  4359. if (isa<IntegerType>(ValueType)) {
  4360. bool LinearMappingPossible = true;
  4361. APInt PrevVal;
  4362. APInt DistToPrev;
  4363. assert(TableSize >= 2 && "Should be a SingleValue table.");
  4364. // Check if there is the same distance between two consecutive values.
  4365. for (uint64_t I = 0; I < TableSize; ++I) {
  4366. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  4367. if (!ConstVal) {
  4368. // This is an undef. We could deal with it, but undefs in lookup tables
  4369. // are very seldom. It's probably not worth the additional complexity.
  4370. LinearMappingPossible = false;
  4371. break;
  4372. }
  4373. const APInt &Val = ConstVal->getValue();
  4374. if (I != 0) {
  4375. APInt Dist = Val - PrevVal;
  4376. if (I == 1) {
  4377. DistToPrev = Dist;
  4378. } else if (Dist != DistToPrev) {
  4379. LinearMappingPossible = false;
  4380. break;
  4381. }
  4382. }
  4383. PrevVal = Val;
  4384. }
  4385. if (LinearMappingPossible) {
  4386. LinearOffset = cast<ConstantInt>(TableContents[0]);
  4387. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  4388. Kind = LinearMapKind;
  4389. ++NumLinearMaps;
  4390. return;
  4391. }
  4392. }
  4393. // If the type is integer and the table fits in a register, build a bitmap.
  4394. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  4395. IntegerType *IT = cast<IntegerType>(ValueType);
  4396. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  4397. for (uint64_t I = TableSize; I > 0; --I) {
  4398. TableInt <<= IT->getBitWidth();
  4399. // Insert values into the bitmap. Undef values are set to zero.
  4400. if (!isa<UndefValue>(TableContents[I - 1])) {
  4401. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  4402. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  4403. }
  4404. }
  4405. BitMap = ConstantInt::get(M.getContext(), TableInt);
  4406. BitMapElementTy = IT;
  4407. Kind = BitMapKind;
  4408. ++NumBitMaps;
  4409. return;
  4410. }
  4411. // Store the table in an array.
  4412. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  4413. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  4414. Array = new GlobalVariable(M, ArrayTy, /*isConstant=*/true,
  4415. GlobalVariable::PrivateLinkage, Initializer,
  4416. "switch.table." + FuncName);
  4417. Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  4418. // Set the alignment to that of an array items. We will be only loading one
  4419. // value out of it.
  4420. Array->setAlignment(DL.getPrefTypeAlignment(ValueType));
  4421. Kind = ArrayKind;
  4422. }
  4423. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  4424. switch (Kind) {
  4425. case SingleValueKind:
  4426. return SingleValue;
  4427. case LinearMapKind: {
  4428. // Derive the result value from the input value.
  4429. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  4430. false, "switch.idx.cast");
  4431. if (!LinearMultiplier->isOne())
  4432. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  4433. if (!LinearOffset->isZero())
  4434. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  4435. return Result;
  4436. }
  4437. case BitMapKind: {
  4438. // Type of the bitmap (e.g. i59).
  4439. IntegerType *MapTy = BitMap->getType();
  4440. // Cast Index to the same type as the bitmap.
  4441. // Note: The Index is <= the number of elements in the table, so
  4442. // truncating it to the width of the bitmask is safe.
  4443. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  4444. // Multiply the shift amount by the element width.
  4445. ShiftAmt = Builder.CreateMul(
  4446. ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  4447. "switch.shiftamt");
  4448. // Shift down.
  4449. Value *DownShifted =
  4450. Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
  4451. // Mask off.
  4452. return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
  4453. }
  4454. case ArrayKind: {
  4455. // Make sure the table index will not overflow when treated as signed.
  4456. IntegerType *IT = cast<IntegerType>(Index->getType());
  4457. uint64_t TableSize =
  4458. Array->getInitializer()->getType()->getArrayNumElements();
  4459. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  4460. Index = Builder.CreateZExt(
  4461. Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
  4462. "switch.tableidx.zext");
  4463. Value *GEPIndices[] = {Builder.getInt32(0), Index};
  4464. Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
  4465. GEPIndices, "switch.gep");
  4466. return Builder.CreateLoad(
  4467. cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
  4468. "switch.load");
  4469. }
  4470. }
  4471. llvm_unreachable("Unknown lookup table kind!");
  4472. }
  4473. bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
  4474. uint64_t TableSize,
  4475. Type *ElementType) {
  4476. auto *IT = dyn_cast<IntegerType>(ElementType);
  4477. if (!IT)
  4478. return false;
  4479. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  4480. // are <= 15, we could try to narrow the type.
  4481. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  4482. if (TableSize >= UINT_MAX / IT->getBitWidth())
  4483. return false;
  4484. return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
  4485. }
  4486. /// Determine whether a lookup table should be built for this switch, based on
  4487. /// the number of cases, size of the table, and the types of the results.
  4488. static bool
  4489. ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
  4490. const TargetTransformInfo &TTI, const DataLayout &DL,
  4491. const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
  4492. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  4493. return false; // TableSize overflowed, or mul below might overflow.
  4494. bool AllTablesFitInRegister = true;
  4495. bool HasIllegalType = false;
  4496. for (const auto &I : ResultTypes) {
  4497. Type *Ty = I.second;
  4498. // Saturate this flag to true.
  4499. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  4500. // Saturate this flag to false.
  4501. AllTablesFitInRegister =
  4502. AllTablesFitInRegister &&
  4503. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  4504. // If both flags saturate, we're done. NOTE: This *only* works with
  4505. // saturating flags, and all flags have to saturate first due to the
  4506. // non-deterministic behavior of iterating over a dense map.
  4507. if (HasIllegalType && !AllTablesFitInRegister)
  4508. break;
  4509. }
  4510. // If each table would fit in a register, we should build it anyway.
  4511. if (AllTablesFitInRegister)
  4512. return true;
  4513. // Don't build a table that doesn't fit in-register if it has illegal types.
  4514. if (HasIllegalType)
  4515. return false;
  4516. // The table density should be at least 40%. This is the same criterion as for
  4517. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  4518. // FIXME: Find the best cut-off.
  4519. return SI->getNumCases() * 10 >= TableSize * 4;
  4520. }
  4521. /// Try to reuse the switch table index compare. Following pattern:
  4522. /// \code
  4523. /// if (idx < tablesize)
  4524. /// r = table[idx]; // table does not contain default_value
  4525. /// else
  4526. /// r = default_value;
  4527. /// if (r != default_value)
  4528. /// ...
  4529. /// \endcode
  4530. /// Is optimized to:
  4531. /// \code
  4532. /// cond = idx < tablesize;
  4533. /// if (cond)
  4534. /// r = table[idx];
  4535. /// else
  4536. /// r = default_value;
  4537. /// if (cond)
  4538. /// ...
  4539. /// \endcode
  4540. /// Jump threading will then eliminate the second if(cond).
  4541. static void reuseTableCompare(
  4542. User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
  4543. Constant *DefaultValue,
  4544. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
  4545. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  4546. if (!CmpInst)
  4547. return;
  4548. // We require that the compare is in the same block as the phi so that jump
  4549. // threading can do its work afterwards.
  4550. if (CmpInst->getParent() != PhiBlock)
  4551. return;
  4552. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  4553. if (!CmpOp1)
  4554. return;
  4555. Value *RangeCmp = RangeCheckBranch->getCondition();
  4556. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  4557. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  4558. // Check if the compare with the default value is constant true or false.
  4559. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4560. DefaultValue, CmpOp1, true);
  4561. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  4562. return;
  4563. // Check if the compare with the case values is distinct from the default
  4564. // compare result.
  4565. for (auto ValuePair : Values) {
  4566. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4567. ValuePair.second, CmpOp1, true);
  4568. if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
  4569. return;
  4570. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  4571. "Expect true or false as compare result.");
  4572. }
  4573. // Check if the branch instruction dominates the phi node. It's a simple
  4574. // dominance check, but sufficient for our needs.
  4575. // Although this check is invariant in the calling loops, it's better to do it
  4576. // at this late stage. Practically we do it at most once for a switch.
  4577. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  4578. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  4579. BasicBlock *Pred = *PI;
  4580. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  4581. return;
  4582. }
  4583. if (DefaultConst == FalseConst) {
  4584. // The compare yields the same result. We can replace it.
  4585. CmpInst->replaceAllUsesWith(RangeCmp);
  4586. ++NumTableCmpReuses;
  4587. } else {
  4588. // The compare yields the same result, just inverted. We can replace it.
  4589. Value *InvertedTableCmp = BinaryOperator::CreateXor(
  4590. RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  4591. RangeCheckBranch);
  4592. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  4593. ++NumTableCmpReuses;
  4594. }
  4595. }
  4596. /// If the switch is only used to initialize one or more phi nodes in a common
  4597. /// successor block with different constant values, replace the switch with
  4598. /// lookup tables.
  4599. static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
  4600. const DataLayout &DL,
  4601. const TargetTransformInfo &TTI) {
  4602. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  4603. Function *Fn = SI->getParent()->getParent();
  4604. // Only build lookup table when we have a target that supports it or the
  4605. // attribute is not set.
  4606. if (!TTI.shouldBuildLookupTables() ||
  4607. (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
  4608. return false;
  4609. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  4610. // split off a dense part and build a lookup table for that.
  4611. // FIXME: This creates arrays of GEPs to constant strings, which means each
  4612. // GEP needs a runtime relocation in PIC code. We should just build one big
  4613. // string and lookup indices into that.
  4614. // Ignore switches with less than three cases. Lookup tables will not make
  4615. // them faster, so we don't analyze them.
  4616. if (SI->getNumCases() < 3)
  4617. return false;
  4618. // Figure out the corresponding result for each case value and phi node in the
  4619. // common destination, as well as the min and max case values.
  4620. assert(!empty(SI->cases()));
  4621. SwitchInst::CaseIt CI = SI->case_begin();
  4622. ConstantInt *MinCaseVal = CI->getCaseValue();
  4623. ConstantInt *MaxCaseVal = CI->getCaseValue();
  4624. BasicBlock *CommonDest = nullptr;
  4625. using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
  4626. SmallDenseMap<PHINode *, ResultListTy> ResultLists;
  4627. SmallDenseMap<PHINode *, Constant *> DefaultResults;
  4628. SmallDenseMap<PHINode *, Type *> ResultTypes;
  4629. SmallVector<PHINode *, 4> PHIs;
  4630. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  4631. ConstantInt *CaseVal = CI->getCaseValue();
  4632. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  4633. MinCaseVal = CaseVal;
  4634. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  4635. MaxCaseVal = CaseVal;
  4636. // Resulting value at phi nodes for this case value.
  4637. using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  4638. ResultsTy Results;
  4639. if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
  4640. Results, DL, TTI))
  4641. return false;
  4642. // Append the result from this case to the list for each phi.
  4643. for (const auto &I : Results) {
  4644. PHINode *PHI = I.first;
  4645. Constant *Value = I.second;
  4646. if (!ResultLists.count(PHI))
  4647. PHIs.push_back(PHI);
  4648. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  4649. }
  4650. }
  4651. // Keep track of the result types.
  4652. for (PHINode *PHI : PHIs) {
  4653. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  4654. }
  4655. uint64_t NumResults = ResultLists[PHIs[0]].size();
  4656. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  4657. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  4658. bool TableHasHoles = (NumResults < TableSize);
  4659. // If the table has holes, we need a constant result for the default case
  4660. // or a bitmask that fits in a register.
  4661. SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
  4662. bool HasDefaultResults =
  4663. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
  4664. DefaultResultsList, DL, TTI);
  4665. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  4666. if (NeedMask) {
  4667. // As an extra penalty for the validity test we require more cases.
  4668. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  4669. return false;
  4670. if (!DL.fitsInLegalInteger(TableSize))
  4671. return false;
  4672. }
  4673. for (const auto &I : DefaultResultsList) {
  4674. PHINode *PHI = I.first;
  4675. Constant *Result = I.second;
  4676. DefaultResults[PHI] = Result;
  4677. }
  4678. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  4679. return false;
  4680. // Create the BB that does the lookups.
  4681. Module &Mod = *CommonDest->getParent()->getParent();
  4682. BasicBlock *LookupBB = BasicBlock::Create(
  4683. Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
  4684. // Compute the table index value.
  4685. Builder.SetInsertPoint(SI);
  4686. Value *TableIndex;
  4687. if (MinCaseVal->isNullValue())
  4688. TableIndex = SI->getCondition();
  4689. else
  4690. TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  4691. "switch.tableidx");
  4692. // Compute the maximum table size representable by the integer type we are
  4693. // switching upon.
  4694. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  4695. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  4696. assert(MaxTableSize >= TableSize &&
  4697. "It is impossible for a switch to have more entries than the max "
  4698. "representable value of its input integer type's size.");
  4699. // If the default destination is unreachable, or if the lookup table covers
  4700. // all values of the conditional variable, branch directly to the lookup table
  4701. // BB. Otherwise, check that the condition is within the case range.
  4702. const bool DefaultIsReachable =
  4703. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  4704. const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
  4705. BranchInst *RangeCheckBranch = nullptr;
  4706. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4707. Builder.CreateBr(LookupBB);
  4708. // Note: We call removeProdecessor later since we need to be able to get the
  4709. // PHI value for the default case in case we're using a bit mask.
  4710. } else {
  4711. Value *Cmp = Builder.CreateICmpULT(
  4712. TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
  4713. RangeCheckBranch =
  4714. Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  4715. }
  4716. // Populate the BB that does the lookups.
  4717. Builder.SetInsertPoint(LookupBB);
  4718. if (NeedMask) {
  4719. // Before doing the lookup, we do the hole check. The LookupBB is therefore
  4720. // re-purposed to do the hole check, and we create a new LookupBB.
  4721. BasicBlock *MaskBB = LookupBB;
  4722. MaskBB->setName("switch.hole_check");
  4723. LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
  4724. CommonDest->getParent(), CommonDest);
  4725. // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
  4726. // unnecessary illegal types.
  4727. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  4728. APInt MaskInt(TableSizePowOf2, 0);
  4729. APInt One(TableSizePowOf2, 1);
  4730. // Build bitmask; fill in a 1 bit for every case.
  4731. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  4732. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  4733. uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
  4734. .getLimitedValue();
  4735. MaskInt |= One << Idx;
  4736. }
  4737. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  4738. // Get the TableIndex'th bit of the bitmask.
  4739. // If this bit is 0 (meaning hole) jump to the default destination,
  4740. // else continue with table lookup.
  4741. IntegerType *MapTy = TableMask->getType();
  4742. Value *MaskIndex =
  4743. Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
  4744. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
  4745. Value *LoBit = Builder.CreateTrunc(
  4746. Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
  4747. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  4748. Builder.SetInsertPoint(LookupBB);
  4749. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  4750. }
  4751. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4752. // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
  4753. // do not delete PHINodes here.
  4754. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  4755. /*KeepOneInputPHIs=*/true);
  4756. }
  4757. bool ReturnedEarly = false;
  4758. for (PHINode *PHI : PHIs) {
  4759. const ResultListTy &ResultList = ResultLists[PHI];
  4760. // If using a bitmask, use any value to fill the lookup table holes.
  4761. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  4762. StringRef FuncName = Fn->getName();
  4763. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
  4764. FuncName);
  4765. Value *Result = Table.BuildLookup(TableIndex, Builder);
  4766. // If the result is used to return immediately from the function, we want to
  4767. // do that right here.
  4768. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  4769. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  4770. Builder.CreateRet(Result);
  4771. ReturnedEarly = true;
  4772. break;
  4773. }
  4774. // Do a small peephole optimization: re-use the switch table compare if
  4775. // possible.
  4776. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  4777. BasicBlock *PhiBlock = PHI->getParent();
  4778. // Search for compare instructions which use the phi.
  4779. for (auto *User : PHI->users()) {
  4780. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  4781. }
  4782. }
  4783. PHI->addIncoming(Result, LookupBB);
  4784. }
  4785. if (!ReturnedEarly)
  4786. Builder.CreateBr(CommonDest);
  4787. // Remove the switch.
  4788. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4789. BasicBlock *Succ = SI->getSuccessor(i);
  4790. if (Succ == SI->getDefaultDest())
  4791. continue;
  4792. Succ->removePredecessor(SI->getParent());
  4793. }
  4794. SI->eraseFromParent();
  4795. ++NumLookupTables;
  4796. if (NeedMask)
  4797. ++NumLookupTablesHoles;
  4798. return true;
  4799. }
  4800. static bool isSwitchDense(ArrayRef<int64_t> Values) {
  4801. // See also SelectionDAGBuilder::isDense(), which this function was based on.
  4802. uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
  4803. uint64_t Range = Diff + 1;
  4804. uint64_t NumCases = Values.size();
  4805. // 40% is the default density for building a jump table in optsize/minsize mode.
  4806. uint64_t MinDensity = 40;
  4807. return NumCases * 100 >= Range * MinDensity;
  4808. }
  4809. /// Try to transform a switch that has "holes" in it to a contiguous sequence
  4810. /// of cases.
  4811. ///
  4812. /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
  4813. /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
  4814. ///
  4815. /// This converts a sparse switch into a dense switch which allows better
  4816. /// lowering and could also allow transforming into a lookup table.
  4817. static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
  4818. const DataLayout &DL,
  4819. const TargetTransformInfo &TTI) {
  4820. auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
  4821. if (CondTy->getIntegerBitWidth() > 64 ||
  4822. !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
  4823. return false;
  4824. // Only bother with this optimization if there are more than 3 switch cases;
  4825. // SDAG will only bother creating jump tables for 4 or more cases.
  4826. if (SI->getNumCases() < 4)
  4827. return false;
  4828. // This transform is agnostic to the signedness of the input or case values. We
  4829. // can treat the case values as signed or unsigned. We can optimize more common
  4830. // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
  4831. // as signed.
  4832. SmallVector<int64_t,4> Values;
  4833. for (auto &C : SI->cases())
  4834. Values.push_back(C.getCaseValue()->getValue().getSExtValue());
  4835. llvm::sort(Values);
  4836. // If the switch is already dense, there's nothing useful to do here.
  4837. if (isSwitchDense(Values))
  4838. return false;
  4839. // First, transform the values such that they start at zero and ascend.
  4840. int64_t Base = Values[0];
  4841. for (auto &V : Values)
  4842. V -= (uint64_t)(Base);
  4843. // Now we have signed numbers that have been shifted so that, given enough
  4844. // precision, there are no negative values. Since the rest of the transform
  4845. // is bitwise only, we switch now to an unsigned representation.
  4846. // This transform can be done speculatively because it is so cheap - it
  4847. // results in a single rotate operation being inserted.
  4848. // FIXME: It's possible that optimizing a switch on powers of two might also
  4849. // be beneficial - flag values are often powers of two and we could use a CLZ
  4850. // as the key function.
  4851. // countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
  4852. // one element and LLVM disallows duplicate cases, Shift is guaranteed to be
  4853. // less than 64.
  4854. unsigned Shift = 64;
  4855. for (auto &V : Values)
  4856. Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
  4857. assert(Shift < 64);
  4858. if (Shift > 0)
  4859. for (auto &V : Values)
  4860. V = (int64_t)((uint64_t)V >> Shift);
  4861. if (!isSwitchDense(Values))
  4862. // Transform didn't create a dense switch.
  4863. return false;
  4864. // The obvious transform is to shift the switch condition right and emit a
  4865. // check that the condition actually cleanly divided by GCD, i.e.
  4866. // C & (1 << Shift - 1) == 0
  4867. // inserting a new CFG edge to handle the case where it didn't divide cleanly.
  4868. //
  4869. // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
  4870. // shift and puts the shifted-off bits in the uppermost bits. If any of these
  4871. // are nonzero then the switch condition will be very large and will hit the
  4872. // default case.
  4873. auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
  4874. Builder.SetInsertPoint(SI);
  4875. auto *ShiftC = ConstantInt::get(Ty, Shift);
  4876. auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
  4877. auto *LShr = Builder.CreateLShr(Sub, ShiftC);
  4878. auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
  4879. auto *Rot = Builder.CreateOr(LShr, Shl);
  4880. SI->replaceUsesOfWith(SI->getCondition(), Rot);
  4881. for (auto Case : SI->cases()) {
  4882. auto *Orig = Case.getCaseValue();
  4883. auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
  4884. Case.setValue(
  4885. cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
  4886. }
  4887. return true;
  4888. }
  4889. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  4890. BasicBlock *BB = SI->getParent();
  4891. if (isValueEqualityComparison(SI)) {
  4892. // If we only have one predecessor, and if it is a branch on this value,
  4893. // see if that predecessor totally determines the outcome of this switch.
  4894. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  4895. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  4896. return requestResimplify();
  4897. Value *Cond = SI->getCondition();
  4898. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  4899. if (SimplifySwitchOnSelect(SI, Select))
  4900. return requestResimplify();
  4901. // If the block only contains the switch, see if we can fold the block
  4902. // away into any preds.
  4903. if (SI == &*BB->instructionsWithoutDebug().begin())
  4904. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  4905. return requestResimplify();
  4906. }
  4907. // Try to transform the switch into an icmp and a branch.
  4908. if (TurnSwitchRangeIntoICmp(SI, Builder))
  4909. return requestResimplify();
  4910. // Remove unreachable cases.
  4911. if (eliminateDeadSwitchCases(SI, Options.AC, DL))
  4912. return requestResimplify();
  4913. if (switchToSelect(SI, Builder, DL, TTI))
  4914. return requestResimplify();
  4915. if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
  4916. return requestResimplify();
  4917. // The conversion from switch to lookup tables results in difficult-to-analyze
  4918. // code and makes pruning branches much harder. This is a problem if the
  4919. // switch expression itself can still be restricted as a result of inlining or
  4920. // CVP. Therefore, only apply this transformation during late stages of the
  4921. // optimisation pipeline.
  4922. if (Options.ConvertSwitchToLookupTable &&
  4923. SwitchToLookupTable(SI, Builder, DL, TTI))
  4924. return requestResimplify();
  4925. if (ReduceSwitchRange(SI, Builder, DL, TTI))
  4926. return requestResimplify();
  4927. return false;
  4928. }
  4929. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  4930. BasicBlock *BB = IBI->getParent();
  4931. bool Changed = false;
  4932. // Eliminate redundant destinations.
  4933. SmallPtrSet<Value *, 8> Succs;
  4934. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  4935. BasicBlock *Dest = IBI->getDestination(i);
  4936. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  4937. Dest->removePredecessor(BB);
  4938. IBI->removeDestination(i);
  4939. --i;
  4940. --e;
  4941. Changed = true;
  4942. }
  4943. }
  4944. if (IBI->getNumDestinations() == 0) {
  4945. // If the indirectbr has no successors, change it to unreachable.
  4946. new UnreachableInst(IBI->getContext(), IBI);
  4947. EraseTerminatorAndDCECond(IBI);
  4948. return true;
  4949. }
  4950. if (IBI->getNumDestinations() == 1) {
  4951. // If the indirectbr has one successor, change it to a direct branch.
  4952. BranchInst::Create(IBI->getDestination(0), IBI);
  4953. EraseTerminatorAndDCECond(IBI);
  4954. return true;
  4955. }
  4956. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  4957. if (SimplifyIndirectBrOnSelect(IBI, SI))
  4958. return requestResimplify();
  4959. }
  4960. return Changed;
  4961. }
  4962. /// Given an block with only a single landing pad and a unconditional branch
  4963. /// try to find another basic block which this one can be merged with. This
  4964. /// handles cases where we have multiple invokes with unique landing pads, but
  4965. /// a shared handler.
  4966. ///
  4967. /// We specifically choose to not worry about merging non-empty blocks
  4968. /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
  4969. /// practice, the optimizer produces empty landing pad blocks quite frequently
  4970. /// when dealing with exception dense code. (see: instcombine, gvn, if-else
  4971. /// sinking in this file)
  4972. ///
  4973. /// This is primarily a code size optimization. We need to avoid performing
  4974. /// any transform which might inhibit optimization (such as our ability to
  4975. /// specialize a particular handler via tail commoning). We do this by not
  4976. /// merging any blocks which require us to introduce a phi. Since the same
  4977. /// values are flowing through both blocks, we don't lose any ability to
  4978. /// specialize. If anything, we make such specialization more likely.
  4979. ///
  4980. /// TODO - This transformation could remove entries from a phi in the target
  4981. /// block when the inputs in the phi are the same for the two blocks being
  4982. /// merged. In some cases, this could result in removal of the PHI entirely.
  4983. static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
  4984. BasicBlock *BB) {
  4985. auto Succ = BB->getUniqueSuccessor();
  4986. assert(Succ);
  4987. // If there's a phi in the successor block, we'd likely have to introduce
  4988. // a phi into the merged landing pad block.
  4989. if (isa<PHINode>(*Succ->begin()))
  4990. return false;
  4991. for (BasicBlock *OtherPred : predecessors(Succ)) {
  4992. if (BB == OtherPred)
  4993. continue;
  4994. BasicBlock::iterator I = OtherPred->begin();
  4995. LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
  4996. if (!LPad2 || !LPad2->isIdenticalTo(LPad))
  4997. continue;
  4998. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  4999. ;
  5000. BranchInst *BI2 = dyn_cast<BranchInst>(I);
  5001. if (!BI2 || !BI2->isIdenticalTo(BI))
  5002. continue;
  5003. // We've found an identical block. Update our predecessors to take that
  5004. // path instead and make ourselves dead.
  5005. SmallPtrSet<BasicBlock *, 16> Preds;
  5006. Preds.insert(pred_begin(BB), pred_end(BB));
  5007. for (BasicBlock *Pred : Preds) {
  5008. InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
  5009. assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
  5010. "unexpected successor");
  5011. II->setUnwindDest(OtherPred);
  5012. }
  5013. // The debug info in OtherPred doesn't cover the merged control flow that
  5014. // used to go through BB. We need to delete it or update it.
  5015. for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
  5016. Instruction &Inst = *I;
  5017. I++;
  5018. if (isa<DbgInfoIntrinsic>(Inst))
  5019. Inst.eraseFromParent();
  5020. }
  5021. SmallPtrSet<BasicBlock *, 16> Succs;
  5022. Succs.insert(succ_begin(BB), succ_end(BB));
  5023. for (BasicBlock *Succ : Succs) {
  5024. Succ->removePredecessor(BB);
  5025. }
  5026. IRBuilder<> Builder(BI);
  5027. Builder.CreateUnreachable();
  5028. BI->eraseFromParent();
  5029. return true;
  5030. }
  5031. return false;
  5032. }
  5033. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
  5034. IRBuilder<> &Builder) {
  5035. BasicBlock *BB = BI->getParent();
  5036. BasicBlock *Succ = BI->getSuccessor(0);
  5037. // If the Terminator is the only non-phi instruction, simplify the block.
  5038. // If LoopHeader is provided, check if the block or its successor is a loop
  5039. // header. (This is for early invocations before loop simplify and
  5040. // vectorization to keep canonical loop forms for nested loops. These blocks
  5041. // can be eliminated when the pass is invoked later in the back-end.)
  5042. // Note that if BB has only one predecessor then we do not introduce new
  5043. // backedge, so we can eliminate BB.
  5044. bool NeedCanonicalLoop =
  5045. Options.NeedCanonicalLoop &&
  5046. (LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
  5047. (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
  5048. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
  5049. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  5050. !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
  5051. return true;
  5052. // If the only instruction in the block is a seteq/setne comparison against a
  5053. // constant, try to simplify the block.
  5054. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  5055. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  5056. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5057. ;
  5058. if (I->isTerminator() &&
  5059. tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
  5060. return true;
  5061. }
  5062. // See if we can merge an empty landing pad block with another which is
  5063. // equivalent.
  5064. if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
  5065. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5066. ;
  5067. if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
  5068. return true;
  5069. }
  5070. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5071. // branches to us and our successor, fold the comparison into the
  5072. // predecessor and use logical operations to update the incoming value
  5073. // for PHI nodes in common successor.
  5074. if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
  5075. return requestResimplify();
  5076. return false;
  5077. }
  5078. static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
  5079. BasicBlock *PredPred = nullptr;
  5080. for (auto *P : predecessors(BB)) {
  5081. BasicBlock *PPred = P->getSinglePredecessor();
  5082. if (!PPred || (PredPred && PredPred != PPred))
  5083. return nullptr;
  5084. PredPred = PPred;
  5085. }
  5086. return PredPred;
  5087. }
  5088. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  5089. BasicBlock *BB = BI->getParent();
  5090. const Function *Fn = BB->getParent();
  5091. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  5092. return false;
  5093. // Conditional branch
  5094. if (isValueEqualityComparison(BI)) {
  5095. // If we only have one predecessor, and if it is a branch on this value,
  5096. // see if that predecessor totally determines the outcome of this
  5097. // switch.
  5098. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  5099. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  5100. return requestResimplify();
  5101. // This block must be empty, except for the setcond inst, if it exists.
  5102. // Ignore dbg intrinsics.
  5103. auto I = BB->instructionsWithoutDebug().begin();
  5104. if (&*I == BI) {
  5105. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  5106. return requestResimplify();
  5107. } else if (&*I == cast<Instruction>(BI->getCondition())) {
  5108. ++I;
  5109. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  5110. return requestResimplify();
  5111. }
  5112. }
  5113. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  5114. if (SimplifyBranchOnICmpChain(BI, Builder, DL))
  5115. return true;
  5116. // If this basic block has dominating predecessor blocks and the dominating
  5117. // blocks' conditions imply BI's condition, we know the direction of BI.
  5118. Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
  5119. if (Imp) {
  5120. // Turn this into a branch on constant.
  5121. auto *OldCond = BI->getCondition();
  5122. ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
  5123. : ConstantInt::getFalse(BB->getContext());
  5124. BI->setCondition(TorF);
  5125. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  5126. return requestResimplify();
  5127. }
  5128. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5129. // branches to us and one of our successors, fold the comparison into the
  5130. // predecessor and use logical operations to pick the right destination.
  5131. if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
  5132. return requestResimplify();
  5133. // We have a conditional branch to two blocks that are only reachable
  5134. // from BI. We know that the condbr dominates the two blocks, so see if
  5135. // there is any identical code in the "then" and "else" blocks. If so, we
  5136. // can hoist it up to the branching block.
  5137. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  5138. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5139. if (HoistThenElseCodeToIf(BI, TTI))
  5140. return requestResimplify();
  5141. } else {
  5142. // If Successor #1 has multiple preds, we may be able to conditionally
  5143. // execute Successor #0 if it branches to Successor #1.
  5144. Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
  5145. if (Succ0TI->getNumSuccessors() == 1 &&
  5146. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  5147. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
  5148. return requestResimplify();
  5149. }
  5150. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5151. // If Successor #0 has multiple preds, we may be able to conditionally
  5152. // execute Successor #1 if it branches to Successor #0.
  5153. Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
  5154. if (Succ1TI->getNumSuccessors() == 1 &&
  5155. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  5156. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
  5157. return requestResimplify();
  5158. }
  5159. // If this is a branch on a phi node in the current block, thread control
  5160. // through this block if any PHI node entries are constants.
  5161. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  5162. if (PN->getParent() == BI->getParent())
  5163. if (FoldCondBranchOnPHI(BI, DL, Options.AC))
  5164. return requestResimplify();
  5165. // Scan predecessor blocks for conditional branches.
  5166. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  5167. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  5168. if (PBI != BI && PBI->isConditional())
  5169. if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
  5170. return requestResimplify();
  5171. // Look for diamond patterns.
  5172. if (MergeCondStores)
  5173. if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
  5174. if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
  5175. if (PBI != BI && PBI->isConditional())
  5176. if (mergeConditionalStores(PBI, BI, DL))
  5177. return requestResimplify();
  5178. return false;
  5179. }
  5180. /// Check if passing a value to an instruction will cause undefined behavior.
  5181. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  5182. Constant *C = dyn_cast<Constant>(V);
  5183. if (!C)
  5184. return false;
  5185. if (I->use_empty())
  5186. return false;
  5187. if (C->isNullValue() || isa<UndefValue>(C)) {
  5188. // Only look at the first use, avoid hurting compile time with long uselists
  5189. User *Use = *I->user_begin();
  5190. // Now make sure that there are no instructions in between that can alter
  5191. // control flow (eg. calls)
  5192. for (BasicBlock::iterator
  5193. i = ++BasicBlock::iterator(I),
  5194. UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
  5195. i != UI; ++i)
  5196. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  5197. return false;
  5198. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  5199. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  5200. if (GEP->getPointerOperand() == I)
  5201. return passingValueIsAlwaysUndefined(V, GEP);
  5202. // Look through bitcasts.
  5203. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  5204. return passingValueIsAlwaysUndefined(V, BC);
  5205. // Load from null is undefined.
  5206. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  5207. if (!LI->isVolatile())
  5208. return !NullPointerIsDefined(LI->getFunction(),
  5209. LI->getPointerAddressSpace());
  5210. // Store to null is undefined.
  5211. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  5212. if (!SI->isVolatile())
  5213. return (!NullPointerIsDefined(SI->getFunction(),
  5214. SI->getPointerAddressSpace())) &&
  5215. SI->getPointerOperand() == I;
  5216. // A call to null is undefined.
  5217. if (auto CS = CallSite(Use))
  5218. return !NullPointerIsDefined(CS->getFunction()) &&
  5219. CS.getCalledValue() == I;
  5220. }
  5221. return false;
  5222. }
  5223. /// If BB has an incoming value that will always trigger undefined behavior
  5224. /// (eg. null pointer dereference), remove the branch leading here.
  5225. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  5226. for (PHINode &PHI : BB->phis())
  5227. for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
  5228. if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
  5229. Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
  5230. IRBuilder<> Builder(T);
  5231. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  5232. BB->removePredecessor(PHI.getIncomingBlock(i));
  5233. // Turn uncoditional branches into unreachables and remove the dead
  5234. // destination from conditional branches.
  5235. if (BI->isUnconditional())
  5236. Builder.CreateUnreachable();
  5237. else
  5238. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
  5239. : BI->getSuccessor(0));
  5240. BI->eraseFromParent();
  5241. return true;
  5242. }
  5243. // TODO: SwitchInst.
  5244. }
  5245. return false;
  5246. }
  5247. bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
  5248. bool Changed = false;
  5249. assert(BB && BB->getParent() && "Block not embedded in function!");
  5250. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  5251. // Remove basic blocks that have no predecessors (except the entry block)...
  5252. // or that just have themself as a predecessor. These are unreachable.
  5253. if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
  5254. BB->getSinglePredecessor() == BB) {
  5255. LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
  5256. DeleteDeadBlock(BB);
  5257. return true;
  5258. }
  5259. // Check to see if we can constant propagate this terminator instruction
  5260. // away...
  5261. Changed |= ConstantFoldTerminator(BB, true);
  5262. // Check for and eliminate duplicate PHI nodes in this block.
  5263. Changed |= EliminateDuplicatePHINodes(BB);
  5264. // Check for and remove branches that will always cause undefined behavior.
  5265. Changed |= removeUndefIntroducingPredecessor(BB);
  5266. // Merge basic blocks into their predecessor if there is only one distinct
  5267. // pred, and if there is only one distinct successor of the predecessor, and
  5268. // if there are no PHI nodes.
  5269. if (MergeBlockIntoPredecessor(BB))
  5270. return true;
  5271. if (SinkCommon && Options.SinkCommonInsts)
  5272. Changed |= SinkCommonCodeFromPredecessors(BB);
  5273. IRBuilder<> Builder(BB);
  5274. // If there is a trivial two-entry PHI node in this basic block, and we can
  5275. // eliminate it, do so now.
  5276. if (auto *PN = dyn_cast<PHINode>(BB->begin()))
  5277. if (PN->getNumIncomingValues() == 2)
  5278. Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
  5279. Builder.SetInsertPoint(BB->getTerminator());
  5280. if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  5281. if (BI->isUnconditional()) {
  5282. if (SimplifyUncondBranch(BI, Builder))
  5283. return true;
  5284. } else {
  5285. if (SimplifyCondBranch(BI, Builder))
  5286. return true;
  5287. }
  5288. } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  5289. if (SimplifyReturn(RI, Builder))
  5290. return true;
  5291. } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  5292. if (SimplifyResume(RI, Builder))
  5293. return true;
  5294. } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  5295. if (SimplifyCleanupReturn(RI))
  5296. return true;
  5297. } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  5298. if (SimplifySwitch(SI, Builder))
  5299. return true;
  5300. } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) {
  5301. if (SimplifyUnreachable(UI))
  5302. return true;
  5303. } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  5304. if (SimplifyIndirectBr(IBI))
  5305. return true;
  5306. }
  5307. return Changed;
  5308. }
  5309. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  5310. bool Changed = false;
  5311. // Repeated simplify BB as long as resimplification is requested.
  5312. do {
  5313. Resimplify = false;
  5314. // Perform one round of simplifcation. Resimplify flag will be set if
  5315. // another iteration is requested.
  5316. Changed |= simplifyOnce(BB);
  5317. } while (Resimplify);
  5318. return Changed;
  5319. }
  5320. bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  5321. const SimplifyCFGOptions &Options,
  5322. SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
  5323. return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
  5324. Options)
  5325. .run(BB);
  5326. }