SimplifyCFG.cpp 182 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741
  1. //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Peephole optimize the CFG.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/Local.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/CFG.h"
  25. #include "llvm/IR/ConstantRange.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/GlobalVariable.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/NoFolder.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/PatternMatch.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/ValueMapper.h"
  47. #include <algorithm>
  48. #include <map>
  49. #include <set>
  50. #include "dxc/DXIL/DxilMetadataHelper.h" // HLSL Change - control flow hint.
  51. using namespace llvm;
  52. using namespace PatternMatch;
  53. #define DEBUG_TYPE "simplifycfg"
  54. // Chosen as 2 so as to be cheap, but still to have enough power to fold
  55. // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
  56. // To catch this, we need to fold a compare and a select, hence '2' being the
  57. // minimum reasonable default.
  58. #if 0 // HLSL Change Starts - option pending
  59. static cl::opt<unsigned>
  60. PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
  61. cl::desc("Control the amount of phi node folding to perform (default = 2)"));
  62. static cl::opt<bool>
  63. DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  64. cl::desc("Duplicate return instructions into unconditional branches"));
  65. static cl::opt<bool>
  66. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  67. cl::desc("Sink common instructions down to the end block"));
  68. static cl::opt<bool> HoistCondStores(
  69. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  70. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  71. #else
  72. static const unsigned PHINodeFoldingThreshold = 2;
  73. static const bool DupRet = false;
  74. static const bool SinkCommon = true;
  75. static const bool HoistCondStores = true;
  76. #endif // HLSL Change Ends
  77. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  78. STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
  79. STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
  80. STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
  81. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  82. STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
  83. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  84. namespace {
  85. // The first field contains the value that the switch produces when a certain
  86. // case group is selected, and the second field is a vector containing the cases
  87. // composing the case group.
  88. typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
  89. SwitchCaseResultVectorTy;
  90. // The first field contains the phi node that generates a result of the switch
  91. // and the second field contains the value generated for a certain case in the switch
  92. // for that PHI.
  93. typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
  94. /// ValueEqualityComparisonCase - Represents a case of a switch.
  95. struct ValueEqualityComparisonCase {
  96. ConstantInt *Value;
  97. BasicBlock *Dest;
  98. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  99. : Value(Value), Dest(Dest) {}
  100. bool operator<(ValueEqualityComparisonCase RHS) const {
  101. // Comparing pointers is ok as we only rely on the order for uniquing.
  102. return Value < RHS.Value;
  103. }
  104. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  105. };
  106. class SimplifyCFGOpt {
  107. const TargetTransformInfo &TTI;
  108. const DataLayout &DL;
  109. unsigned BonusInstThreshold;
  110. AssumptionCache *AC;
  111. Value *isValueEqualityComparison(TerminatorInst *TI);
  112. BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
  113. std::vector<ValueEqualityComparisonCase> &Cases);
  114. bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  115. BasicBlock *Pred,
  116. IRBuilder<> &Builder);
  117. bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  118. IRBuilder<> &Builder);
  119. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  120. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  121. bool SimplifyUnreachable(UnreachableInst *UI);
  122. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  123. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  124. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
  125. bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
  126. public:
  127. SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
  128. unsigned BonusInstThreshold, AssumptionCache *AC)
  129. : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
  130. bool run(BasicBlock *BB);
  131. };
  132. }
  133. /// Return true if it is safe to merge these two
  134. /// terminator instructions together.
  135. static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
  136. if (SI1 == SI2) return false; // Can't merge with self!
  137. // It is not safe to merge these two switch instructions if they have a common
  138. // successor, and if that successor has a PHI node, and if *that* PHI node has
  139. // conflicting incoming values from the two switch blocks.
  140. BasicBlock *SI1BB = SI1->getParent();
  141. BasicBlock *SI2BB = SI2->getParent();
  142. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  143. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  144. if (SI1Succs.count(*I))
  145. for (BasicBlock::iterator BBI = (*I)->begin();
  146. isa<PHINode>(BBI); ++BBI) {
  147. PHINode *PN = cast<PHINode>(BBI);
  148. if (PN->getIncomingValueForBlock(SI1BB) !=
  149. PN->getIncomingValueForBlock(SI2BB))
  150. return false;
  151. }
  152. return true;
  153. }
  154. /// Return true if it is safe and profitable to merge these two terminator
  155. /// instructions together, where SI1 is an unconditional branch. PhiNodes will
  156. /// store all PHI nodes in common successors.
  157. static bool isProfitableToFoldUnconditional(BranchInst *SI1,
  158. BranchInst *SI2,
  159. Instruction *Cond,
  160. SmallVectorImpl<PHINode*> &PhiNodes) {
  161. if (SI1 == SI2) return false; // Can't merge with self!
  162. assert(SI1->isUnconditional() && SI2->isConditional());
  163. // We fold the unconditional branch if we can easily update all PHI nodes in
  164. // common successors:
  165. // 1> We have a constant incoming value for the conditional branch;
  166. // 2> We have "Cond" as the incoming value for the unconditional branch;
  167. // 3> SI2->getCondition() and Cond have same operands.
  168. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  169. if (!Ci2) return false;
  170. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  171. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  172. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  173. Cond->getOperand(1) == Ci2->getOperand(0)))
  174. return false;
  175. BasicBlock *SI1BB = SI1->getParent();
  176. BasicBlock *SI2BB = SI2->getParent();
  177. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  178. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  179. if (SI1Succs.count(*I))
  180. for (BasicBlock::iterator BBI = (*I)->begin();
  181. isa<PHINode>(BBI); ++BBI) {
  182. PHINode *PN = cast<PHINode>(BBI);
  183. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  184. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  185. return false;
  186. PhiNodes.push_back(PN);
  187. }
  188. return true;
  189. }
  190. /// Update PHI nodes in Succ to indicate that there will now be entries in it
  191. /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
  192. /// will be the same as those coming in from ExistPred, an existing predecessor
  193. /// of Succ.
  194. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  195. BasicBlock *ExistPred) {
  196. if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
  197. PHINode *PN;
  198. for (BasicBlock::iterator I = Succ->begin();
  199. (PN = dyn_cast<PHINode>(I)); ++I)
  200. PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
  201. }
  202. /// Compute an abstract "cost" of speculating the given instruction,
  203. /// which is assumed to be safe to speculate. TCC_Free means cheap,
  204. /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
  205. /// expensive.
  206. static unsigned ComputeSpeculationCost(const User *I,
  207. const TargetTransformInfo &TTI) {
  208. assert(isSafeToSpeculativelyExecute(I) &&
  209. "Instruction is not safe to speculatively execute!");
  210. return TTI.getUserCost(I);
  211. }
  212. /// If we have a merge point of an "if condition" as accepted above,
  213. /// return true if the specified value dominates the block. We
  214. /// don't handle the true generality of domination here, just a special case
  215. /// which works well enough for us.
  216. ///
  217. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  218. /// see if V (which must be an instruction) and its recursive operands
  219. /// that do not dominate BB have a combined cost lower than CostRemaining and
  220. /// are non-trapping. If both are true, the instruction is inserted into the
  221. /// set and true is returned.
  222. ///
  223. /// The cost for most non-trapping instructions is defined as 1 except for
  224. /// Select whose cost is 2.
  225. ///
  226. /// After this function returns, CostRemaining is decreased by the cost of
  227. /// V plus its non-dominating operands. If that cost is greater than
  228. /// CostRemaining, false is returned and CostRemaining is undefined.
  229. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  230. SmallPtrSetImpl<Instruction*> *AggressiveInsts,
  231. unsigned &CostRemaining,
  232. const TargetTransformInfo &TTI) {
  233. Instruction *I = dyn_cast<Instruction>(V);
  234. if (!I) {
  235. // Non-instructions all dominate instructions, but not all constantexprs
  236. // can be executed unconditionally.
  237. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  238. if (C->canTrap())
  239. return false;
  240. return true;
  241. }
  242. BasicBlock *PBB = I->getParent();
  243. // We don't want to allow weird loops that might have the "if condition" in
  244. // the bottom of this block.
  245. if (PBB == BB) return false;
  246. // If this instruction is defined in a block that contains an unconditional
  247. // branch to BB, then it must be in the 'conditional' part of the "if
  248. // statement". If not, it definitely dominates the region.
  249. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  250. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  251. return true;
  252. // If we aren't allowing aggressive promotion anymore, then don't consider
  253. // instructions in the 'if region'.
  254. if (!AggressiveInsts) return false;
  255. // If we have seen this instruction before, don't count it again.
  256. if (AggressiveInsts->count(I)) return true;
  257. // Okay, it looks like the instruction IS in the "condition". Check to
  258. // see if it's a cheap instruction to unconditionally compute, and if it
  259. // only uses stuff defined outside of the condition. If so, hoist it out.
  260. if (!isSafeToSpeculativelyExecute(I))
  261. return false;
  262. unsigned Cost = ComputeSpeculationCost(I, TTI);
  263. if (Cost > CostRemaining)
  264. return false;
  265. CostRemaining -= Cost;
  266. // Okay, we can only really hoist these out if their operands do
  267. // not take us over the cost threshold.
  268. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  269. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
  270. return false;
  271. // Okay, it's safe to do this! Remember this instruction.
  272. AggressiveInsts->insert(I);
  273. return true;
  274. }
  275. /// Extract ConstantInt from value, looking through IntToPtr
  276. /// and PointerNullValue. Return NULL if value is not a constant int.
  277. static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
  278. // Normal constant int.
  279. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  280. if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
  281. return CI;
  282. // This is some kind of pointer constant. Turn it into a pointer-sized
  283. // ConstantInt if possible.
  284. IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
  285. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  286. if (isa<ConstantPointerNull>(V))
  287. return ConstantInt::get(PtrTy, 0);
  288. // IntToPtr const int.
  289. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  290. if (CE->getOpcode() == Instruction::IntToPtr)
  291. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  292. // The constant is very likely to have the right type already.
  293. if (CI->getType() == PtrTy)
  294. return CI;
  295. else
  296. return cast<ConstantInt>
  297. (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  298. }
  299. return nullptr;
  300. }
  301. namespace {
  302. /// Given a chain of or (||) or and (&&) comparison of a value against a
  303. /// constant, this will try to recover the information required for a switch
  304. /// structure.
  305. /// It will depth-first traverse the chain of comparison, seeking for patterns
  306. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  307. /// representing the different cases for the switch.
  308. /// Note that if the chain is composed of '||' it will build the set of elements
  309. /// that matches the comparisons (i.e. any of this value validate the chain)
  310. /// while for a chain of '&&' it will build the set elements that make the test
  311. /// fail.
  312. struct ConstantComparesGatherer {
  313. const DataLayout &DL;
  314. Value *CompValue; /// Value found for the switch comparison
  315. Value *Extra; /// Extra clause to be checked before the switch
  316. SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
  317. unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
  318. /// Construct and compute the result for the comparison instruction Cond
  319. ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
  320. : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
  321. gather(Cond);
  322. }
  323. /// Prevent copy
  324. ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
  325. ConstantComparesGatherer &
  326. operator=(const ConstantComparesGatherer &) = delete;
  327. private:
  328. /// Try to set the current value used for the comparison, it succeeds only if
  329. /// it wasn't set before or if the new value is the same as the old one
  330. bool setValueOnce(Value *NewVal) {
  331. if(CompValue && CompValue != NewVal) return false;
  332. CompValue = NewVal;
  333. return (CompValue != nullptr);
  334. }
  335. /// Try to match Instruction "I" as a comparison against a constant and
  336. /// populates the array Vals with the set of values that match (or do not
  337. /// match depending on isEQ).
  338. /// Return false on failure. On success, the Value the comparison matched
  339. /// against is placed in CompValue.
  340. /// If CompValue is already set, the function is expected to fail if a match
  341. /// is found but the value compared to is different.
  342. bool matchInstruction(Instruction *I, bool isEQ) {
  343. // If this is an icmp against a constant, handle this as one of the cases.
  344. ICmpInst *ICI;
  345. ConstantInt *C;
  346. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  347. (C = GetConstantInt(I->getOperand(1), DL)))) {
  348. return false;
  349. }
  350. Value *RHSVal;
  351. ConstantInt *RHSC;
  352. // Pattern match a special case
  353. // (x & ~2^x) == y --> x == y || x == y|2^x
  354. // This undoes a transformation done by instcombine to fuse 2 compares.
  355. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
  356. if (match(ICI->getOperand(0),
  357. m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  358. APInt Not = ~RHSC->getValue();
  359. if (Not.isPowerOf2()) {
  360. // If we already have a value for the switch, it has to match!
  361. if(!setValueOnce(RHSVal))
  362. return false;
  363. Vals.push_back(C);
  364. Vals.push_back(ConstantInt::get(C->getContext(),
  365. C->getValue() | Not));
  366. UsedICmps++;
  367. return true;
  368. }
  369. }
  370. // If we already have a value for the switch, it has to match!
  371. if(!setValueOnce(ICI->getOperand(0)))
  372. return false;
  373. UsedICmps++;
  374. Vals.push_back(C);
  375. return ICI->getOperand(0);
  376. }
  377. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  378. ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
  379. ICI->getPredicate(), C->getValue());
  380. // Shift the range if the compare is fed by an add. This is the range
  381. // compare idiom as emitted by instcombine.
  382. Value *CandidateVal = I->getOperand(0);
  383. if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  384. Span = Span.subtract(RHSC->getValue());
  385. CandidateVal = RHSVal;
  386. }
  387. // If this is an and/!= check, then we are looking to build the set of
  388. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  389. // x != 0 && x != 1.
  390. if (!isEQ)
  391. Span = Span.inverse();
  392. // If there are a ton of values, we don't want to make a ginormous switch.
  393. if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
  394. return false;
  395. }
  396. // If we already have a value for the switch, it has to match!
  397. if(!setValueOnce(CandidateVal))
  398. return false;
  399. // Add all values from the range to the set
  400. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  401. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  402. UsedICmps++;
  403. return true;
  404. }
  405. /// Given a potentially 'or'd or 'and'd together collection of icmp
  406. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  407. /// the value being compared, and stick the list constants into the Vals
  408. /// vector.
  409. /// One "Extra" case is allowed to differ from the other.
  410. void gather(Value *V) {
  411. Instruction *I = dyn_cast<Instruction>(V);
  412. bool isEQ = (I->getOpcode() == Instruction::Or);
  413. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  414. SmallVector<Value *, 8> DFT;
  415. // Initialize
  416. DFT.push_back(V);
  417. while(!DFT.empty()) {
  418. V = DFT.pop_back_val();
  419. if (Instruction *I = dyn_cast<Instruction>(V)) {
  420. // If it is a || (or && depending on isEQ), process the operands.
  421. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  422. DFT.push_back(I->getOperand(1));
  423. DFT.push_back(I->getOperand(0));
  424. continue;
  425. }
  426. // Try to match the current instruction
  427. if (matchInstruction(I, isEQ))
  428. // Match succeed, continue the loop
  429. continue;
  430. }
  431. // One element of the sequence of || (or &&) could not be match as a
  432. // comparison against the same value as the others.
  433. // We allow only one "Extra" case to be checked before the switch
  434. if (!Extra) {
  435. Extra = V;
  436. continue;
  437. }
  438. // Failed to parse a proper sequence, abort now
  439. CompValue = nullptr;
  440. break;
  441. }
  442. }
  443. };
  444. }
  445. static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
  446. Instruction *Cond = nullptr;
  447. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  448. Cond = dyn_cast<Instruction>(SI->getCondition());
  449. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  450. if (BI->isConditional())
  451. Cond = dyn_cast<Instruction>(BI->getCondition());
  452. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  453. Cond = dyn_cast<Instruction>(IBI->getAddress());
  454. }
  455. TI->eraseFromParent();
  456. if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
  457. }
  458. /// Return true if the specified terminator checks
  459. /// to see if a value is equal to constant integer value.
  460. Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
  461. Value *CV = nullptr;
  462. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  463. // Do not permit merging of large switch instructions into their
  464. // predecessors unless there is only one predecessor.
  465. if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
  466. pred_end(SI->getParent())) <= 128)
  467. CV = SI->getCondition();
  468. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  469. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  470. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  471. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  472. CV = ICI->getOperand(0);
  473. }
  474. // Unwrap any lossless ptrtoint cast.
  475. if (CV) {
  476. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  477. Value *Ptr = PTII->getPointerOperand();
  478. if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
  479. CV = Ptr;
  480. }
  481. }
  482. return CV;
  483. }
  484. /// Given a value comparison instruction,
  485. /// decode all of the 'cases' that it represents and return the 'default' block.
  486. BasicBlock *SimplifyCFGOpt::
  487. GetValueEqualityComparisonCases(TerminatorInst *TI,
  488. std::vector<ValueEqualityComparisonCase>
  489. &Cases) {
  490. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  491. Cases.reserve(SI->getNumCases());
  492. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
  493. Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
  494. i.getCaseSuccessor()));
  495. return SI->getDefaultDest();
  496. }
  497. BranchInst *BI = cast<BranchInst>(TI);
  498. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  499. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  500. Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
  501. DL),
  502. Succ));
  503. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  504. }
  505. /// Given a vector of bb/value pairs, remove any entries
  506. /// in the list that match the specified block.
  507. static void EliminateBlockCases(BasicBlock *BB,
  508. std::vector<ValueEqualityComparisonCase> &Cases) {
  509. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  510. }
  511. /// Return true if there are any keys in C1 that exist in C2 as well.
  512. static bool
  513. ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  514. std::vector<ValueEqualityComparisonCase > &C2) {
  515. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  516. // Make V1 be smaller than V2.
  517. if (V1->size() > V2->size())
  518. std::swap(V1, V2);
  519. if (V1->size() == 0) return false;
  520. if (V1->size() == 1) {
  521. // Just scan V2.
  522. ConstantInt *TheVal = (*V1)[0].Value;
  523. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  524. if (TheVal == (*V2)[i].Value)
  525. return true;
  526. }
  527. // Otherwise, just sort both lists and compare element by element.
  528. array_pod_sort(V1->begin(), V1->end());
  529. array_pod_sort(V2->begin(), V2->end());
  530. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  531. while (i1 != e1 && i2 != e2) {
  532. if ((*V1)[i1].Value == (*V2)[i2].Value)
  533. return true;
  534. if ((*V1)[i1].Value < (*V2)[i2].Value)
  535. ++i1;
  536. else
  537. ++i2;
  538. }
  539. return false;
  540. }
  541. /// If TI is known to be a terminator instruction and its block is known to
  542. /// only have a single predecessor block, check to see if that predecessor is
  543. /// also a value comparison with the same value, and if that comparison
  544. /// determines the outcome of this comparison. If so, simplify TI. This does a
  545. /// very limited form of jump threading.
  546. bool SimplifyCFGOpt::
  547. SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  548. BasicBlock *Pred,
  549. IRBuilder<> &Builder) {
  550. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  551. if (!PredVal) return false; // Not a value comparison in predecessor.
  552. Value *ThisVal = isValueEqualityComparison(TI);
  553. assert(ThisVal && "This isn't a value comparison!!");
  554. if (ThisVal != PredVal) return false; // Different predicates.
  555. // TODO: Preserve branch weight metadata, similarly to how
  556. // FoldValueComparisonIntoPredecessors preserves it.
  557. // Find out information about when control will move from Pred to TI's block.
  558. std::vector<ValueEqualityComparisonCase> PredCases;
  559. BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
  560. PredCases);
  561. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  562. // Find information about how control leaves this block.
  563. std::vector<ValueEqualityComparisonCase> ThisCases;
  564. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  565. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  566. // If TI's block is the default block from Pred's comparison, potentially
  567. // simplify TI based on this knowledge.
  568. if (PredDef == TI->getParent()) {
  569. // If we are here, we know that the value is none of those cases listed in
  570. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  571. // can simplify TI.
  572. if (!ValuesOverlap(PredCases, ThisCases))
  573. return false;
  574. if (isa<BranchInst>(TI)) {
  575. // Okay, one of the successors of this condbr is dead. Convert it to a
  576. // uncond br.
  577. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  578. // Insert the new branch.
  579. Instruction *NI = Builder.CreateBr(ThisDef);
  580. (void) NI;
  581. // Remove PHI node entries for the dead edge.
  582. ThisCases[0].Dest->removePredecessor(TI->getParent());
  583. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  584. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  585. EraseTerminatorInstAndDCECond(TI);
  586. return true;
  587. }
  588. SwitchInst *SI = cast<SwitchInst>(TI);
  589. // Okay, TI has cases that are statically dead, prune them away.
  590. SmallPtrSet<Constant*, 16> DeadCases;
  591. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  592. DeadCases.insert(PredCases[i].Value);
  593. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  594. << "Through successor TI: " << *TI);
  595. // Collect branch weights into a vector.
  596. SmallVector<uint32_t, 8> Weights;
  597. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  598. bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
  599. if (HasWeight)
  600. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  601. ++MD_i) {
  602. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  603. Weights.push_back(CI->getValue().getZExtValue());
  604. }
  605. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  606. --i;
  607. if (DeadCases.count(i.getCaseValue())) {
  608. if (HasWeight) {
  609. std::swap(Weights[i.getCaseIndex()+1], Weights.back());
  610. Weights.pop_back();
  611. }
  612. i.getCaseSuccessor()->removePredecessor(TI->getParent());
  613. SI->removeCase(i);
  614. }
  615. }
  616. if (HasWeight && Weights.size() >= 2)
  617. SI->setMetadata(LLVMContext::MD_prof,
  618. MDBuilder(SI->getParent()->getContext()).
  619. createBranchWeights(Weights));
  620. DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  621. return true;
  622. }
  623. // Otherwise, TI's block must correspond to some matched value. Find out
  624. // which value (or set of values) this is.
  625. ConstantInt *TIV = nullptr;
  626. BasicBlock *TIBB = TI->getParent();
  627. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  628. if (PredCases[i].Dest == TIBB) {
  629. if (TIV)
  630. return false; // Cannot handle multiple values coming to this block.
  631. TIV = PredCases[i].Value;
  632. }
  633. assert(TIV && "No edge from pred to succ?");
  634. // Okay, we found the one constant that our value can be if we get into TI's
  635. // BB. Find out which successor will unconditionally be branched to.
  636. BasicBlock *TheRealDest = nullptr;
  637. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  638. if (ThisCases[i].Value == TIV) {
  639. TheRealDest = ThisCases[i].Dest;
  640. break;
  641. }
  642. // If not handled by any explicit cases, it is handled by the default case.
  643. if (!TheRealDest) TheRealDest = ThisDef;
  644. // Remove PHI node entries for dead edges.
  645. BasicBlock *CheckEdge = TheRealDest;
  646. for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
  647. if (*SI != CheckEdge)
  648. (*SI)->removePredecessor(TIBB);
  649. else
  650. CheckEdge = nullptr;
  651. // Insert the new branch.
  652. Instruction *NI = Builder.CreateBr(TheRealDest);
  653. (void) NI;
  654. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  655. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  656. EraseTerminatorInstAndDCECond(TI);
  657. return true;
  658. }
  659. namespace {
  660. /// This class implements a stable ordering of constant
  661. /// integers that does not depend on their address. This is important for
  662. /// applications that sort ConstantInt's to ensure uniqueness.
  663. struct ConstantIntOrdering {
  664. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  665. return LHS->getValue().ult(RHS->getValue());
  666. }
  667. };
  668. }
  669. // HLSL Change: changed calling convention to __cdecl
  670. static int __cdecl ConstantIntSortPredicate(ConstantInt *const *P1,
  671. ConstantInt *const *P2) {
  672. const ConstantInt *LHS = *P1;
  673. const ConstantInt *RHS = *P2;
  674. if (LHS->getValue().ult(RHS->getValue()))
  675. return 1;
  676. if (LHS->getValue() == RHS->getValue())
  677. return 0;
  678. return -1;
  679. }
  680. static inline bool HasBranchWeights(const Instruction* I) {
  681. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  682. if (ProfMD && ProfMD->getOperand(0))
  683. if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  684. return MDS->getString().equals("branch_weights");
  685. return false;
  686. }
  687. /// Get Weights of a given TerminatorInst, the default weight is at the front
  688. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  689. /// metadata.
  690. static void GetBranchWeights(TerminatorInst *TI,
  691. SmallVectorImpl<uint64_t> &Weights) {
  692. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  693. assert(MD);
  694. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  695. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  696. Weights.push_back(CI->getValue().getZExtValue());
  697. }
  698. // If TI is a conditional eq, the default case is the false case,
  699. // and the corresponding branch-weight data is at index 2. We swap the
  700. // default weight to be the first entry.
  701. if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
  702. assert(Weights.size() == 2);
  703. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  704. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  705. std::swap(Weights.front(), Weights.back());
  706. }
  707. }
  708. /// Keep halving the weights until all can fit in uint32_t.
  709. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  710. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  711. if (Max > UINT_MAX) {
  712. unsigned Offset = 32 - countLeadingZeros(Max);
  713. for (uint64_t &I : Weights)
  714. I >>= Offset;
  715. }
  716. }
  717. /// The specified terminator is a value equality comparison instruction
  718. /// (either a switch or a branch on "X == c").
  719. /// See if any of the predecessors of the terminator block are value comparisons
  720. /// on the same value. If so, and if safe to do so, fold them together.
  721. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  722. IRBuilder<> &Builder) {
  723. #if 0 // HLSL Change - fold to switch will not help hlsl.
  724. BasicBlock *BB = TI->getParent();
  725. Value *CV = isValueEqualityComparison(TI); // CondVal
  726. assert(CV && "Not a comparison?");
  727. bool Changed = false;
  728. SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
  729. while (!Preds.empty()) {
  730. BasicBlock *Pred = Preds.pop_back_val();
  731. // See if the predecessor is a comparison with the same value.
  732. TerminatorInst *PTI = Pred->getTerminator();
  733. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  734. if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
  735. // Figure out which 'cases' to copy from SI to PSI.
  736. std::vector<ValueEqualityComparisonCase> BBCases;
  737. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  738. std::vector<ValueEqualityComparisonCase> PredCases;
  739. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  740. // Based on whether the default edge from PTI goes to BB or not, fill in
  741. // PredCases and PredDefault with the new switch cases we would like to
  742. // build.
  743. SmallVector<BasicBlock*, 8> NewSuccessors;
  744. // Update the branch weight metadata along the way
  745. SmallVector<uint64_t, 8> Weights;
  746. bool PredHasWeights = HasBranchWeights(PTI);
  747. bool SuccHasWeights = HasBranchWeights(TI);
  748. if (PredHasWeights) {
  749. GetBranchWeights(PTI, Weights);
  750. // branch-weight metadata is inconsistent here.
  751. if (Weights.size() != 1 + PredCases.size())
  752. PredHasWeights = SuccHasWeights = false;
  753. } else if (SuccHasWeights)
  754. // If there are no predecessor weights but there are successor weights,
  755. // populate Weights with 1, which will later be scaled to the sum of
  756. // successor's weights
  757. Weights.assign(1 + PredCases.size(), 1);
  758. SmallVector<uint64_t, 8> SuccWeights;
  759. if (SuccHasWeights) {
  760. GetBranchWeights(TI, SuccWeights);
  761. // branch-weight metadata is inconsistent here.
  762. if (SuccWeights.size() != 1 + BBCases.size())
  763. PredHasWeights = SuccHasWeights = false;
  764. } else if (PredHasWeights)
  765. SuccWeights.assign(1 + BBCases.size(), 1);
  766. if (PredDefault == BB) {
  767. // If this is the default destination from PTI, only the edges in TI
  768. // that don't occur in PTI, or that branch to BB will be activated.
  769. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  770. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  771. if (PredCases[i].Dest != BB)
  772. PTIHandled.insert(PredCases[i].Value);
  773. else {
  774. // The default destination is BB, we don't need explicit targets.
  775. std::swap(PredCases[i], PredCases.back());
  776. if (PredHasWeights || SuccHasWeights) {
  777. // Increase weight for the default case.
  778. Weights[0] += Weights[i+1];
  779. std::swap(Weights[i+1], Weights.back());
  780. Weights.pop_back();
  781. }
  782. PredCases.pop_back();
  783. --i; --e;
  784. }
  785. // Reconstruct the new switch statement we will be building.
  786. if (PredDefault != BBDefault) {
  787. PredDefault->removePredecessor(Pred);
  788. PredDefault = BBDefault;
  789. NewSuccessors.push_back(BBDefault);
  790. }
  791. unsigned CasesFromPred = Weights.size();
  792. uint64_t ValidTotalSuccWeight = 0;
  793. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  794. if (!PTIHandled.count(BBCases[i].Value) &&
  795. BBCases[i].Dest != BBDefault) {
  796. PredCases.push_back(BBCases[i]);
  797. NewSuccessors.push_back(BBCases[i].Dest);
  798. if (SuccHasWeights || PredHasWeights) {
  799. // The default weight is at index 0, so weight for the ith case
  800. // should be at index i+1. Scale the cases from successor by
  801. // PredDefaultWeight (Weights[0]).
  802. Weights.push_back(Weights[0] * SuccWeights[i+1]);
  803. ValidTotalSuccWeight += SuccWeights[i+1];
  804. }
  805. }
  806. if (SuccHasWeights || PredHasWeights) {
  807. ValidTotalSuccWeight += SuccWeights[0];
  808. // Scale the cases from predecessor by ValidTotalSuccWeight.
  809. for (unsigned i = 1; i < CasesFromPred; ++i)
  810. Weights[i] *= ValidTotalSuccWeight;
  811. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  812. Weights[0] *= SuccWeights[0];
  813. }
  814. } else {
  815. // If this is not the default destination from PSI, only the edges
  816. // in SI that occur in PSI with a destination of BB will be
  817. // activated.
  818. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  819. std::map<ConstantInt*, uint64_t> WeightsForHandled;
  820. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  821. if (PredCases[i].Dest == BB) {
  822. PTIHandled.insert(PredCases[i].Value);
  823. if (PredHasWeights || SuccHasWeights) {
  824. WeightsForHandled[PredCases[i].Value] = Weights[i+1];
  825. std::swap(Weights[i+1], Weights.back());
  826. Weights.pop_back();
  827. }
  828. std::swap(PredCases[i], PredCases.back());
  829. PredCases.pop_back();
  830. --i; --e;
  831. }
  832. // Okay, now we know which constants were sent to BB from the
  833. // predecessor. Figure out where they will all go now.
  834. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  835. if (PTIHandled.count(BBCases[i].Value)) {
  836. // If this is one we are capable of getting...
  837. if (PredHasWeights || SuccHasWeights)
  838. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  839. PredCases.push_back(BBCases[i]);
  840. NewSuccessors.push_back(BBCases[i].Dest);
  841. PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
  842. }
  843. // If there are any constants vectored to BB that TI doesn't handle,
  844. // they must go to the default destination of TI.
  845. for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
  846. PTIHandled.begin(),
  847. E = PTIHandled.end(); I != E; ++I) {
  848. if (PredHasWeights || SuccHasWeights)
  849. Weights.push_back(WeightsForHandled[*I]);
  850. PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
  851. NewSuccessors.push_back(BBDefault);
  852. }
  853. }
  854. // Okay, at this point, we know which new successor Pred will get. Make
  855. // sure we update the number of entries in the PHI nodes for these
  856. // successors.
  857. for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
  858. AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
  859. Builder.SetInsertPoint(PTI);
  860. // Convert pointer to int before we switch.
  861. if (CV->getType()->isPointerTy()) {
  862. CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
  863. "magicptr");
  864. }
  865. // Now that the successors are updated, create the new Switch instruction.
  866. SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
  867. PredCases.size());
  868. NewSI->setDebugLoc(PTI->getDebugLoc());
  869. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  870. NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
  871. if (PredHasWeights || SuccHasWeights) {
  872. // Halve the weights if any of them cannot fit in an uint32_t
  873. FitWeights(Weights);
  874. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  875. NewSI->setMetadata(LLVMContext::MD_prof,
  876. MDBuilder(BB->getContext()).
  877. createBranchWeights(MDWeights));
  878. }
  879. EraseTerminatorInstAndDCECond(PTI);
  880. // Okay, last check. If BB is still a successor of PSI, then we must
  881. // have an infinite loop case. If so, add an infinitely looping block
  882. // to handle the case to preserve the behavior of the code.
  883. BasicBlock *InfLoopBlock = nullptr;
  884. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  885. if (NewSI->getSuccessor(i) == BB) {
  886. if (!InfLoopBlock) {
  887. // Insert it at the end of the function, because it's either code,
  888. // or it won't matter if it's hot. :)
  889. InfLoopBlock = BasicBlock::Create(BB->getContext(),
  890. "infloop", BB->getParent());
  891. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  892. }
  893. NewSI->setSuccessor(i, InfLoopBlock);
  894. }
  895. Changed = true;
  896. }
  897. }
  898. return Changed;
  899. #else // HLSL Change Begin. // fold to switch will not help hlsl.
  900. return false;
  901. #endif // HLSL Change End.
  902. }
  903. // If we would need to insert a select that uses the value of this invoke
  904. // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
  905. // can't hoist the invoke, as there is nowhere to put the select in this case.
  906. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  907. Instruction *I1, Instruction *I2) {
  908. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  909. PHINode *PN;
  910. for (BasicBlock::iterator BBI = SI->begin();
  911. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  912. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  913. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  914. if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
  915. return false;
  916. }
  917. }
  918. }
  919. return true;
  920. }
  921. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  922. /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
  923. /// in the two blocks up into the branch block. The caller of this function
  924. /// guarantees that BI's block dominates BB1 and BB2.
  925. static bool HoistThenElseCodeToIf(BranchInst *BI,
  926. const TargetTransformInfo &TTI) {
  927. // HLSL Change Begins.
  928. // Leave CSE to target backend.
  929. // Also wave operations should not be CSEed.
  930. return false;
  931. // HLSL Change Ends.
  932. // This does very trivial matching, with limited scanning, to find identical
  933. // instructions in the two blocks. In particular, we don't want to get into
  934. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  935. // such, we currently just scan for obviously identical instructions in an
  936. // identical order.
  937. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  938. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  939. BasicBlock::iterator BB1_Itr = BB1->begin();
  940. BasicBlock::iterator BB2_Itr = BB2->begin();
  941. Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
  942. // Skip debug info if it is not identical.
  943. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  944. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  945. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  946. while (isa<DbgInfoIntrinsic>(I1))
  947. I1 = BB1_Itr++;
  948. while (isa<DbgInfoIntrinsic>(I2))
  949. I2 = BB2_Itr++;
  950. }
  951. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  952. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  953. return false;
  954. BasicBlock *BIParent = BI->getParent();
  955. bool Changed = false;
  956. do {
  957. // If we are hoisting the terminator instruction, don't move one (making a
  958. // broken BB), instead clone it, and remove BI.
  959. if (isa<TerminatorInst>(I1))
  960. goto HoistTerminator;
  961. if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
  962. return Changed;
  963. // For a normal instruction, we just move one to right before the branch,
  964. // then replace all uses of the other with the first. Finally, we remove
  965. // the now redundant second instruction.
  966. BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
  967. if (!I2->use_empty())
  968. I2->replaceAllUsesWith(I1);
  969. I1->intersectOptionalDataWith(I2);
  970. unsigned KnownIDs[] = {
  971. LLVMContext::MD_tbaa,
  972. LLVMContext::MD_range,
  973. LLVMContext::MD_fpmath,
  974. LLVMContext::MD_invariant_load,
  975. LLVMContext::MD_nonnull
  976. };
  977. combineMetadata(I1, I2, KnownIDs);
  978. I2->eraseFromParent();
  979. Changed = true;
  980. I1 = BB1_Itr++;
  981. I2 = BB2_Itr++;
  982. // Skip debug info if it is not identical.
  983. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  984. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  985. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  986. while (isa<DbgInfoIntrinsic>(I1))
  987. I1 = BB1_Itr++;
  988. while (isa<DbgInfoIntrinsic>(I2))
  989. I2 = BB2_Itr++;
  990. }
  991. } while (I1->isIdenticalToWhenDefined(I2));
  992. return true;
  993. HoistTerminator:
  994. // It may not be possible to hoist an invoke.
  995. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  996. return Changed;
  997. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  998. PHINode *PN;
  999. for (BasicBlock::iterator BBI = SI->begin();
  1000. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  1001. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1002. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1003. if (BB1V == BB2V)
  1004. continue;
  1005. // Check for passingValueIsAlwaysUndefined here because we would rather
  1006. // eliminate undefined control flow then converting it to a select.
  1007. if (passingValueIsAlwaysUndefined(BB1V, PN) ||
  1008. passingValueIsAlwaysUndefined(BB2V, PN))
  1009. return Changed;
  1010. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
  1011. return Changed;
  1012. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
  1013. return Changed;
  1014. }
  1015. }
  1016. // Okay, it is safe to hoist the terminator.
  1017. Instruction *NT = I1->clone();
  1018. BIParent->getInstList().insert(BI, NT);
  1019. if (!NT->getType()->isVoidTy()) {
  1020. I1->replaceAllUsesWith(NT);
  1021. I2->replaceAllUsesWith(NT);
  1022. NT->takeName(I1);
  1023. }
  1024. IRBuilder<true, NoFolder> Builder(NT);
  1025. // Hoisting one of the terminators from our successor is a great thing.
  1026. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1027. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1028. // nodes, so we insert select instruction to compute the final result.
  1029. std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
  1030. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  1031. PHINode *PN;
  1032. for (BasicBlock::iterator BBI = SI->begin();
  1033. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  1034. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1035. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1036. if (BB1V == BB2V) continue;
  1037. // These values do not agree. Insert a select instruction before NT
  1038. // that determines the right value.
  1039. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1040. if (!SI)
  1041. SI = cast<SelectInst>
  1042. (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1043. BB1V->getName()+"."+BB2V->getName()));
  1044. // Make the PHI node use the select for all incoming values for BB1/BB2
  1045. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  1046. if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
  1047. PN->setIncomingValue(i, SI);
  1048. }
  1049. }
  1050. // Update any PHI nodes in our new successors.
  1051. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
  1052. AddPredecessorToBlock(*SI, BIParent, BB1);
  1053. EraseTerminatorInstAndDCECond(BI);
  1054. return true;
  1055. }
  1056. /// Given an unconditional branch that goes to BBEnd,
  1057. /// check whether BBEnd has only two predecessors and the other predecessor
  1058. /// ends with an unconditional branch. If it is true, sink any common code
  1059. /// in the two predecessors to BBEnd.
  1060. static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
  1061. assert(BI1->isUnconditional());
  1062. BasicBlock *BB1 = BI1->getParent();
  1063. BasicBlock *BBEnd = BI1->getSuccessor(0);
  1064. // Check that BBEnd has two predecessors and the other predecessor ends with
  1065. // an unconditional branch.
  1066. pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
  1067. BasicBlock *Pred0 = *PI++;
  1068. if (PI == PE) // Only one predecessor.
  1069. return false;
  1070. BasicBlock *Pred1 = *PI++;
  1071. if (PI != PE) // More than two predecessors.
  1072. return false;
  1073. BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
  1074. BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
  1075. if (!BI2 || !BI2->isUnconditional())
  1076. return false;
  1077. // Gather the PHI nodes in BBEnd.
  1078. SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
  1079. Instruction *FirstNonPhiInBBEnd = nullptr;
  1080. for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
  1081. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  1082. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1083. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1084. JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
  1085. } else {
  1086. FirstNonPhiInBBEnd = &*I;
  1087. break;
  1088. }
  1089. }
  1090. if (!FirstNonPhiInBBEnd)
  1091. return false;
  1092. // This does very trivial matching, with limited scanning, to find identical
  1093. // instructions in the two blocks. We scan backward for obviously identical
  1094. // instructions in an identical order.
  1095. BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
  1096. RE1 = BB1->getInstList().rend(),
  1097. RI2 = BB2->getInstList().rbegin(),
  1098. RE2 = BB2->getInstList().rend();
  1099. // Skip debug info.
  1100. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1101. if (RI1 == RE1)
  1102. return false;
  1103. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1104. if (RI2 == RE2)
  1105. return false;
  1106. // Skip the unconditional branches.
  1107. ++RI1;
  1108. ++RI2;
  1109. bool Changed = false;
  1110. while (RI1 != RE1 && RI2 != RE2) {
  1111. // Skip debug info.
  1112. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1113. if (RI1 == RE1)
  1114. return Changed;
  1115. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1116. if (RI2 == RE2)
  1117. return Changed;
  1118. Instruction *I1 = &*RI1, *I2 = &*RI2;
  1119. auto InstPair = std::make_pair(I1, I2);
  1120. // I1 and I2 should have a single use in the same PHI node, and they
  1121. // perform the same operation.
  1122. // Cannot move control-flow-involving, volatile loads, vaarg, etc.
  1123. if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
  1124. isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
  1125. isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
  1126. isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
  1127. I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
  1128. I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
  1129. !I1->hasOneUse() || !I2->hasOneUse() ||
  1130. !JointValueMap.count(InstPair))
  1131. return Changed;
  1132. // Check whether we should swap the operands of ICmpInst.
  1133. // TODO: Add support of communativity.
  1134. ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
  1135. bool SwapOpnds = false;
  1136. if (ICmp1 && ICmp2 &&
  1137. ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
  1138. ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
  1139. (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
  1140. ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
  1141. ICmp2->swapOperands();
  1142. SwapOpnds = true;
  1143. }
  1144. if (!I1->isSameOperationAs(I2)) {
  1145. if (SwapOpnds)
  1146. ICmp2->swapOperands();
  1147. return Changed;
  1148. }
  1149. // The operands should be either the same or they need to be generated
  1150. // with a PHI node after sinking. We only handle the case where there is
  1151. // a single pair of different operands.
  1152. Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
  1153. unsigned Op1Idx = ~0U;
  1154. for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
  1155. if (I1->getOperand(I) == I2->getOperand(I))
  1156. continue;
  1157. // Early exit if we have more-than one pair of different operands or if
  1158. // we need a PHI node to replace a constant.
  1159. if (Op1Idx != ~0U ||
  1160. isa<Constant>(I1->getOperand(I)) ||
  1161. isa<Constant>(I2->getOperand(I))) {
  1162. // If we can't sink the instructions, undo the swapping.
  1163. if (SwapOpnds)
  1164. ICmp2->swapOperands();
  1165. return Changed;
  1166. }
  1167. DifferentOp1 = I1->getOperand(I);
  1168. Op1Idx = I;
  1169. DifferentOp2 = I2->getOperand(I);
  1170. }
  1171. // HLSL Change Begin.
  1172. // Don't sink struct type which will generate struct PhiNode to make sure
  1173. // struct type value only used by Extract/InsertValue.
  1174. if (DifferentOp1 && DifferentOp1->getType()->isStructTy())
  1175. return Changed;
  1176. // HLSL Change End.
  1177. DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
  1178. DEBUG(dbgs() << " " << *I2 << "\n");
  1179. // We insert the pair of different operands to JointValueMap and
  1180. // remove (I1, I2) from JointValueMap.
  1181. if (Op1Idx != ~0U) {
  1182. auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
  1183. if (!NewPN) {
  1184. NewPN =
  1185. PHINode::Create(DifferentOp1->getType(), 2,
  1186. DifferentOp1->getName() + ".sink", BBEnd->begin());
  1187. NewPN->addIncoming(DifferentOp1, BB1);
  1188. NewPN->addIncoming(DifferentOp2, BB2);
  1189. DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
  1190. }
  1191. // I1 should use NewPN instead of DifferentOp1.
  1192. I1->setOperand(Op1Idx, NewPN);
  1193. }
  1194. PHINode *OldPN = JointValueMap[InstPair];
  1195. JointValueMap.erase(InstPair);
  1196. // We need to update RE1 and RE2 if we are going to sink the first
  1197. // instruction in the basic block down.
  1198. bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
  1199. // Sink the instruction.
  1200. BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
  1201. if (!OldPN->use_empty())
  1202. OldPN->replaceAllUsesWith(I1);
  1203. OldPN->eraseFromParent();
  1204. if (!I2->use_empty())
  1205. I2->replaceAllUsesWith(I1);
  1206. I1->intersectOptionalDataWith(I2);
  1207. // TODO: Use combineMetadata here to preserve what metadata we can
  1208. // (analogous to the hoisting case above).
  1209. I2->eraseFromParent();
  1210. if (UpdateRE1)
  1211. RE1 = BB1->getInstList().rend();
  1212. if (UpdateRE2)
  1213. RE2 = BB2->getInstList().rend();
  1214. FirstNonPhiInBBEnd = I1;
  1215. NumSinkCommons++;
  1216. Changed = true;
  1217. }
  1218. return Changed;
  1219. }
  1220. /// \brief Determine if we can hoist sink a sole store instruction out of a
  1221. /// conditional block.
  1222. ///
  1223. /// We are looking for code like the following:
  1224. /// BrBB:
  1225. /// store i32 %add, i32* %arrayidx2
  1226. /// ... // No other stores or function calls (we could be calling a memory
  1227. /// ... // function).
  1228. /// %cmp = icmp ult %x, %y
  1229. /// br i1 %cmp, label %EndBB, label %ThenBB
  1230. /// ThenBB:
  1231. /// store i32 %add5, i32* %arrayidx2
  1232. /// br label EndBB
  1233. /// EndBB:
  1234. /// ...
  1235. /// We are going to transform this into:
  1236. /// BrBB:
  1237. /// store i32 %add, i32* %arrayidx2
  1238. /// ... //
  1239. /// %cmp = icmp ult %x, %y
  1240. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1241. /// store i32 %add.add5, i32* %arrayidx2
  1242. /// ...
  1243. ///
  1244. /// \return The pointer to the value of the previous store if the store can be
  1245. /// hoisted into the predecessor block. 0 otherwise.
  1246. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1247. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1248. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1249. if (!StoreToHoist)
  1250. return nullptr;
  1251. // Volatile or atomic.
  1252. if (!StoreToHoist->isSimple())
  1253. return nullptr;
  1254. Value *StorePtr = StoreToHoist->getPointerOperand();
  1255. // Look for a store to the same pointer in BrBB.
  1256. unsigned MaxNumInstToLookAt = 10;
  1257. for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
  1258. RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
  1259. Instruction *CurI = &*RI;
  1260. // Could be calling an instruction that effects memory like free().
  1261. if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1262. return nullptr;
  1263. StoreInst *SI = dyn_cast<StoreInst>(CurI);
  1264. // Found the previous store make sure it stores to the same location.
  1265. if (SI && SI->getPointerOperand() == StorePtr)
  1266. // Found the previous store, return its value operand.
  1267. return SI->getValueOperand();
  1268. else if (SI)
  1269. return nullptr; // Unknown store.
  1270. }
  1271. return nullptr;
  1272. }
  1273. /// \brief Speculate a conditional basic block flattening the CFG.
  1274. ///
  1275. /// Note that this is a very risky transform currently. Speculating
  1276. /// instructions like this is most often not desirable. Instead, there is an MI
  1277. /// pass which can do it with full awareness of the resource constraints.
  1278. /// However, some cases are "obvious" and we should do directly. An example of
  1279. /// this is speculating a single, reasonably cheap instruction.
  1280. ///
  1281. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1282. /// it makes very common but simplistic optimizations such as are common in
  1283. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1284. /// modeling their effects with easier to reason about SSA value graphs.
  1285. ///
  1286. ///
  1287. /// An illustration of this transform is turning this IR:
  1288. /// \code
  1289. /// BB:
  1290. /// %cmp = icmp ult %x, %y
  1291. /// br i1 %cmp, label %EndBB, label %ThenBB
  1292. /// ThenBB:
  1293. /// %sub = sub %x, %y
  1294. /// br label BB2
  1295. /// EndBB:
  1296. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1297. /// ...
  1298. /// \endcode
  1299. ///
  1300. /// Into this IR:
  1301. /// \code
  1302. /// BB:
  1303. /// %cmp = icmp ult %x, %y
  1304. /// %sub = sub %x, %y
  1305. /// %cond = select i1 %cmp, 0, %sub
  1306. /// ...
  1307. /// \endcode
  1308. ///
  1309. /// \returns true if the conditional block is removed.
  1310. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1311. const TargetTransformInfo &TTI) {
  1312. // HLSL Change Begins.
  1313. // Skip block with control flow hint.
  1314. if (hlsl::DxilMDHelper::HasControlFlowHintToPreventFlatten(BI)) {
  1315. return false;
  1316. }
  1317. // HLSL Change Ends.
  1318. // Be conservative for now. FP select instruction can often be expensive.
  1319. Value *BrCond = BI->getCondition();
  1320. if (isa<FCmpInst>(BrCond))
  1321. return false;
  1322. BasicBlock *BB = BI->getParent();
  1323. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1324. // If ThenBB is actually on the false edge of the conditional branch, remember
  1325. // to swap the select operands later.
  1326. bool Invert = false;
  1327. if (ThenBB != BI->getSuccessor(0)) {
  1328. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1329. Invert = true;
  1330. }
  1331. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1332. // Keep a count of how many times instructions are used within CondBB when
  1333. // they are candidates for sinking into CondBB. Specifically:
  1334. // - They are defined in BB, and
  1335. // - They have no side effects, and
  1336. // - All of their uses are in CondBB.
  1337. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1338. unsigned SpeculationCost = 0;
  1339. Value *SpeculatedStoreValue = nullptr;
  1340. StoreInst *SpeculatedStore = nullptr;
  1341. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1342. BBE = std::prev(ThenBB->end());
  1343. BBI != BBE; ++BBI) {
  1344. Instruction *I = BBI;
  1345. // Skip debug info.
  1346. if (isa<DbgInfoIntrinsic>(I))
  1347. continue;
  1348. // Only speculatively execute a single instruction (not counting the
  1349. // terminator) for now.
  1350. ++SpeculationCost;
  1351. if (SpeculationCost > 1)
  1352. return false;
  1353. // Don't hoist the instruction if it's unsafe or expensive.
  1354. if (!isSafeToSpeculativelyExecute(I) &&
  1355. !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
  1356. I, BB, ThenBB, EndBB))))
  1357. return false;
  1358. if (!SpeculatedStoreValue &&
  1359. ComputeSpeculationCost(I, TTI) >
  1360. PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
  1361. return false;
  1362. // Store the store speculation candidate.
  1363. if (SpeculatedStoreValue)
  1364. SpeculatedStore = cast<StoreInst>(I);
  1365. // Do not hoist the instruction if any of its operands are defined but not
  1366. // used in BB. The transformation will prevent the operand from
  1367. // being sunk into the use block.
  1368. for (User::op_iterator i = I->op_begin(), e = I->op_end();
  1369. i != e; ++i) {
  1370. Instruction *OpI = dyn_cast<Instruction>(*i);
  1371. if (!OpI || OpI->getParent() != BB ||
  1372. OpI->mayHaveSideEffects())
  1373. continue; // Not a candidate for sinking.
  1374. ++SinkCandidateUseCounts[OpI];
  1375. }
  1376. }
  1377. // Consider any sink candidates which are only used in CondBB as costs for
  1378. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1379. // and so iteration order isn't significant.
  1380. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
  1381. SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
  1382. I != E; ++I)
  1383. if (I->first->getNumUses() == I->second) {
  1384. ++SpeculationCost;
  1385. if (SpeculationCost > 1)
  1386. return false;
  1387. }
  1388. // Check that the PHI nodes can be converted to selects.
  1389. bool HaveRewritablePHIs = false;
  1390. for (BasicBlock::iterator I = EndBB->begin();
  1391. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1392. Value *OrigV = PN->getIncomingValueForBlock(BB);
  1393. Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
  1394. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1395. // Skip PHIs which are trivial.
  1396. if (ThenV == OrigV)
  1397. continue;
  1398. // Don't convert to selects if we could remove undefined behavior instead.
  1399. if (passingValueIsAlwaysUndefined(OrigV, PN) ||
  1400. passingValueIsAlwaysUndefined(ThenV, PN))
  1401. return false;
  1402. HaveRewritablePHIs = true;
  1403. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1404. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1405. if (!OrigCE && !ThenCE)
  1406. continue; // Known safe and cheap.
  1407. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
  1408. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
  1409. return false;
  1410. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
  1411. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
  1412. unsigned MaxCost = 2 * PHINodeFoldingThreshold *
  1413. TargetTransformInfo::TCC_Basic;
  1414. if (OrigCost + ThenCost > MaxCost)
  1415. return false;
  1416. // Account for the cost of an unfolded ConstantExpr which could end up
  1417. // getting expanded into Instructions.
  1418. // FIXME: This doesn't account for how many operations are combined in the
  1419. // constant expression.
  1420. ++SpeculationCost;
  1421. if (SpeculationCost > 1)
  1422. return false;
  1423. }
  1424. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1425. // as well.
  1426. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1427. return false;
  1428. // If we get here, we can hoist the instruction and if-convert.
  1429. DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1430. // Insert a select of the value of the speculated store.
  1431. if (SpeculatedStoreValue) {
  1432. IRBuilder<true, NoFolder> Builder(BI);
  1433. Value *TrueV = SpeculatedStore->getValueOperand();
  1434. Value *FalseV = SpeculatedStoreValue;
  1435. if (Invert)
  1436. std::swap(TrueV, FalseV);
  1437. Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
  1438. "." + FalseV->getName());
  1439. SpeculatedStore->setOperand(0, S);
  1440. }
  1441. // Hoist the instructions.
  1442. BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
  1443. std::prev(ThenBB->end()));
  1444. // Insert selects and rewrite the PHI operands.
  1445. IRBuilder<true, NoFolder> Builder(BI);
  1446. for (BasicBlock::iterator I = EndBB->begin();
  1447. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1448. unsigned OrigI = PN->getBasicBlockIndex(BB);
  1449. unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
  1450. Value *OrigV = PN->getIncomingValue(OrigI);
  1451. Value *ThenV = PN->getIncomingValue(ThenI);
  1452. // Skip PHIs which are trivial.
  1453. if (OrigV == ThenV)
  1454. continue;
  1455. // Create a select whose true value is the speculatively executed value and
  1456. // false value is the preexisting value. Swap them if the branch
  1457. // destinations were inverted.
  1458. Value *TrueV = ThenV, *FalseV = OrigV;
  1459. if (Invert)
  1460. std::swap(TrueV, FalseV);
  1461. Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
  1462. TrueV->getName() + "." + FalseV->getName());
  1463. PN->setIncomingValue(OrigI, V);
  1464. PN->setIncomingValue(ThenI, V);
  1465. }
  1466. ++NumSpeculations;
  1467. return true;
  1468. }
  1469. #if 0 // HLSL Change - Unused function
  1470. /// \returns True if this block contains a CallInst with the NoDuplicate
  1471. /// attribute.
  1472. static bool HasNoDuplicateCall(const BasicBlock *BB) {
  1473. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  1474. const CallInst *CI = dyn_cast<CallInst>(I);
  1475. if (!CI)
  1476. continue;
  1477. if (CI->cannotDuplicate())
  1478. return true;
  1479. }
  1480. return false;
  1481. }
  1482. #endif
  1483. /// Return true if we can thread a branch across this block.
  1484. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1485. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  1486. unsigned Size = 0;
  1487. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1488. if (isa<DbgInfoIntrinsic>(BBI))
  1489. continue;
  1490. if (Size > 10) return false; // Don't clone large BB's.
  1491. ++Size;
  1492. // We can only support instructions that do not define values that are
  1493. // live outside of the current basic block.
  1494. for (User *U : BBI->users()) {
  1495. Instruction *UI = cast<Instruction>(U);
  1496. if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
  1497. }
  1498. // Looks ok, continue checking.
  1499. }
  1500. return true;
  1501. }
  1502. #if 0 // HLSL Change - Unused function
  1503. /// If we have a conditional branch on a PHI node value that is defined in the
  1504. /// same block as the branch and if any PHI entries are constants, thread edges
  1505. /// corresponding to that entry to be branches to their ultimate destination.
  1506. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
  1507. BasicBlock *BB = BI->getParent();
  1508. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1509. // NOTE: we currently cannot transform this case if the PHI node is used
  1510. // outside of the block.
  1511. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1512. return false;
  1513. // Degenerate case of a single entry PHI.
  1514. if (PN->getNumIncomingValues() == 1) {
  1515. FoldSingleEntryPHINodes(PN->getParent());
  1516. return true;
  1517. }
  1518. // Now we know that this block has multiple preds and two succs.
  1519. if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
  1520. if (HasNoDuplicateCall(BB)) return false;
  1521. // Okay, this is a simple enough basic block. See if any phi values are
  1522. // constants.
  1523. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1524. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1525. if (!CB || !CB->getType()->isIntegerTy(1)) continue;
  1526. // Okay, we now know that all edges from PredBB should be revectored to
  1527. // branch to RealDest.
  1528. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1529. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1530. if (RealDest == BB) continue; // Skip self loops.
  1531. // Skip if the predecessor's terminator is an indirect branch.
  1532. if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
  1533. // The dest block might have PHI nodes, other predecessors and other
  1534. // difficult cases. Instead of being smart about this, just insert a new
  1535. // block that jumps to the destination block, effectively splitting
  1536. // the edge we are about to create.
  1537. BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
  1538. RealDest->getName()+".critedge",
  1539. RealDest->getParent(), RealDest);
  1540. BranchInst::Create(RealDest, EdgeBB);
  1541. // Update PHI nodes.
  1542. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1543. // BB may have instructions that are being threaded over. Clone these
  1544. // instructions into EdgeBB. We know that there will be no uses of the
  1545. // cloned instructions outside of EdgeBB.
  1546. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1547. DenseMap<Value*, Value*> TranslateMap; // Track translated values.
  1548. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1549. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1550. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1551. continue;
  1552. }
  1553. // Clone the instruction.
  1554. Instruction *N = BBI->clone();
  1555. if (BBI->hasName()) N->setName(BBI->getName()+".c");
  1556. // Update operands due to translation.
  1557. for (User::op_iterator i = N->op_begin(), e = N->op_end();
  1558. i != e; ++i) {
  1559. DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
  1560. if (PI != TranslateMap.end())
  1561. *i = PI->second;
  1562. }
  1563. // Check for trivial simplification.
  1564. if (Value *V = SimplifyInstruction(N, DL)) {
  1565. TranslateMap[BBI] = V;
  1566. delete N; // Instruction folded away, don't need actual inst
  1567. } else {
  1568. // Insert the new instruction into its new home.
  1569. EdgeBB->getInstList().insert(InsertPt, N);
  1570. if (!BBI->use_empty())
  1571. TranslateMap[BBI] = N;
  1572. }
  1573. }
  1574. // Loop over all of the edges from PredBB to BB, changing them to branch
  1575. // to EdgeBB instead.
  1576. TerminatorInst *PredBBTI = PredBB->getTerminator();
  1577. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1578. if (PredBBTI->getSuccessor(i) == BB) {
  1579. BB->removePredecessor(PredBB);
  1580. PredBBTI->setSuccessor(i, EdgeBB);
  1581. }
  1582. // Recurse, simplifying any other constants.
  1583. return FoldCondBranchOnPHI(BI, DL) | true;
  1584. }
  1585. return false;
  1586. }
  1587. #endif
  1588. /// Given a BB that starts with the specified two-entry PHI node,
  1589. /// see if we can eliminate it.
  1590. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
  1591. const DataLayout &DL) {
  1592. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1593. // statement", which has a very simple dominance structure. Basically, we
  1594. // are trying to find the condition that is being branched on, which
  1595. // subsequently causes this merge to happen. We really want control
  1596. // dependence information for this check, but simplifycfg can't keep it up
  1597. // to date, and this catches most of the cases we care about anyway.
  1598. BasicBlock *BB = PN->getParent();
  1599. BasicBlock *IfTrue, *IfFalse;
  1600. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  1601. if (!IfCond ||
  1602. // Don't bother if the branch will be constant folded trivially.
  1603. isa<ConstantInt>(IfCond))
  1604. return false;
  1605. // Okay, we found that we can merge this two-entry phi node into a select.
  1606. // Doing so would require us to fold *all* two entry phi nodes in this block.
  1607. // At some point this becomes non-profitable (particularly if the target
  1608. // doesn't support cmov's). Only do this transformation if there are two or
  1609. // fewer PHI nodes in this block.
  1610. unsigned NumPhis = 0;
  1611. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  1612. if (NumPhis > 2)
  1613. return false;
  1614. // Loop over the PHI's seeing if we can promote them all to select
  1615. // instructions. While we are at it, keep track of the instructions
  1616. // that need to be moved to the dominating block.
  1617. SmallPtrSet<Instruction*, 4> AggressiveInsts;
  1618. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  1619. MaxCostVal1 = PHINodeFoldingThreshold;
  1620. MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
  1621. MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
  1622. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  1623. PHINode *PN = cast<PHINode>(II++);
  1624. if (Value *V = SimplifyInstruction(PN, DL)) {
  1625. PN->replaceAllUsesWith(V);
  1626. PN->eraseFromParent();
  1627. continue;
  1628. }
  1629. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
  1630. MaxCostVal0, TTI) ||
  1631. !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
  1632. MaxCostVal1, TTI))
  1633. return false;
  1634. }
  1635. // If we folded the first phi, PN dangles at this point. Refresh it. If
  1636. // we ran out of PHIs then we simplified them all.
  1637. PN = dyn_cast<PHINode>(BB->begin());
  1638. if (!PN) return true;
  1639. // Don't fold i1 branches on PHIs which contain binary operators. These can
  1640. // often be turned into switches and other things.
  1641. if (PN->getType()->isIntegerTy(1) &&
  1642. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  1643. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  1644. isa<BinaryOperator>(IfCond)))
  1645. return false;
  1646. // If we all PHI nodes are promotable, check to make sure that all
  1647. // instructions in the predecessor blocks can be promoted as well. If
  1648. // not, we won't be able to get rid of the control flow, so it's not
  1649. // worth promoting to select instructions.
  1650. BasicBlock *DomBlock = nullptr;
  1651. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  1652. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  1653. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  1654. IfBlock1 = nullptr;
  1655. } else {
  1656. DomBlock = *pred_begin(IfBlock1);
  1657. for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
  1658. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1659. // This is not an aggressive instruction that we can promote.
  1660. // Because of this, we won't be able to get rid of the control
  1661. // flow, so the xform is not worth it.
  1662. return false;
  1663. }
  1664. }
  1665. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  1666. IfBlock2 = nullptr;
  1667. } else {
  1668. DomBlock = *pred_begin(IfBlock2);
  1669. for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
  1670. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1671. // This is not an aggressive instruction that we can promote.
  1672. // Because of this, we won't be able to get rid of the control
  1673. // flow, so the xform is not worth it.
  1674. return false;
  1675. }
  1676. }
  1677. DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
  1678. << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
  1679. // If we can still promote the PHI nodes after this gauntlet of tests,
  1680. // do all of the PHI's now.
  1681. Instruction *InsertPt = DomBlock->getTerminator();
  1682. // HLSL Change Begins.
  1683. // Skip block with control flow hint.
  1684. if (hlsl::DxilMDHelper::HasControlFlowHintToPreventFlatten(InsertPt)) {
  1685. return false;
  1686. }
  1687. // HLSL Change Ends.
  1688. IRBuilder<true, NoFolder> Builder(InsertPt);
  1689. // Move all 'aggressive' instructions, which are defined in the
  1690. // conditional parts of the if's up to the dominating block.
  1691. if (IfBlock1)
  1692. DomBlock->getInstList().splice(InsertPt,
  1693. IfBlock1->getInstList(), IfBlock1->begin(),
  1694. IfBlock1->getTerminator());
  1695. if (IfBlock2)
  1696. DomBlock->getInstList().splice(InsertPt,
  1697. IfBlock2->getInstList(), IfBlock2->begin(),
  1698. IfBlock2->getTerminator());
  1699. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  1700. // Change the PHI node into a select instruction.
  1701. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  1702. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  1703. SelectInst *NV =
  1704. cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
  1705. PN->replaceAllUsesWith(NV);
  1706. NV->takeName(PN);
  1707. PN->eraseFromParent();
  1708. }
  1709. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  1710. // has been flattened. Change DomBlock to jump directly to our new block to
  1711. // avoid other simplifycfg's kicking in on the diamond.
  1712. TerminatorInst *OldTI = DomBlock->getTerminator();
  1713. Builder.SetInsertPoint(OldTI);
  1714. Builder.CreateBr(BB);
  1715. OldTI->eraseFromParent();
  1716. return true;
  1717. }
  1718. /// If we found a conditional branch that goes to two returning blocks,
  1719. /// try to merge them together into one return,
  1720. /// introducing a select if the return values disagree.
  1721. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  1722. IRBuilder<> &Builder) {
  1723. assert(BI->isConditional() && "Must be a conditional branch");
  1724. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1725. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1726. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  1727. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  1728. // Check to ensure both blocks are empty (just a return) or optionally empty
  1729. // with PHI nodes. If there are other instructions, merging would cause extra
  1730. // computation on one path or the other.
  1731. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  1732. return false;
  1733. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  1734. return false;
  1735. Builder.SetInsertPoint(BI);
  1736. // Okay, we found a branch that is going to two return nodes. If
  1737. // there is no return value for this function, just change the
  1738. // branch into a return.
  1739. if (FalseRet->getNumOperands() == 0) {
  1740. TrueSucc->removePredecessor(BI->getParent());
  1741. FalseSucc->removePredecessor(BI->getParent());
  1742. Builder.CreateRetVoid();
  1743. EraseTerminatorInstAndDCECond(BI);
  1744. return true;
  1745. }
  1746. // Otherwise, figure out what the true and false return values are
  1747. // so we can insert a new select instruction.
  1748. Value *TrueValue = TrueRet->getReturnValue();
  1749. Value *FalseValue = FalseRet->getReturnValue();
  1750. // Unwrap any PHI nodes in the return blocks.
  1751. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  1752. if (TVPN->getParent() == TrueSucc)
  1753. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  1754. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  1755. if (FVPN->getParent() == FalseSucc)
  1756. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  1757. // In order for this transformation to be safe, we must be able to
  1758. // unconditionally execute both operands to the return. This is
  1759. // normally the case, but we could have a potentially-trapping
  1760. // constant expression that prevents this transformation from being
  1761. // safe.
  1762. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  1763. if (TCV->canTrap())
  1764. return false;
  1765. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  1766. if (FCV->canTrap())
  1767. return false;
  1768. // Okay, we collected all the mapped values and checked them for sanity, and
  1769. // defined to really do this transformation. First, update the CFG.
  1770. TrueSucc->removePredecessor(BI->getParent());
  1771. FalseSucc->removePredecessor(BI->getParent());
  1772. // Insert select instructions where needed.
  1773. Value *BrCond = BI->getCondition();
  1774. if (TrueValue) {
  1775. // Insert a select if the results differ.
  1776. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  1777. } else if (isa<UndefValue>(TrueValue)) {
  1778. TrueValue = FalseValue;
  1779. } else {
  1780. TrueValue = Builder.CreateSelect(BrCond, TrueValue,
  1781. FalseValue, "retval");
  1782. }
  1783. }
  1784. Value *RI = !TrueValue ?
  1785. Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  1786. (void) RI;
  1787. DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  1788. << "\n " << *BI << "NewRet = " << *RI
  1789. << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
  1790. EraseTerminatorInstAndDCECond(BI);
  1791. return true;
  1792. }
  1793. /// Given a conditional BranchInstruction, retrieve the probabilities of the
  1794. /// branch taking each edge. Fills in the two APInt parameters and returns true,
  1795. /// or returns false if no or invalid metadata was found.
  1796. static bool ExtractBranchMetadata(BranchInst *BI,
  1797. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  1798. assert(BI->isConditional() &&
  1799. "Looking for probabilities on unconditional branch?");
  1800. MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  1801. if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
  1802. ConstantInt *CITrue =
  1803. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1804. ConstantInt *CIFalse =
  1805. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1806. if (!CITrue || !CIFalse) return false;
  1807. ProbTrue = CITrue->getValue().getZExtValue();
  1808. ProbFalse = CIFalse->getValue().getZExtValue();
  1809. return true;
  1810. }
  1811. /// Return true if the given instruction is available
  1812. /// in its predecessor block. If yes, the instruction will be removed.
  1813. static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
  1814. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  1815. return false;
  1816. for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
  1817. Instruction *PBI = &*I;
  1818. // Check whether Inst and PBI generate the same value.
  1819. if (Inst->isIdenticalTo(PBI)) {
  1820. Inst->replaceAllUsesWith(PBI);
  1821. Inst->eraseFromParent();
  1822. return true;
  1823. }
  1824. }
  1825. return false;
  1826. }
  1827. /// If this basic block is simple enough, and if a predecessor branches to us
  1828. /// and one of our successors, fold the block into the predecessor and use
  1829. /// logical operations to pick the right destination.
  1830. bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
  1831. BasicBlock *BB = BI->getParent();
  1832. Instruction *Cond = nullptr;
  1833. if (BI->isConditional())
  1834. Cond = dyn_cast<Instruction>(BI->getCondition());
  1835. else {
  1836. // For unconditional branch, check for a simple CFG pattern, where
  1837. // BB has a single predecessor and BB's successor is also its predecessor's
  1838. // successor. If such pattern exisits, check for CSE between BB and its
  1839. // predecessor.
  1840. if (BasicBlock *PB = BB->getSinglePredecessor())
  1841. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  1842. if (PBI->isConditional() &&
  1843. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  1844. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  1845. for (BasicBlock::iterator I = BB->begin(), E = BB->end();
  1846. I != E; ) {
  1847. Instruction *Curr = I++;
  1848. if (isa<DbgInfoIntrinsic>(Curr)) continue; // HLSL Change - Ignore debug insts
  1849. if (isa<CmpInst>(Curr)) {
  1850. Cond = Curr;
  1851. break;
  1852. }
  1853. // Quit if we can't remove this instruction.
  1854. if (!checkCSEInPredecessor(Curr, PB))
  1855. return false;
  1856. }
  1857. }
  1858. if (!Cond)
  1859. return false;
  1860. }
  1861. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  1862. Cond->getParent() != BB || !Cond->hasOneUse())
  1863. return false;
  1864. // Make sure the instruction after the condition is the cond branch.
  1865. BasicBlock::iterator CondIt = Cond; ++CondIt;
  1866. // Ignore dbg intrinsics.
  1867. while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
  1868. if (&*CondIt != BI)
  1869. return false;
  1870. // Only allow this transformation if computing the condition doesn't involve
  1871. // too many instructions and these involved instructions can be executed
  1872. // unconditionally. We denote all involved instructions except the condition
  1873. // as "bonus instructions", and only allow this transformation when the
  1874. // number of the bonus instructions does not exceed a certain threshold.
  1875. unsigned NumBonusInsts = 0;
  1876. for (auto I = BB->begin(); Cond != I; ++I) {
  1877. // Ignore dbg intrinsics.
  1878. if (isa<DbgInfoIntrinsic>(I))
  1879. continue;
  1880. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
  1881. return false;
  1882. // I has only one use and can be executed unconditionally.
  1883. Instruction *User = dyn_cast<Instruction>(I->user_back());
  1884. if (User == nullptr || User->getParent() != BB)
  1885. return false;
  1886. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  1887. // to use any other instruction, User must be an instruction between next(I)
  1888. // and Cond.
  1889. ++NumBonusInsts;
  1890. // Early exits once we reach the limit.
  1891. if (NumBonusInsts > BonusInstThreshold)
  1892. return false;
  1893. }
  1894. // Cond is known to be a compare or binary operator. Check to make sure that
  1895. // neither operand is a potentially-trapping constant expression.
  1896. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  1897. if (CE->canTrap())
  1898. return false;
  1899. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  1900. if (CE->canTrap())
  1901. return false;
  1902. // Finally, don't infinitely unroll conditional loops.
  1903. BasicBlock *TrueDest = BI->getSuccessor(0);
  1904. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  1905. if (TrueDest == BB || FalseDest == BB)
  1906. return false;
  1907. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1908. BasicBlock *PredBlock = *PI;
  1909. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  1910. // Check that we have two conditional branches. If there is a PHI node in
  1911. // the common successor, verify that the same value flows in from both
  1912. // blocks.
  1913. SmallVector<PHINode*, 4> PHIs;
  1914. if (!PBI || PBI->isUnconditional() ||
  1915. (BI->isConditional() &&
  1916. !SafeToMergeTerminators(BI, PBI)) ||
  1917. (!BI->isConditional() &&
  1918. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  1919. continue;
  1920. // Determine if the two branches share a common destination.
  1921. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  1922. bool InvertPredCond = false;
  1923. if (BI->isConditional()) {
  1924. if (PBI->getSuccessor(0) == TrueDest)
  1925. Opc = Instruction::Or;
  1926. else if (PBI->getSuccessor(1) == FalseDest)
  1927. Opc = Instruction::And;
  1928. else if (PBI->getSuccessor(0) == FalseDest)
  1929. Opc = Instruction::And, InvertPredCond = true;
  1930. else if (PBI->getSuccessor(1) == TrueDest)
  1931. Opc = Instruction::Or, InvertPredCond = true;
  1932. else
  1933. continue;
  1934. } else {
  1935. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  1936. continue;
  1937. }
  1938. DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  1939. IRBuilder<> Builder(PBI);
  1940. // If we need to invert the condition in the pred block to match, do so now.
  1941. if (InvertPredCond) {
  1942. Value *NewCond = PBI->getCondition();
  1943. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  1944. CmpInst *CI = cast<CmpInst>(NewCond);
  1945. CI->setPredicate(CI->getInversePredicate());
  1946. } else {
  1947. NewCond = Builder.CreateNot(NewCond,
  1948. PBI->getCondition()->getName()+".not");
  1949. }
  1950. PBI->setCondition(NewCond);
  1951. PBI->swapSuccessors();
  1952. }
  1953. // If we have bonus instructions, clone them into the predecessor block.
  1954. // Note that there may be multiple predecessor blocks, so we cannot move
  1955. // bonus instructions to a predecessor block.
  1956. ValueToValueMapTy VMap; // maps original values to cloned values
  1957. // We already make sure Cond is the last instruction before BI. Therefore,
  1958. // all instructions before Cond other than DbgInfoIntrinsic are bonus
  1959. // instructions.
  1960. for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
  1961. if (isa<DbgInfoIntrinsic>(BonusInst))
  1962. continue;
  1963. Instruction *NewBonusInst = BonusInst->clone();
  1964. RemapInstruction(NewBonusInst, VMap,
  1965. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1966. VMap[BonusInst] = NewBonusInst;
  1967. // If we moved a load, we cannot any longer claim any knowledge about
  1968. // its potential value. The previous information might have been valid
  1969. // only given the branch precondition.
  1970. // For an analogous reason, we must also drop all the metadata whose
  1971. // semantics we don't understand.
  1972. NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
  1973. PredBlock->getInstList().insert(PBI, NewBonusInst);
  1974. NewBonusInst->takeName(BonusInst);
  1975. BonusInst->setName(BonusInst->getName() + ".old");
  1976. }
  1977. // Clone Cond into the predecessor basic block, and or/and the
  1978. // two conditions together.
  1979. Instruction *New = Cond->clone();
  1980. RemapInstruction(New, VMap,
  1981. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1982. PredBlock->getInstList().insert(PBI, New);
  1983. New->takeName(Cond);
  1984. Cond->setName(New->getName() + ".old");
  1985. if (BI->isConditional()) {
  1986. Instruction *NewCond =
  1987. cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
  1988. New, "or.cond"));
  1989. PBI->setCondition(NewCond);
  1990. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  1991. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  1992. PredFalseWeight);
  1993. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  1994. SuccFalseWeight);
  1995. SmallVector<uint64_t, 8> NewWeights;
  1996. if (PBI->getSuccessor(0) == BB) {
  1997. if (PredHasWeights && SuccHasWeights) {
  1998. // PBI: br i1 %x, BB, FalseDest
  1999. // BI: br i1 %y, TrueDest, FalseDest
  2000. //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  2001. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  2002. //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  2003. // TrueWeight for PBI * FalseWeight for BI.
  2004. // We assume that total weights of a BranchInst can fit into 32 bits.
  2005. // Therefore, we will not have overflow using 64-bit arithmetic.
  2006. NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
  2007. SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
  2008. }
  2009. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  2010. PBI->setSuccessor(0, TrueDest);
  2011. }
  2012. if (PBI->getSuccessor(1) == BB) {
  2013. if (PredHasWeights && SuccHasWeights) {
  2014. // PBI: br i1 %x, TrueDest, BB
  2015. // BI: br i1 %y, TrueDest, FalseDest
  2016. //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2017. // FalseWeight for PBI * TrueWeight for BI.
  2018. NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
  2019. SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
  2020. //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2021. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2022. }
  2023. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  2024. PBI->setSuccessor(1, FalseDest);
  2025. }
  2026. if (NewWeights.size() == 2) {
  2027. // Halve the weights if any of them cannot fit in an uint32_t
  2028. FitWeights(NewWeights);
  2029. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
  2030. PBI->setMetadata(LLVMContext::MD_prof,
  2031. MDBuilder(BI->getContext()).
  2032. createBranchWeights(MDWeights));
  2033. } else
  2034. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2035. } else {
  2036. // Update PHI nodes in the common successors.
  2037. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2038. ConstantInt *PBI_C = cast<ConstantInt>(
  2039. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2040. assert(PBI_C->getType()->isIntegerTy(1));
  2041. Instruction *MergedCond = nullptr;
  2042. if (PBI->getSuccessor(0) == TrueDest) {
  2043. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2044. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2045. // is false: !PBI_Cond and BI_Value
  2046. Instruction *NotCond =
  2047. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2048. "not.cond"));
  2049. MergedCond =
  2050. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2051. NotCond, New,
  2052. "and.cond"));
  2053. if (PBI_C->isOne())
  2054. MergedCond =
  2055. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2056. PBI->getCondition(), MergedCond,
  2057. "or.cond"));
  2058. } else {
  2059. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2060. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2061. // is false: PBI_Cond and BI_Value
  2062. MergedCond =
  2063. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2064. PBI->getCondition(), New,
  2065. "and.cond"));
  2066. if (PBI_C->isOne()) {
  2067. Instruction *NotCond =
  2068. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2069. "not.cond"));
  2070. MergedCond =
  2071. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2072. NotCond, MergedCond,
  2073. "or.cond"));
  2074. }
  2075. }
  2076. // Update PHI Node.
  2077. PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
  2078. MergedCond);
  2079. }
  2080. // Change PBI from Conditional to Unconditional.
  2081. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2082. EraseTerminatorInstAndDCECond(PBI);
  2083. PBI = New_PBI;
  2084. }
  2085. // TODO: If BB is reachable from all paths through PredBlock, then we
  2086. // could replace PBI's branch probabilities with BI's.
  2087. // Copy any debug value intrinsics into the end of PredBlock.
  2088. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  2089. if (isa<DbgInfoIntrinsic>(*I))
  2090. I->clone()->insertBefore(PBI);
  2091. return true;
  2092. }
  2093. return false;
  2094. }
  2095. /// If we have a conditional branch as a predecessor of another block,
  2096. /// this function tries to simplify it. We know
  2097. /// that PBI and BI are both conditional branches, and BI is in one of the
  2098. /// successor blocks of PBI - PBI branches to BI.
  2099. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
  2100. assert(PBI->isConditional() && BI->isConditional());
  2101. BasicBlock *BB = BI->getParent();
  2102. // If this block ends with a branch instruction, and if there is a
  2103. // predecessor that ends on a branch of the same condition, make
  2104. // this conditional branch redundant.
  2105. if (PBI->getCondition() == BI->getCondition() &&
  2106. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2107. // Okay, the outcome of this conditional branch is statically
  2108. // knowable. If this block had a single pred, handle specially.
  2109. if (BB->getSinglePredecessor()) {
  2110. // Turn this into a branch on constant.
  2111. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2112. BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2113. CondIsTrue));
  2114. return true; // Nuke the branch on constant.
  2115. }
  2116. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2117. // in the constant and simplify the block result. Subsequent passes of
  2118. // simplifycfg will thread the block.
  2119. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2120. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2121. PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
  2122. std::distance(PB, PE),
  2123. BI->getCondition()->getName() + ".pr",
  2124. BB->begin());
  2125. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2126. // predecessor, compute the PHI'd conditional value for all of the preds.
  2127. // Any predecessor where the condition is not computable we keep symbolic.
  2128. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2129. BasicBlock *P = *PI;
  2130. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
  2131. PBI != BI && PBI->isConditional() &&
  2132. PBI->getCondition() == BI->getCondition() &&
  2133. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2134. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2135. NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2136. CondIsTrue), P);
  2137. } else {
  2138. NewPN->addIncoming(BI->getCondition(), P);
  2139. }
  2140. }
  2141. BI->setCondition(NewPN);
  2142. return true;
  2143. }
  2144. }
  2145. // If this is a conditional branch in an empty block, and if any
  2146. // predecessors are a conditional branch to one of our destinations,
  2147. // fold the conditions into logical ops and one cond br.
  2148. BasicBlock::iterator BBI = BB->begin();
  2149. // Ignore dbg intrinsics.
  2150. while (isa<DbgInfoIntrinsic>(BBI))
  2151. ++BBI;
  2152. if (&*BBI != BI)
  2153. return false;
  2154. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2155. if (CE->canTrap())
  2156. return false;
  2157. int PBIOp, BIOp;
  2158. if (PBI->getSuccessor(0) == BI->getSuccessor(0))
  2159. PBIOp = BIOp = 0;
  2160. else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
  2161. PBIOp = 0, BIOp = 1;
  2162. else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
  2163. PBIOp = 1, BIOp = 0;
  2164. else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
  2165. PBIOp = BIOp = 1;
  2166. else
  2167. return false;
  2168. // Check to make sure that the other destination of this branch
  2169. // isn't BB itself. If so, this is an infinite loop that will
  2170. // keep getting unwound.
  2171. if (PBI->getSuccessor(PBIOp) == BB)
  2172. return false;
  2173. // Do not perform this transformation if it would require
  2174. // insertion of a large number of select instructions. For targets
  2175. // without predication/cmovs, this is a big pessimization.
  2176. // Also do not perform this transformation if any phi node in the common
  2177. // destination block can trap when reached by BB or PBB (PR17073). In that
  2178. // case, it would be unsafe to hoist the operation into a select instruction.
  2179. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2180. unsigned NumPhis = 0;
  2181. for (BasicBlock::iterator II = CommonDest->begin();
  2182. isa<PHINode>(II); ++II, ++NumPhis) {
  2183. if (NumPhis > 2) // Disable this xform.
  2184. return false;
  2185. PHINode *PN = cast<PHINode>(II);
  2186. Value *BIV = PN->getIncomingValueForBlock(BB);
  2187. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2188. if (CE->canTrap())
  2189. return false;
  2190. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2191. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2192. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2193. if (CE->canTrap())
  2194. return false;
  2195. }
  2196. // Finally, if everything is ok, fold the branches to logical ops.
  2197. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2198. DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2199. << "AND: " << *BI->getParent());
  2200. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2201. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2202. // exits. We don't *know* that the program avoids the infinite loop
  2203. // (even though that seems likely). If we do this xform naively, we'll end up
  2204. // recursively unpeeling the loop. Since we know that (after the xform is
  2205. // done) that the block *is* infinite if reached, we just make it an obviously
  2206. // infinite loop with no cond branch.
  2207. if (OtherDest == BB) {
  2208. // Insert it at the end of the function, because it's either code,
  2209. // or it won't matter if it's hot. :)
  2210. BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
  2211. "infloop", BB->getParent());
  2212. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2213. OtherDest = InfLoopBlock;
  2214. }
  2215. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2216. // BI may have other predecessors. Because of this, we leave
  2217. // it alone, but modify PBI.
  2218. // Make sure we get to CommonDest on True&True directions.
  2219. Value *PBICond = PBI->getCondition();
  2220. IRBuilder<true, NoFolder> Builder(PBI);
  2221. if (PBIOp)
  2222. PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
  2223. Value *BICond = BI->getCondition();
  2224. if (BIOp)
  2225. BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
  2226. // Merge the conditions.
  2227. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2228. // Modify PBI to branch on the new condition to the new dests.
  2229. PBI->setCondition(Cond);
  2230. PBI->setSuccessor(0, CommonDest);
  2231. PBI->setSuccessor(1, OtherDest);
  2232. // Update branch weight for PBI.
  2233. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2234. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  2235. PredFalseWeight);
  2236. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  2237. SuccFalseWeight);
  2238. if (PredHasWeights && SuccHasWeights) {
  2239. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2240. uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
  2241. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2242. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2243. // The weight to CommonDest should be PredCommon * SuccTotal +
  2244. // PredOther * SuccCommon.
  2245. // The weight to OtherDest should be PredOther * SuccOther.
  2246. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
  2247. PredOther * SuccCommon,
  2248. PredOther * SuccOther};
  2249. // Halve the weights if any of them cannot fit in an uint32_t
  2250. FitWeights(NewWeights);
  2251. PBI->setMetadata(LLVMContext::MD_prof,
  2252. MDBuilder(BI->getContext())
  2253. .createBranchWeights(NewWeights[0], NewWeights[1]));
  2254. }
  2255. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2256. // block that are identical to the entries for BI's block.
  2257. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2258. // We know that the CommonDest already had an edge from PBI to
  2259. // it. If it has PHIs though, the PHIs may have different
  2260. // entries for BB and PBI's BB. If so, insert a select to make
  2261. // them agree.
  2262. PHINode *PN;
  2263. for (BasicBlock::iterator II = CommonDest->begin();
  2264. (PN = dyn_cast<PHINode>(II)); ++II) {
  2265. Value *BIV = PN->getIncomingValueForBlock(BB);
  2266. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2267. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2268. if (BIV != PBIV) {
  2269. // Insert a select in PBI to pick the right value.
  2270. Value *NV = cast<SelectInst>
  2271. (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
  2272. PN->setIncomingValue(PBBIdx, NV);
  2273. }
  2274. }
  2275. DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  2276. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2277. // This basic block is probably dead. We know it has at least
  2278. // one fewer predecessor.
  2279. return true;
  2280. }
  2281. // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
  2282. // true or to FalseBB if Cond is false.
  2283. // Takes care of updating the successors and removing the old terminator.
  2284. // Also makes sure not to introduce new successors by assuming that edges to
  2285. // non-successor TrueBBs and FalseBBs aren't reachable.
  2286. static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
  2287. BasicBlock *TrueBB, BasicBlock *FalseBB,
  2288. uint32_t TrueWeight,
  2289. uint32_t FalseWeight){
  2290. // Remove any superfluous successor edges from the CFG.
  2291. // First, figure out which successors to preserve.
  2292. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  2293. // successor.
  2294. BasicBlock *KeepEdge1 = TrueBB;
  2295. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  2296. // Then remove the rest.
  2297. for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
  2298. BasicBlock *Succ = OldTerm->getSuccessor(I);
  2299. // Make sure only to keep exactly one copy of each edge.
  2300. if (Succ == KeepEdge1)
  2301. KeepEdge1 = nullptr;
  2302. else if (Succ == KeepEdge2)
  2303. KeepEdge2 = nullptr;
  2304. else
  2305. Succ->removePredecessor(OldTerm->getParent());
  2306. }
  2307. IRBuilder<> Builder(OldTerm);
  2308. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  2309. // Insert an appropriate new terminator.
  2310. if (!KeepEdge1 && !KeepEdge2) {
  2311. if (TrueBB == FalseBB)
  2312. // We were only looking for one successor, and it was present.
  2313. // Create an unconditional branch to it.
  2314. Builder.CreateBr(TrueBB);
  2315. else {
  2316. // We found both of the successors we were looking for.
  2317. // Create a conditional branch sharing the condition of the select.
  2318. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  2319. if (TrueWeight != FalseWeight)
  2320. NewBI->setMetadata(LLVMContext::MD_prof,
  2321. MDBuilder(OldTerm->getContext()).
  2322. createBranchWeights(TrueWeight, FalseWeight));
  2323. }
  2324. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  2325. // Neither of the selected blocks were successors, so this
  2326. // terminator must be unreachable.
  2327. new UnreachableInst(OldTerm->getContext(), OldTerm);
  2328. } else {
  2329. // One of the selected values was a successor, but the other wasn't.
  2330. // Insert an unconditional branch to the one that was found;
  2331. // the edge to the one that wasn't must be unreachable.
  2332. if (!KeepEdge1)
  2333. // Only TrueBB was found.
  2334. Builder.CreateBr(TrueBB);
  2335. else
  2336. // Only FalseBB was found.
  2337. Builder.CreateBr(FalseBB);
  2338. }
  2339. EraseTerminatorInstAndDCECond(OldTerm);
  2340. return true;
  2341. }
  2342. // Replaces
  2343. // (switch (select cond, X, Y)) on constant X, Y
  2344. // with a branch - conditional if X and Y lead to distinct BBs,
  2345. // unconditional otherwise.
  2346. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  2347. // Check for constant integer values in the select.
  2348. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  2349. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  2350. if (!TrueVal || !FalseVal)
  2351. return false;
  2352. // Find the relevant condition and destinations.
  2353. Value *Condition = Select->getCondition();
  2354. BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
  2355. BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
  2356. // Get weight for TrueBB and FalseBB.
  2357. uint32_t TrueWeight = 0, FalseWeight = 0;
  2358. SmallVector<uint64_t, 8> Weights;
  2359. bool HasWeights = HasBranchWeights(SI);
  2360. if (HasWeights) {
  2361. GetBranchWeights(SI, Weights);
  2362. if (Weights.size() == 1 + SI->getNumCases()) {
  2363. TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
  2364. getSuccessorIndex()];
  2365. FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
  2366. getSuccessorIndex()];
  2367. }
  2368. }
  2369. // Perform the actual simplification.
  2370. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
  2371. TrueWeight, FalseWeight);
  2372. }
  2373. // Replaces
  2374. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  2375. // blockaddress(@fn, BlockB)))
  2376. // with
  2377. // (br cond, BlockA, BlockB).
  2378. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  2379. // Check that both operands of the select are block addresses.
  2380. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  2381. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  2382. if (!TBA || !FBA)
  2383. return false;
  2384. // Extract the actual blocks.
  2385. BasicBlock *TrueBB = TBA->getBasicBlock();
  2386. BasicBlock *FalseBB = FBA->getBasicBlock();
  2387. // Perform the actual simplification.
  2388. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
  2389. 0, 0);
  2390. }
  2391. /// This is called when we find an icmp instruction
  2392. /// (a seteq/setne with a constant) as the only instruction in a
  2393. /// block that ends with an uncond branch. We are looking for a very specific
  2394. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  2395. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  2396. /// default value goes to an uncond block with a seteq in it, we get something
  2397. /// like:
  2398. ///
  2399. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  2400. /// DEFAULT:
  2401. /// %tmp = icmp eq i8 %A, 92
  2402. /// br label %end
  2403. /// end:
  2404. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  2405. ///
  2406. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  2407. /// the PHI, merging the third icmp into the switch.
  2408. static bool TryToSimplifyUncondBranchWithICmpInIt(
  2409. ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
  2410. const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
  2411. AssumptionCache *AC) {
  2412. BasicBlock *BB = ICI->getParent();
  2413. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  2414. // complex.
  2415. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
  2416. Value *V = ICI->getOperand(0);
  2417. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  2418. // The pattern we're looking for is where our only predecessor is a switch on
  2419. // 'V' and this block is the default case for the switch. In this case we can
  2420. // fold the compared value into the switch to simplify things.
  2421. BasicBlock *Pred = BB->getSinglePredecessor();
  2422. if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
  2423. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  2424. if (SI->getCondition() != V)
  2425. return false;
  2426. // If BB is reachable on a non-default case, then we simply know the value of
  2427. // V in this block. Substitute it and constant fold the icmp instruction
  2428. // away.
  2429. if (SI->getDefaultDest() != BB) {
  2430. ConstantInt *VVal = SI->findCaseDest(BB);
  2431. assert(VVal && "Should have a unique destination value");
  2432. ICI->setOperand(0, VVal);
  2433. if (Value *V = SimplifyInstruction(ICI, DL)) {
  2434. ICI->replaceAllUsesWith(V);
  2435. ICI->eraseFromParent();
  2436. }
  2437. // BB is now empty, so it is likely to simplify away.
  2438. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  2439. }
  2440. // Ok, the block is reachable from the default dest. If the constant we're
  2441. // comparing exists in one of the other edges, then we can constant fold ICI
  2442. // and zap it.
  2443. if (SI->findCaseValue(Cst) != SI->case_default()) {
  2444. Value *V;
  2445. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2446. V = ConstantInt::getFalse(BB->getContext());
  2447. else
  2448. V = ConstantInt::getTrue(BB->getContext());
  2449. ICI->replaceAllUsesWith(V);
  2450. ICI->eraseFromParent();
  2451. // BB is now empty, so it is likely to simplify away.
  2452. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  2453. }
  2454. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  2455. // the block.
  2456. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  2457. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  2458. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  2459. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  2460. return false;
  2461. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  2462. // true in the PHI.
  2463. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  2464. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  2465. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2466. std::swap(DefaultCst, NewCst);
  2467. // Replace ICI (which is used by the PHI for the default value) with true or
  2468. // false depending on if it is EQ or NE.
  2469. ICI->replaceAllUsesWith(DefaultCst);
  2470. ICI->eraseFromParent();
  2471. // Okay, the switch goes to this block on a default value. Add an edge from
  2472. // the switch to the merge point on the compared value.
  2473. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
  2474. BB->getParent(), BB);
  2475. SmallVector<uint64_t, 8> Weights;
  2476. bool HasWeights = HasBranchWeights(SI);
  2477. if (HasWeights) {
  2478. GetBranchWeights(SI, Weights);
  2479. if (Weights.size() == 1 + SI->getNumCases()) {
  2480. // Split weight for default case to case for "Cst".
  2481. Weights[0] = (Weights[0]+1) >> 1;
  2482. Weights.push_back(Weights[0]);
  2483. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2484. SI->setMetadata(LLVMContext::MD_prof,
  2485. MDBuilder(SI->getContext()).
  2486. createBranchWeights(MDWeights));
  2487. }
  2488. }
  2489. SI->addCase(Cst, NewBB);
  2490. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  2491. Builder.SetInsertPoint(NewBB);
  2492. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  2493. Builder.CreateBr(SuccBlock);
  2494. PHIUse->addIncoming(NewCst, NewBB);
  2495. return true;
  2496. }
  2497. #if 0 // HLSL Change Begins. This will not help for hlsl.
  2498. /// The specified branch is a conditional branch.
  2499. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  2500. /// fold it into a switch instruction if so.
  2501. static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
  2502. const DataLayout &DL) {
  2503. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  2504. if (!Cond) return false;
  2505. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  2506. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  2507. // 'setne's and'ed together, collect them.
  2508. // Try to gather values from a chain of and/or to be turned into a switch
  2509. ConstantComparesGatherer ConstantCompare(Cond, DL);
  2510. // Unpack the result
  2511. SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
  2512. Value *CompVal = ConstantCompare.CompValue;
  2513. unsigned UsedICmps = ConstantCompare.UsedICmps;
  2514. Value *ExtraCase = ConstantCompare.Extra;
  2515. // If we didn't have a multiply compared value, fail.
  2516. if (!CompVal) return false;
  2517. // Avoid turning single icmps into a switch.
  2518. if (UsedICmps <= 1)
  2519. return false;
  2520. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  2521. // There might be duplicate constants in the list, which the switch
  2522. // instruction can't handle, remove them now.
  2523. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  2524. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  2525. // If Extra was used, we require at least two switch values to do the
  2526. // transformation. A switch with one value is just an cond branch.
  2527. if (ExtraCase && Values.size() < 2) return false;
  2528. // TODO: Preserve branch weight metadata, similarly to how
  2529. // FoldValueComparisonIntoPredecessors preserves it.
  2530. // Figure out which block is which destination.
  2531. BasicBlock *DefaultBB = BI->getSuccessor(1);
  2532. BasicBlock *EdgeBB = BI->getSuccessor(0);
  2533. if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
  2534. BasicBlock *BB = BI->getParent();
  2535. DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  2536. << " cases into SWITCH. BB is:\n" << *BB);
  2537. // If there are any extra values that couldn't be folded into the switch
  2538. // then we evaluate them with an explicit branch first. Split the block
  2539. // right before the condbr to handle it.
  2540. if (ExtraCase) {
  2541. BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
  2542. // Remove the uncond branch added to the old block.
  2543. TerminatorInst *OldTI = BB->getTerminator();
  2544. Builder.SetInsertPoint(OldTI);
  2545. if (TrueWhenEqual)
  2546. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  2547. else
  2548. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  2549. OldTI->eraseFromParent();
  2550. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  2551. // for the edge we just added.
  2552. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  2553. DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  2554. << "\nEXTRABB = " << *BB);
  2555. BB = NewBB;
  2556. }
  2557. Builder.SetInsertPoint(BI);
  2558. // Convert pointer to int before we switch.
  2559. if (CompVal->getType()->isPointerTy()) {
  2560. CompVal = Builder.CreatePtrToInt(
  2561. CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
  2562. }
  2563. // Create the new switch instruction now.
  2564. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  2565. // Add all of the 'cases' to the switch instruction.
  2566. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  2567. New->addCase(Values[i], EdgeBB);
  2568. // We added edges from PI to the EdgeBB. As such, if there were any
  2569. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  2570. // the number of edges added.
  2571. for (BasicBlock::iterator BBI = EdgeBB->begin();
  2572. isa<PHINode>(BBI); ++BBI) {
  2573. PHINode *PN = cast<PHINode>(BBI);
  2574. Value *InVal = PN->getIncomingValueForBlock(BB);
  2575. for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
  2576. PN->addIncoming(InVal, BB);
  2577. }
  2578. // Erase the old branch instruction.
  2579. EraseTerminatorInstAndDCECond(BI);
  2580. DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  2581. return true;
  2582. }
  2583. #endif // HLSL Change Ends
  2584. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  2585. // If this is a trivial landing pad that just continues unwinding the caught
  2586. // exception then zap the landing pad, turning its invokes into calls.
  2587. BasicBlock *BB = RI->getParent();
  2588. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  2589. if (RI->getValue() != LPInst)
  2590. // Not a landing pad, or the resume is not unwinding the exception that
  2591. // caused control to branch here.
  2592. return false;
  2593. // Check that there are no other instructions except for debug intrinsics.
  2594. BasicBlock::iterator I = LPInst, E = RI;
  2595. while (++I != E)
  2596. if (!isa<DbgInfoIntrinsic>(I))
  2597. return false;
  2598. // Turn all invokes that unwind here into calls and delete the basic block.
  2599. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  2600. InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
  2601. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  2602. // Insert a call instruction before the invoke.
  2603. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  2604. Call->takeName(II);
  2605. Call->setCallingConv(II->getCallingConv());
  2606. Call->setAttributes(II->getAttributes());
  2607. Call->setDebugLoc(II->getDebugLoc());
  2608. // Anything that used the value produced by the invoke instruction now uses
  2609. // the value produced by the call instruction. Note that we do this even
  2610. // for void functions and calls with no uses so that the callgraph edge is
  2611. // updated.
  2612. II->replaceAllUsesWith(Call);
  2613. BB->removePredecessor(II->getParent());
  2614. // Insert a branch to the normal destination right before the invoke.
  2615. BranchInst::Create(II->getNormalDest(), II);
  2616. // Finally, delete the invoke instruction!
  2617. II->eraseFromParent();
  2618. }
  2619. // The landingpad is now unreachable. Zap it.
  2620. BB->eraseFromParent();
  2621. return true;
  2622. }
  2623. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  2624. BasicBlock *BB = RI->getParent();
  2625. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  2626. // Find predecessors that end with branches.
  2627. SmallVector<BasicBlock*, 8> UncondBranchPreds;
  2628. SmallVector<BranchInst*, 8> CondBranchPreds;
  2629. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2630. BasicBlock *P = *PI;
  2631. TerminatorInst *PTI = P->getTerminator();
  2632. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  2633. if (BI->isUnconditional())
  2634. UncondBranchPreds.push_back(P);
  2635. else
  2636. CondBranchPreds.push_back(BI);
  2637. }
  2638. }
  2639. // If we found some, do the transformation!
  2640. if (!UncondBranchPreds.empty() && DupRet) {
  2641. while (!UncondBranchPreds.empty()) {
  2642. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  2643. DEBUG(dbgs() << "FOLDING: " << *BB
  2644. << "INTO UNCOND BRANCH PRED: " << *Pred);
  2645. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  2646. }
  2647. // If we eliminated all predecessors of the block, delete the block now.
  2648. if (pred_empty(BB))
  2649. // We know there are no successors, so just nuke the block.
  2650. BB->eraseFromParent();
  2651. return true;
  2652. }
  2653. // Check out all of the conditional branches going to this return
  2654. // instruction. If any of them just select between returns, change the
  2655. // branch itself into a select/return pair.
  2656. while (!CondBranchPreds.empty()) {
  2657. BranchInst *BI = CondBranchPreds.pop_back_val();
  2658. // Check to see if the non-BB successor is also a return block.
  2659. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  2660. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  2661. SimplifyCondBranchToTwoReturns(BI, Builder))
  2662. return true;
  2663. }
  2664. return false;
  2665. }
  2666. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  2667. BasicBlock *BB = UI->getParent();
  2668. bool Changed = false;
  2669. // If there are any instructions immediately before the unreachable that can
  2670. // be removed, do so.
  2671. while (UI != BB->begin()) {
  2672. BasicBlock::iterator BBI = UI;
  2673. --BBI;
  2674. // Do not delete instructions that can have side effects which might cause
  2675. // the unreachable to not be reachable; specifically, calls and volatile
  2676. // operations may have this effect.
  2677. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
  2678. if (BBI->mayHaveSideEffects()) {
  2679. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  2680. if (SI->isVolatile())
  2681. break;
  2682. } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  2683. if (LI->isVolatile())
  2684. break;
  2685. } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  2686. if (RMWI->isVolatile())
  2687. break;
  2688. } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  2689. if (CXI->isVolatile())
  2690. break;
  2691. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  2692. !isa<LandingPadInst>(BBI)) {
  2693. break;
  2694. }
  2695. // Note that deleting LandingPad's here is in fact okay, although it
  2696. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  2697. // all the predecessors of this block will be the unwind edges of Invokes,
  2698. // and we can therefore guarantee this block will be erased.
  2699. }
  2700. // Delete this instruction (any uses are guaranteed to be dead)
  2701. if (!BBI->use_empty())
  2702. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  2703. BBI->eraseFromParent();
  2704. Changed = true;
  2705. }
  2706. // If the unreachable instruction is the first in the block, take a gander
  2707. // at all of the predecessors of this instruction, and simplify them.
  2708. if (&BB->front() != UI) return Changed;
  2709. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  2710. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  2711. TerminatorInst *TI = Preds[i]->getTerminator();
  2712. IRBuilder<> Builder(TI);
  2713. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2714. if (BI->isUnconditional()) {
  2715. if (BI->getSuccessor(0) == BB) {
  2716. new UnreachableInst(TI->getContext(), TI);
  2717. TI->eraseFromParent();
  2718. Changed = true;
  2719. }
  2720. } else {
  2721. if (BI->getSuccessor(0) == BB) {
  2722. Builder.CreateBr(BI->getSuccessor(1));
  2723. EraseTerminatorInstAndDCECond(BI);
  2724. } else if (BI->getSuccessor(1) == BB) {
  2725. Builder.CreateBr(BI->getSuccessor(0));
  2726. EraseTerminatorInstAndDCECond(BI);
  2727. Changed = true;
  2728. }
  2729. }
  2730. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2731. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2732. i != e; ++i)
  2733. if (i.getCaseSuccessor() == BB) {
  2734. BB->removePredecessor(SI->getParent());
  2735. SI->removeCase(i);
  2736. --i; --e;
  2737. Changed = true;
  2738. }
  2739. } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
  2740. if (II->getUnwindDest() == BB) {
  2741. // Convert the invoke to a call instruction. This would be a good
  2742. // place to note that the call does not throw though.
  2743. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2744. II->removeFromParent(); // Take out of symbol table
  2745. // Insert the call now...
  2746. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
  2747. Builder.SetInsertPoint(BI);
  2748. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2749. Args, II->getName());
  2750. CI->setCallingConv(II->getCallingConv());
  2751. CI->setAttributes(II->getAttributes());
  2752. // If the invoke produced a value, the call does now instead.
  2753. II->replaceAllUsesWith(CI);
  2754. delete II;
  2755. Changed = true;
  2756. }
  2757. }
  2758. }
  2759. // If this block is now dead, remove it.
  2760. if (pred_empty(BB) &&
  2761. BB != &BB->getParent()->getEntryBlock()) {
  2762. // We know there are no successors, so just nuke the block.
  2763. BB->eraseFromParent();
  2764. return true;
  2765. }
  2766. return Changed;
  2767. }
  2768. static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
  2769. assert(Cases.size() >= 1);
  2770. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  2771. for (size_t I = 1, E = Cases.size(); I != E; ++I) {
  2772. if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
  2773. return false;
  2774. }
  2775. return true;
  2776. }
  2777. /// Turn a switch with two reachable destinations into an integer range
  2778. /// comparison and branch.
  2779. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  2780. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  2781. bool HasDefault =
  2782. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  2783. // Partition the cases into two sets with different destinations.
  2784. BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
  2785. BasicBlock *DestB = nullptr;
  2786. SmallVector <ConstantInt *, 16> CasesA;
  2787. SmallVector <ConstantInt *, 16> CasesB;
  2788. for (SwitchInst::CaseIt I : SI->cases()) {
  2789. BasicBlock *Dest = I.getCaseSuccessor();
  2790. if (!DestA) DestA = Dest;
  2791. if (Dest == DestA) {
  2792. CasesA.push_back(I.getCaseValue());
  2793. continue;
  2794. }
  2795. if (!DestB) DestB = Dest;
  2796. if (Dest == DestB) {
  2797. CasesB.push_back(I.getCaseValue());
  2798. continue;
  2799. }
  2800. return false; // More than two destinations.
  2801. }
  2802. assert(DestA && DestB && "Single-destination switch should have been folded.");
  2803. assert(DestA != DestB);
  2804. assert(DestB != SI->getDefaultDest());
  2805. assert(!CasesB.empty() && "There must be non-default cases.");
  2806. assert(!CasesA.empty() || HasDefault);
  2807. // Figure out if one of the sets of cases form a contiguous range.
  2808. SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
  2809. BasicBlock *ContiguousDest = nullptr;
  2810. BasicBlock *OtherDest = nullptr;
  2811. if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
  2812. ContiguousCases = &CasesA;
  2813. ContiguousDest = DestA;
  2814. OtherDest = DestB;
  2815. } else if (CasesAreContiguous(CasesB)) {
  2816. ContiguousCases = &CasesB;
  2817. ContiguousDest = DestB;
  2818. OtherDest = DestA;
  2819. } else
  2820. return false;
  2821. // Start building the compare and branch.
  2822. Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
  2823. Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
  2824. Value *Sub = SI->getCondition();
  2825. if (!Offset->isNullValue())
  2826. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
  2827. Value *Cmp;
  2828. // If NumCases overflowed, then all possible values jump to the successor.
  2829. if (NumCases->isNullValue() && !ContiguousCases->empty())
  2830. Cmp = ConstantInt::getTrue(SI->getContext());
  2831. else
  2832. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  2833. BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
  2834. // Update weight for the newly-created conditional branch.
  2835. if (HasBranchWeights(SI)) {
  2836. SmallVector<uint64_t, 8> Weights;
  2837. GetBranchWeights(SI, Weights);
  2838. if (Weights.size() == 1 + SI->getNumCases()) {
  2839. uint64_t TrueWeight = 0;
  2840. uint64_t FalseWeight = 0;
  2841. for (size_t I = 0, E = Weights.size(); I != E; ++I) {
  2842. if (SI->getSuccessor(I) == ContiguousDest)
  2843. TrueWeight += Weights[I];
  2844. else
  2845. FalseWeight += Weights[I];
  2846. }
  2847. while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
  2848. TrueWeight /= 2;
  2849. FalseWeight /= 2;
  2850. }
  2851. NewBI->setMetadata(LLVMContext::MD_prof,
  2852. MDBuilder(SI->getContext()).createBranchWeights(
  2853. (uint32_t)TrueWeight, (uint32_t)FalseWeight));
  2854. }
  2855. }
  2856. // Prune obsolete incoming values off the successors' PHI nodes.
  2857. for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
  2858. unsigned PreviousEdges = ContiguousCases->size();
  2859. if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
  2860. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  2861. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2862. }
  2863. for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
  2864. unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
  2865. if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
  2866. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  2867. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2868. }
  2869. // Drop the switch.
  2870. SI->eraseFromParent();
  2871. return true;
  2872. }
  2873. /// Compute masked bits for the condition of a switch
  2874. /// and use it to remove dead cases.
  2875. static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
  2876. const DataLayout &DL) {
  2877. Value *Cond = SI->getCondition();
  2878. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  2879. APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
  2880. computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
  2881. // Gather dead cases.
  2882. SmallVector<ConstantInt*, 8> DeadCases;
  2883. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2884. if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
  2885. (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
  2886. DeadCases.push_back(I.getCaseValue());
  2887. DEBUG(dbgs() << "SimplifyCFG: switch case '"
  2888. << I.getCaseValue() << "' is dead.\n");
  2889. }
  2890. }
  2891. SmallVector<uint64_t, 8> Weights;
  2892. bool HasWeight = HasBranchWeights(SI);
  2893. if (HasWeight) {
  2894. GetBranchWeights(SI, Weights);
  2895. HasWeight = (Weights.size() == 1 + SI->getNumCases());
  2896. }
  2897. // Remove dead cases from the switch.
  2898. for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
  2899. SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
  2900. assert(Case != SI->case_default() &&
  2901. "Case was not found. Probably mistake in DeadCases forming.");
  2902. if (HasWeight) {
  2903. std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
  2904. Weights.pop_back();
  2905. }
  2906. // Prune unused values from PHI nodes.
  2907. Case.getCaseSuccessor()->removePredecessor(SI->getParent());
  2908. SI->removeCase(Case);
  2909. }
  2910. if (HasWeight && Weights.size() >= 2) {
  2911. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2912. SI->setMetadata(LLVMContext::MD_prof,
  2913. MDBuilder(SI->getParent()->getContext()).
  2914. createBranchWeights(MDWeights));
  2915. }
  2916. return !DeadCases.empty();
  2917. }
  2918. /// If BB would be eligible for simplification by
  2919. /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  2920. /// by an unconditional branch), look at the phi node for BB in the successor
  2921. /// block and see if the incoming value is equal to CaseValue. If so, return
  2922. /// the phi node, and set PhiIndex to BB's index in the phi node.
  2923. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  2924. BasicBlock *BB,
  2925. int *PhiIndex) {
  2926. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  2927. return nullptr; // BB must be empty to be a candidate for simplification.
  2928. if (!BB->getSinglePredecessor())
  2929. return nullptr; // BB must be dominated by the switch.
  2930. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  2931. if (!Branch || !Branch->isUnconditional())
  2932. return nullptr; // Terminator must be unconditional branch.
  2933. BasicBlock *Succ = Branch->getSuccessor(0);
  2934. BasicBlock::iterator I = Succ->begin();
  2935. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  2936. int Idx = PHI->getBasicBlockIndex(BB);
  2937. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  2938. Value *InValue = PHI->getIncomingValue(Idx);
  2939. if (InValue != CaseValue) continue;
  2940. *PhiIndex = Idx;
  2941. return PHI;
  2942. }
  2943. return nullptr;
  2944. }
  2945. /// Try to forward the condition of a switch instruction to a phi node
  2946. /// dominated by the switch, if that would mean that some of the destination
  2947. /// blocks of the switch can be folded away.
  2948. /// Returns true if a change is made.
  2949. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  2950. typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
  2951. ForwardingNodesMap ForwardingNodes;
  2952. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2953. ConstantInt *CaseValue = I.getCaseValue();
  2954. BasicBlock *CaseDest = I.getCaseSuccessor();
  2955. int PhiIndex;
  2956. PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
  2957. &PhiIndex);
  2958. if (!PHI) continue;
  2959. ForwardingNodes[PHI].push_back(PhiIndex);
  2960. }
  2961. bool Changed = false;
  2962. for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
  2963. E = ForwardingNodes.end(); I != E; ++I) {
  2964. PHINode *Phi = I->first;
  2965. SmallVectorImpl<int> &Indexes = I->second;
  2966. if (Indexes.size() < 2) continue;
  2967. for (size_t I = 0, E = Indexes.size(); I != E; ++I)
  2968. Phi->setIncomingValue(Indexes[I], SI->getCondition());
  2969. Changed = true;
  2970. }
  2971. return Changed;
  2972. }
  2973. /// Return true if the backend will be able to handle
  2974. /// initializing an array of constants like C.
  2975. static bool ValidLookupTableConstant(Constant *C) {
  2976. if (C->isThreadDependent())
  2977. return false;
  2978. if (C->isDLLImportDependent())
  2979. return false;
  2980. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
  2981. return CE->isGEPWithNoNotionalOverIndexing();
  2982. return isa<ConstantFP>(C) ||
  2983. isa<ConstantInt>(C) ||
  2984. isa<ConstantPointerNull>(C) ||
  2985. isa<GlobalValue>(C) ||
  2986. isa<UndefValue>(C);
  2987. }
  2988. /// If V is a Constant, return it. Otherwise, try to look up
  2989. /// its constant value in ConstantPool, returning 0 if it's not there.
  2990. static Constant *LookupConstant(Value *V,
  2991. const SmallDenseMap<Value*, Constant*>& ConstantPool) {
  2992. if (Constant *C = dyn_cast<Constant>(V))
  2993. return C;
  2994. return ConstantPool.lookup(V);
  2995. }
  2996. /// Try to fold instruction I into a constant. This works for
  2997. /// simple instructions such as binary operations where both operands are
  2998. /// constant or can be replaced by constants from the ConstantPool. Returns the
  2999. /// resulting constant on success, 0 otherwise.
  3000. static Constant *
  3001. ConstantFold(Instruction *I, const DataLayout &DL,
  3002. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  3003. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  3004. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  3005. if (!A)
  3006. return nullptr;
  3007. if (A->isAllOnesValue())
  3008. return LookupConstant(Select->getTrueValue(), ConstantPool);
  3009. if (A->isNullValue())
  3010. return LookupConstant(Select->getFalseValue(), ConstantPool);
  3011. return nullptr;
  3012. }
  3013. SmallVector<Constant *, 4> COps;
  3014. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  3015. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  3016. COps.push_back(A);
  3017. else
  3018. return nullptr;
  3019. }
  3020. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  3021. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  3022. COps[1], DL);
  3023. }
  3024. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
  3025. }
  3026. /// Try to determine the resulting constant values in phi nodes
  3027. /// at the common destination basic block, *CommonDest, for one of the case
  3028. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  3029. /// case), of a switch instruction SI.
  3030. static bool
  3031. GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
  3032. BasicBlock **CommonDest,
  3033. SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
  3034. const DataLayout &DL) {
  3035. // The block from which we enter the common destination.
  3036. BasicBlock *Pred = SI->getParent();
  3037. // If CaseDest is empty except for some side-effect free instructions through
  3038. // which we can constant-propagate the CaseVal, continue to its successor.
  3039. SmallDenseMap<Value*, Constant*> ConstantPool;
  3040. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  3041. for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
  3042. ++I) {
  3043. if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
  3044. // If the terminator is a simple branch, continue to the next block.
  3045. if (T->getNumSuccessors() != 1)
  3046. return false;
  3047. Pred = CaseDest;
  3048. CaseDest = T->getSuccessor(0);
  3049. } else if (isa<DbgInfoIntrinsic>(I)) {
  3050. // Skip debug intrinsic.
  3051. continue;
  3052. } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) {
  3053. // Instruction is side-effect free and constant.
  3054. // If the instruction has uses outside this block or a phi node slot for
  3055. // the block, it is not safe to bypass the instruction since it would then
  3056. // no longer dominate all its uses.
  3057. for (auto &Use : I->uses()) {
  3058. User *User = Use.getUser();
  3059. if (Instruction *I = dyn_cast<Instruction>(User))
  3060. if (I->getParent() == CaseDest)
  3061. continue;
  3062. if (PHINode *Phi = dyn_cast<PHINode>(User))
  3063. if (Phi->getIncomingBlock(Use) == CaseDest)
  3064. continue;
  3065. return false;
  3066. }
  3067. ConstantPool.insert(std::make_pair(I, C));
  3068. } else {
  3069. break;
  3070. }
  3071. }
  3072. // If we did not have a CommonDest before, use the current one.
  3073. if (!*CommonDest)
  3074. *CommonDest = CaseDest;
  3075. // If the destination isn't the common one, abort.
  3076. if (CaseDest != *CommonDest)
  3077. return false;
  3078. // Get the values for this case from phi nodes in the destination block.
  3079. BasicBlock::iterator I = (*CommonDest)->begin();
  3080. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  3081. int Idx = PHI->getBasicBlockIndex(Pred);
  3082. if (Idx == -1)
  3083. continue;
  3084. Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
  3085. ConstantPool);
  3086. if (!ConstVal)
  3087. return false;
  3088. // Be conservative about which kinds of constants we support.
  3089. if (!ValidLookupTableConstant(ConstVal))
  3090. return false;
  3091. Res.push_back(std::make_pair(PHI, ConstVal));
  3092. }
  3093. return Res.size() > 0;
  3094. }
  3095. // Helper function used to add CaseVal to the list of cases that generate
  3096. // Result.
  3097. static void MapCaseToResult(ConstantInt *CaseVal,
  3098. SwitchCaseResultVectorTy &UniqueResults,
  3099. Constant *Result) {
  3100. for (auto &I : UniqueResults) {
  3101. if (I.first == Result) {
  3102. I.second.push_back(CaseVal);
  3103. return;
  3104. }
  3105. }
  3106. UniqueResults.push_back(std::make_pair(Result,
  3107. SmallVector<ConstantInt*, 4>(1, CaseVal)));
  3108. }
  3109. // Helper function that initializes a map containing
  3110. // results for the PHI node of the common destination block for a switch
  3111. // instruction. Returns false if multiple PHI nodes have been found or if
  3112. // there is not a common destination block for the switch.
  3113. static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
  3114. BasicBlock *&CommonDest,
  3115. SwitchCaseResultVectorTy &UniqueResults,
  3116. Constant *&DefaultResult,
  3117. const DataLayout &DL) {
  3118. for (auto &I : SI->cases()) {
  3119. ConstantInt *CaseVal = I.getCaseValue();
  3120. // Resulting value at phi nodes for this case value.
  3121. SwitchCaseResultsTy Results;
  3122. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  3123. DL))
  3124. return false;
  3125. // Only one value per case is permitted
  3126. if (Results.size() > 1)
  3127. return false;
  3128. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  3129. // Check the PHI consistency.
  3130. if (!PHI)
  3131. PHI = Results[0].first;
  3132. else if (PHI != Results[0].first)
  3133. return false;
  3134. }
  3135. // Find the default result value.
  3136. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  3137. BasicBlock *DefaultDest = SI->getDefaultDest();
  3138. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  3139. DL);
  3140. // If the default value is not found abort unless the default destination
  3141. // is unreachable.
  3142. DefaultResult =
  3143. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  3144. if ((!DefaultResult &&
  3145. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  3146. return false;
  3147. return true;
  3148. }
  3149. // Helper function that checks if it is possible to transform a switch with only
  3150. // two cases (or two cases + default) that produces a result into a select.
  3151. // Example:
  3152. // switch (a) {
  3153. // case 10: %0 = icmp eq i32 %a, 10
  3154. // return 10; %1 = select i1 %0, i32 10, i32 4
  3155. // case 20: ----> %2 = icmp eq i32 %a, 20
  3156. // return 2; %3 = select i1 %2, i32 2, i32 %1
  3157. // default:
  3158. // return 4;
  3159. // }
  3160. static Value *
  3161. ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  3162. Constant *DefaultResult, Value *Condition,
  3163. IRBuilder<> &Builder) {
  3164. assert(ResultVector.size() == 2 &&
  3165. "We should have exactly two unique results at this point");
  3166. // If we are selecting between only two cases transform into a simple
  3167. // select or a two-way select if default is possible.
  3168. if (ResultVector[0].second.size() == 1 &&
  3169. ResultVector[1].second.size() == 1) {
  3170. ConstantInt *const FirstCase = ResultVector[0].second[0];
  3171. ConstantInt *const SecondCase = ResultVector[1].second[0];
  3172. bool DefaultCanTrigger = DefaultResult;
  3173. Value *SelectValue = ResultVector[1].first;
  3174. if (DefaultCanTrigger) {
  3175. Value *const ValueCompare =
  3176. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  3177. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  3178. DefaultResult, "switch.select");
  3179. }
  3180. Value *const ValueCompare =
  3181. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  3182. return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
  3183. "switch.select");
  3184. }
  3185. return nullptr;
  3186. }
  3187. // Helper function to cleanup a switch instruction that has been converted into
  3188. // a select, fixing up PHI nodes and basic blocks.
  3189. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  3190. Value *SelectValue,
  3191. IRBuilder<> &Builder) {
  3192. BasicBlock *SelectBB = SI->getParent();
  3193. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  3194. PHI->removeIncomingValue(SelectBB);
  3195. PHI->addIncoming(SelectValue, SelectBB);
  3196. Builder.CreateBr(PHI->getParent());
  3197. // Remove the switch.
  3198. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3199. BasicBlock *Succ = SI->getSuccessor(i);
  3200. if (Succ == PHI->getParent())
  3201. continue;
  3202. Succ->removePredecessor(SelectBB);
  3203. }
  3204. SI->eraseFromParent();
  3205. }
  3206. /// If the switch is only used to initialize one or more
  3207. /// phi nodes in a common successor block with only two different
  3208. /// constant values, replace the switch with select.
  3209. static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  3210. AssumptionCache *AC, const DataLayout &DL) {
  3211. Value *const Cond = SI->getCondition();
  3212. PHINode *PHI = nullptr;
  3213. BasicBlock *CommonDest = nullptr;
  3214. Constant *DefaultResult;
  3215. SwitchCaseResultVectorTy UniqueResults;
  3216. // Collect all the cases that will deliver the same value from the switch.
  3217. if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
  3218. DL))
  3219. return false;
  3220. // Selects choose between maximum two values.
  3221. if (UniqueResults.size() != 2)
  3222. return false;
  3223. assert(PHI != nullptr && "PHI for value select not found");
  3224. Builder.SetInsertPoint(SI);
  3225. Value *SelectValue = ConvertTwoCaseSwitch(
  3226. UniqueResults,
  3227. DefaultResult, Cond, Builder);
  3228. if (SelectValue) {
  3229. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  3230. return true;
  3231. }
  3232. // The switch couldn't be converted into a select.
  3233. return false;
  3234. }
  3235. namespace {
  3236. /// This class represents a lookup table that can be used to replace a switch.
  3237. class SwitchLookupTable {
  3238. public:
  3239. /// Create a lookup table to use as a switch replacement with the contents
  3240. /// of Values, using DefaultValue to fill any holes in the table.
  3241. SwitchLookupTable(
  3242. Module &M, uint64_t TableSize, ConstantInt *Offset,
  3243. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  3244. Constant *DefaultValue, const DataLayout &DL);
  3245. /// Build instructions with Builder to retrieve the value at
  3246. /// the position given by Index in the lookup table.
  3247. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  3248. /// Return true if a table with TableSize elements of
  3249. /// type ElementType would fit in a target-legal register.
  3250. static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
  3251. const Type *ElementType);
  3252. private:
  3253. // Depending on the contents of the table, it can be represented in
  3254. // different ways.
  3255. enum {
  3256. // For tables where each element contains the same value, we just have to
  3257. // store that single value and return it for each lookup.
  3258. SingleValueKind,
  3259. // For tables where there is a linear relationship between table index
  3260. // and values. We calculate the result with a simple multiplication
  3261. // and addition instead of a table lookup.
  3262. LinearMapKind,
  3263. // For small tables with integer elements, we can pack them into a bitmap
  3264. // that fits into a target-legal register. Values are retrieved by
  3265. // shift and mask operations.
  3266. BitMapKind,
  3267. // The table is stored as an array of values. Values are retrieved by load
  3268. // instructions from the table.
  3269. ArrayKind
  3270. } Kind;
  3271. // For SingleValueKind, this is the single value.
  3272. Constant *SingleValue;
  3273. // For BitMapKind, this is the bitmap.
  3274. ConstantInt *BitMap;
  3275. IntegerType *BitMapElementTy;
  3276. // For LinearMapKind, these are the constants used to derive the value.
  3277. ConstantInt *LinearOffset;
  3278. ConstantInt *LinearMultiplier;
  3279. // For ArrayKind, this is the array.
  3280. GlobalVariable *Array;
  3281. };
  3282. }
  3283. SwitchLookupTable::SwitchLookupTable(
  3284. Module &M, uint64_t TableSize, ConstantInt *Offset,
  3285. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  3286. Constant *DefaultValue, const DataLayout &DL)
  3287. : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
  3288. LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
  3289. assert(Values.size() && "Can't build lookup table without values!");
  3290. assert(TableSize >= Values.size() && "Can't fit values in table!");
  3291. // If all values in the table are equal, this is that value.
  3292. SingleValue = Values.begin()->second;
  3293. Type *ValueType = Values.begin()->second->getType();
  3294. // Build up the table contents.
  3295. SmallVector<Constant*, 64> TableContents(TableSize);
  3296. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  3297. ConstantInt *CaseVal = Values[I].first;
  3298. Constant *CaseRes = Values[I].second;
  3299. assert(CaseRes->getType() == ValueType);
  3300. uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
  3301. .getLimitedValue();
  3302. TableContents[Idx] = CaseRes;
  3303. if (CaseRes != SingleValue)
  3304. SingleValue = nullptr;
  3305. }
  3306. // Fill in any holes in the table with the default result.
  3307. if (Values.size() < TableSize) {
  3308. assert(DefaultValue &&
  3309. "Need a default value to fill the lookup table holes.");
  3310. assert(DefaultValue->getType() == ValueType);
  3311. for (uint64_t I = 0; I < TableSize; ++I) {
  3312. if (!TableContents[I])
  3313. TableContents[I] = DefaultValue;
  3314. }
  3315. if (DefaultValue != SingleValue)
  3316. SingleValue = nullptr;
  3317. }
  3318. // If each element in the table contains the same value, we only need to store
  3319. // that single value.
  3320. if (SingleValue) {
  3321. Kind = SingleValueKind;
  3322. return;
  3323. }
  3324. // Check if we can derive the value with a linear transformation from the
  3325. // table index.
  3326. if (isa<IntegerType>(ValueType)) {
  3327. bool LinearMappingPossible = true;
  3328. APInt PrevVal;
  3329. APInt DistToPrev;
  3330. assert(TableSize >= 2 && "Should be a SingleValue table.");
  3331. // Check if there is the same distance between two consecutive values.
  3332. for (uint64_t I = 0; I < TableSize; ++I) {
  3333. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  3334. if (!ConstVal) {
  3335. // This is an undef. We could deal with it, but undefs in lookup tables
  3336. // are very seldom. It's probably not worth the additional complexity.
  3337. LinearMappingPossible = false;
  3338. break;
  3339. }
  3340. APInt Val = ConstVal->getValue();
  3341. if (I != 0) {
  3342. APInt Dist = Val - PrevVal;
  3343. if (I == 1) {
  3344. DistToPrev = Dist;
  3345. } else if (Dist != DistToPrev) {
  3346. LinearMappingPossible = false;
  3347. break;
  3348. }
  3349. }
  3350. PrevVal = Val;
  3351. }
  3352. if (LinearMappingPossible) {
  3353. LinearOffset = cast<ConstantInt>(TableContents[0]);
  3354. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  3355. Kind = LinearMapKind;
  3356. ++NumLinearMaps;
  3357. return;
  3358. }
  3359. }
  3360. // If the type is integer and the table fits in a register, build a bitmap.
  3361. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  3362. IntegerType *IT = cast<IntegerType>(ValueType);
  3363. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  3364. for (uint64_t I = TableSize; I > 0; --I) {
  3365. TableInt <<= IT->getBitWidth();
  3366. // Insert values into the bitmap. Undef values are set to zero.
  3367. if (!isa<UndefValue>(TableContents[I - 1])) {
  3368. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  3369. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  3370. }
  3371. }
  3372. BitMap = ConstantInt::get(M.getContext(), TableInt);
  3373. BitMapElementTy = IT;
  3374. Kind = BitMapKind;
  3375. ++NumBitMaps;
  3376. return;
  3377. }
  3378. // Store the table in an array.
  3379. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  3380. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  3381. Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
  3382. GlobalVariable::PrivateLinkage,
  3383. Initializer,
  3384. "switch.table");
  3385. Array->setUnnamedAddr(true);
  3386. Kind = ArrayKind;
  3387. }
  3388. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  3389. switch (Kind) {
  3390. case SingleValueKind:
  3391. return SingleValue;
  3392. case LinearMapKind: {
  3393. // Derive the result value from the input value.
  3394. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  3395. false, "switch.idx.cast");
  3396. if (!LinearMultiplier->isOne())
  3397. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  3398. if (!LinearOffset->isZero())
  3399. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  3400. return Result;
  3401. }
  3402. case BitMapKind: {
  3403. // Type of the bitmap (e.g. i59).
  3404. IntegerType *MapTy = BitMap->getType();
  3405. // Cast Index to the same type as the bitmap.
  3406. // Note: The Index is <= the number of elements in the table, so
  3407. // truncating it to the width of the bitmask is safe.
  3408. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  3409. // Multiply the shift amount by the element width.
  3410. ShiftAmt = Builder.CreateMul(ShiftAmt,
  3411. ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  3412. "switch.shiftamt");
  3413. // Shift down.
  3414. Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
  3415. "switch.downshift");
  3416. // Mask off.
  3417. return Builder.CreateTrunc(DownShifted, BitMapElementTy,
  3418. "switch.masked");
  3419. }
  3420. case ArrayKind: {
  3421. // Make sure the table index will not overflow when treated as signed.
  3422. IntegerType *IT = cast<IntegerType>(Index->getType());
  3423. uint64_t TableSize = Array->getInitializer()->getType()
  3424. ->getArrayNumElements();
  3425. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  3426. Index = Builder.CreateZExt(Index,
  3427. IntegerType::get(IT->getContext(),
  3428. IT->getBitWidth() + 1),
  3429. "switch.tableidx.zext");
  3430. Value *GEPIndices[] = { Builder.getInt32(0), Index };
  3431. Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
  3432. GEPIndices, "switch.gep");
  3433. return Builder.CreateLoad(GEP, "switch.load");
  3434. }
  3435. }
  3436. llvm_unreachable("Unknown lookup table kind!");
  3437. }
  3438. bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
  3439. uint64_t TableSize,
  3440. const Type *ElementType) {
  3441. const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
  3442. if (!IT)
  3443. return false;
  3444. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  3445. // are <= 15, we could try to narrow the type.
  3446. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  3447. if (TableSize >= UINT_MAX/IT->getBitWidth())
  3448. return false;
  3449. return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
  3450. }
  3451. /// Determine whether a lookup table should be built for this switch, based on
  3452. /// the number of cases, size of the table, and the types of the results.
  3453. static bool
  3454. ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
  3455. const TargetTransformInfo &TTI, const DataLayout &DL,
  3456. const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
  3457. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  3458. return false; // TableSize overflowed, or mul below might overflow.
  3459. bool AllTablesFitInRegister = true;
  3460. bool HasIllegalType = false;
  3461. for (const auto &I : ResultTypes) {
  3462. Type *Ty = I.second;
  3463. // Saturate this flag to true.
  3464. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  3465. // Saturate this flag to false.
  3466. AllTablesFitInRegister = AllTablesFitInRegister &&
  3467. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  3468. // If both flags saturate, we're done. NOTE: This *only* works with
  3469. // saturating flags, and all flags have to saturate first due to the
  3470. // non-deterministic behavior of iterating over a dense map.
  3471. if (HasIllegalType && !AllTablesFitInRegister)
  3472. break;
  3473. }
  3474. // If each table would fit in a register, we should build it anyway.
  3475. if (AllTablesFitInRegister)
  3476. return true;
  3477. // Don't build a table that doesn't fit in-register if it has illegal types.
  3478. if (HasIllegalType)
  3479. return false;
  3480. // The table density should be at least 40%. This is the same criterion as for
  3481. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  3482. // FIXME: Find the best cut-off.
  3483. return SI->getNumCases() * 10 >= TableSize * 4;
  3484. }
  3485. /// Try to reuse the switch table index compare. Following pattern:
  3486. /// \code
  3487. /// if (idx < tablesize)
  3488. /// r = table[idx]; // table does not contain default_value
  3489. /// else
  3490. /// r = default_value;
  3491. /// if (r != default_value)
  3492. /// ...
  3493. /// \endcode
  3494. /// Is optimized to:
  3495. /// \code
  3496. /// cond = idx < tablesize;
  3497. /// if (cond)
  3498. /// r = table[idx];
  3499. /// else
  3500. /// r = default_value;
  3501. /// if (cond)
  3502. /// ...
  3503. /// \endcode
  3504. /// Jump threading will then eliminate the second if(cond).
  3505. static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
  3506. BranchInst *RangeCheckBranch, Constant *DefaultValue,
  3507. const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
  3508. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  3509. if (!CmpInst)
  3510. return;
  3511. // We require that the compare is in the same block as the phi so that jump
  3512. // threading can do its work afterwards.
  3513. if (CmpInst->getParent() != PhiBlock)
  3514. return;
  3515. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  3516. if (!CmpOp1)
  3517. return;
  3518. Value *RangeCmp = RangeCheckBranch->getCondition();
  3519. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  3520. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  3521. // Check if the compare with the default value is constant true or false.
  3522. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3523. DefaultValue, CmpOp1, true);
  3524. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  3525. return;
  3526. // Check if the compare with the case values is distinct from the default
  3527. // compare result.
  3528. for (auto ValuePair : Values) {
  3529. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3530. ValuePair.second, CmpOp1, true);
  3531. if (!CaseConst || CaseConst == DefaultConst)
  3532. return;
  3533. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  3534. "Expect true or false as compare result.");
  3535. }
  3536. // Check if the branch instruction dominates the phi node. It's a simple
  3537. // dominance check, but sufficient for our needs.
  3538. // Although this check is invariant in the calling loops, it's better to do it
  3539. // at this late stage. Practically we do it at most once for a switch.
  3540. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  3541. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  3542. BasicBlock *Pred = *PI;
  3543. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  3544. return;
  3545. }
  3546. if (DefaultConst == FalseConst) {
  3547. // The compare yields the same result. We can replace it.
  3548. CmpInst->replaceAllUsesWith(RangeCmp);
  3549. ++NumTableCmpReuses;
  3550. } else {
  3551. // The compare yields the same result, just inverted. We can replace it.
  3552. Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
  3553. ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  3554. RangeCheckBranch);
  3555. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  3556. ++NumTableCmpReuses;
  3557. }
  3558. }
  3559. /// If the switch is only used to initialize one or more phi nodes in a common
  3560. /// successor block with different constant values, replace the switch with
  3561. /// lookup tables.
  3562. static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
  3563. const DataLayout &DL,
  3564. const TargetTransformInfo &TTI) {
  3565. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3566. // Only build lookup table when we have a target that supports it.
  3567. if (!TTI.shouldBuildLookupTables())
  3568. return false;
  3569. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  3570. // split off a dense part and build a lookup table for that.
  3571. // FIXME: This creates arrays of GEPs to constant strings, which means each
  3572. // GEP needs a runtime relocation in PIC code. We should just build one big
  3573. // string and lookup indices into that.
  3574. // Ignore switches with less than three cases. Lookup tables will not make them
  3575. // faster, so we don't analyze them.
  3576. if (SI->getNumCases() < 3)
  3577. return false;
  3578. // Figure out the corresponding result for each case value and phi node in the
  3579. // common destination, as well as the min and max case values.
  3580. assert(SI->case_begin() != SI->case_end());
  3581. SwitchInst::CaseIt CI = SI->case_begin();
  3582. ConstantInt *MinCaseVal = CI.getCaseValue();
  3583. ConstantInt *MaxCaseVal = CI.getCaseValue();
  3584. BasicBlock *CommonDest = nullptr;
  3585. typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
  3586. SmallDenseMap<PHINode*, ResultListTy> ResultLists;
  3587. SmallDenseMap<PHINode*, Constant*> DefaultResults;
  3588. SmallDenseMap<PHINode*, Type*> ResultTypes;
  3589. SmallVector<PHINode*, 4> PHIs;
  3590. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  3591. ConstantInt *CaseVal = CI.getCaseValue();
  3592. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  3593. MinCaseVal = CaseVal;
  3594. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  3595. MaxCaseVal = CaseVal;
  3596. // Resulting value at phi nodes for this case value.
  3597. typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
  3598. ResultsTy Results;
  3599. if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
  3600. Results, DL))
  3601. return false;
  3602. // Append the result from this case to the list for each phi.
  3603. for (const auto &I : Results) {
  3604. PHINode *PHI = I.first;
  3605. Constant *Value = I.second;
  3606. if (!ResultLists.count(PHI))
  3607. PHIs.push_back(PHI);
  3608. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  3609. }
  3610. }
  3611. // Keep track of the result types.
  3612. for (PHINode *PHI : PHIs) {
  3613. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  3614. }
  3615. uint64_t NumResults = ResultLists[PHIs[0]].size();
  3616. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  3617. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  3618. bool TableHasHoles = (NumResults < TableSize);
  3619. // If the table has holes, we need a constant result for the default case
  3620. // or a bitmask that fits in a register.
  3621. SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
  3622. bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
  3623. &CommonDest, DefaultResultsList, DL);
  3624. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  3625. if (NeedMask) {
  3626. // As an extra penalty for the validity test we require more cases.
  3627. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  3628. return false;
  3629. if (!DL.fitsInLegalInteger(TableSize))
  3630. return false;
  3631. }
  3632. for (const auto &I : DefaultResultsList) {
  3633. PHINode *PHI = I.first;
  3634. Constant *Result = I.second;
  3635. DefaultResults[PHI] = Result;
  3636. }
  3637. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  3638. return false;
  3639. // Create the BB that does the lookups.
  3640. Module &Mod = *CommonDest->getParent()->getParent();
  3641. BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
  3642. "switch.lookup",
  3643. CommonDest->getParent(),
  3644. CommonDest);
  3645. // Compute the table index value.
  3646. Builder.SetInsertPoint(SI);
  3647. Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  3648. "switch.tableidx");
  3649. // Compute the maximum table size representable by the integer type we are
  3650. // switching upon.
  3651. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  3652. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  3653. assert(MaxTableSize >= TableSize &&
  3654. "It is impossible for a switch to have more entries than the max "
  3655. "representable value of its input integer type's size.");
  3656. // If the default destination is unreachable, or if the lookup table covers
  3657. // all values of the conditional variable, branch directly to the lookup table
  3658. // BB. Otherwise, check that the condition is within the case range.
  3659. const bool DefaultIsReachable =
  3660. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3661. const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
  3662. BranchInst *RangeCheckBranch = nullptr;
  3663. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  3664. Builder.CreateBr(LookupBB);
  3665. // Note: We call removeProdecessor later since we need to be able to get the
  3666. // PHI value for the default case in case we're using a bit mask.
  3667. } else {
  3668. Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
  3669. MinCaseVal->getType(), TableSize));
  3670. RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  3671. }
  3672. // Populate the BB that does the lookups.
  3673. Builder.SetInsertPoint(LookupBB);
  3674. if (NeedMask) {
  3675. // Before doing the lookup we do the hole check.
  3676. // The LookupBB is therefore re-purposed to do the hole check
  3677. // and we create a new LookupBB.
  3678. BasicBlock *MaskBB = LookupBB;
  3679. MaskBB->setName("switch.hole_check");
  3680. LookupBB = BasicBlock::Create(Mod.getContext(),
  3681. "switch.lookup",
  3682. CommonDest->getParent(),
  3683. CommonDest);
  3684. // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
  3685. // unnecessary illegal types.
  3686. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  3687. APInt MaskInt(TableSizePowOf2, 0);
  3688. APInt One(TableSizePowOf2, 1);
  3689. // Build bitmask; fill in a 1 bit for every case.
  3690. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  3691. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  3692. uint64_t Idx = (ResultList[I].first->getValue() -
  3693. MinCaseVal->getValue()).getLimitedValue();
  3694. MaskInt |= One << Idx;
  3695. }
  3696. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  3697. // Get the TableIndex'th bit of the bitmask.
  3698. // If this bit is 0 (meaning hole) jump to the default destination,
  3699. // else continue with table lookup.
  3700. IntegerType *MapTy = TableMask->getType();
  3701. Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
  3702. "switch.maskindex");
  3703. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
  3704. "switch.shifted");
  3705. Value *LoBit = Builder.CreateTrunc(Shifted,
  3706. Type::getInt1Ty(Mod.getContext()),
  3707. "switch.lobit");
  3708. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  3709. Builder.SetInsertPoint(LookupBB);
  3710. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  3711. }
  3712. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  3713. // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
  3714. // do not delete PHINodes here.
  3715. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  3716. /*DontDeleteUselessPHIs=*/true);
  3717. }
  3718. bool ReturnedEarly = false;
  3719. for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
  3720. PHINode *PHI = PHIs[I];
  3721. const ResultListTy &ResultList = ResultLists[PHI];
  3722. // If using a bitmask, use any value to fill the lookup table holes.
  3723. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  3724. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
  3725. Value *Result = Table.BuildLookup(TableIndex, Builder);
  3726. // If the result is used to return immediately from the function, we want to
  3727. // do that right here.
  3728. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  3729. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  3730. Builder.CreateRet(Result);
  3731. ReturnedEarly = true;
  3732. break;
  3733. }
  3734. // Do a small peephole optimization: re-use the switch table compare if
  3735. // possible.
  3736. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  3737. BasicBlock *PhiBlock = PHI->getParent();
  3738. // Search for compare instructions which use the phi.
  3739. for (auto *User : PHI->users()) {
  3740. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  3741. }
  3742. }
  3743. PHI->addIncoming(Result, LookupBB);
  3744. }
  3745. if (!ReturnedEarly)
  3746. Builder.CreateBr(CommonDest);
  3747. // Remove the switch.
  3748. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3749. BasicBlock *Succ = SI->getSuccessor(i);
  3750. if (Succ == SI->getDefaultDest())
  3751. continue;
  3752. Succ->removePredecessor(SI->getParent());
  3753. }
  3754. SI->eraseFromParent();
  3755. ++NumLookupTables;
  3756. if (NeedMask)
  3757. ++NumLookupTablesHoles;
  3758. return true;
  3759. }
  3760. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  3761. BasicBlock *BB = SI->getParent();
  3762. if (isValueEqualityComparison(SI)) {
  3763. // If we only have one predecessor, and if it is a branch on this value,
  3764. // see if that predecessor totally determines the outcome of this switch.
  3765. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3766. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  3767. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3768. Value *Cond = SI->getCondition();
  3769. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  3770. if (SimplifySwitchOnSelect(SI, Select))
  3771. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3772. // If the block only contains the switch, see if we can fold the block
  3773. // away into any preds.
  3774. BasicBlock::iterator BBI = BB->begin();
  3775. // Ignore dbg intrinsics.
  3776. while (isa<DbgInfoIntrinsic>(BBI))
  3777. ++BBI;
  3778. if (SI == &*BBI)
  3779. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  3780. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3781. }
  3782. // Try to transform the switch into an icmp and a branch.
  3783. if (TurnSwitchRangeIntoICmp(SI, Builder))
  3784. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3785. // Remove unreachable cases.
  3786. if (EliminateDeadSwitchCases(SI, AC, DL))
  3787. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3788. if (SwitchToSelect(SI, Builder, AC, DL))
  3789. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3790. if (ForwardSwitchConditionToPHI(SI))
  3791. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3792. if (SwitchToLookupTable(SI, Builder, DL, TTI))
  3793. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3794. return false;
  3795. }
  3796. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  3797. BasicBlock *BB = IBI->getParent();
  3798. bool Changed = false;
  3799. // Eliminate redundant destinations.
  3800. SmallPtrSet<Value *, 8> Succs;
  3801. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  3802. BasicBlock *Dest = IBI->getDestination(i);
  3803. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  3804. Dest->removePredecessor(BB);
  3805. IBI->removeDestination(i);
  3806. --i; --e;
  3807. Changed = true;
  3808. }
  3809. }
  3810. if (IBI->getNumDestinations() == 0) {
  3811. // If the indirectbr has no successors, change it to unreachable.
  3812. new UnreachableInst(IBI->getContext(), IBI);
  3813. EraseTerminatorInstAndDCECond(IBI);
  3814. return true;
  3815. }
  3816. if (IBI->getNumDestinations() == 1) {
  3817. // If the indirectbr has one successor, change it to a direct branch.
  3818. BranchInst::Create(IBI->getDestination(0), IBI);
  3819. EraseTerminatorInstAndDCECond(IBI);
  3820. return true;
  3821. }
  3822. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  3823. if (SimplifyIndirectBrOnSelect(IBI, SI))
  3824. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3825. }
  3826. return Changed;
  3827. }
  3828. /// Given an block with only a single landing pad and a unconditional branch
  3829. /// try to find another basic block which this one can be merged with. This
  3830. /// handles cases where we have multiple invokes with unique landing pads, but
  3831. /// a shared handler.
  3832. ///
  3833. /// We specifically choose to not worry about merging non-empty blocks
  3834. /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
  3835. /// practice, the optimizer produces empty landing pad blocks quite frequently
  3836. /// when dealing with exception dense code. (see: instcombine, gvn, if-else
  3837. /// sinking in this file)
  3838. ///
  3839. /// This is primarily a code size optimization. We need to avoid performing
  3840. /// any transform which might inhibit optimization (such as our ability to
  3841. /// specialize a particular handler via tail commoning). We do this by not
  3842. /// merging any blocks which require us to introduce a phi. Since the same
  3843. /// values are flowing through both blocks, we don't loose any ability to
  3844. /// specialize. If anything, we make such specialization more likely.
  3845. ///
  3846. /// TODO - This transformation could remove entries from a phi in the target
  3847. /// block when the inputs in the phi are the same for the two blocks being
  3848. /// merged. In some cases, this could result in removal of the PHI entirely.
  3849. static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
  3850. BasicBlock *BB) {
  3851. auto Succ = BB->getUniqueSuccessor();
  3852. assert(Succ);
  3853. // If there's a phi in the successor block, we'd likely have to introduce
  3854. // a phi into the merged landing pad block.
  3855. if (isa<PHINode>(*Succ->begin()))
  3856. return false;
  3857. for (BasicBlock *OtherPred : predecessors(Succ)) {
  3858. if (BB == OtherPred)
  3859. continue;
  3860. BasicBlock::iterator I = OtherPred->begin();
  3861. LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
  3862. if (!LPad2 || !LPad2->isIdenticalTo(LPad))
  3863. continue;
  3864. for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
  3865. BranchInst *BI2 = dyn_cast<BranchInst>(I);
  3866. if (!BI2 || !BI2->isIdenticalTo(BI))
  3867. continue;
  3868. // We've found an identical block. Update our predeccessors to take that
  3869. // path instead and make ourselves dead.
  3870. SmallSet<BasicBlock *, 16> Preds;
  3871. Preds.insert(pred_begin(BB), pred_end(BB));
  3872. for (BasicBlock *Pred : Preds) {
  3873. InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
  3874. assert(II->getNormalDest() != BB &&
  3875. II->getUnwindDest() == BB && "unexpected successor");
  3876. II->setUnwindDest(OtherPred);
  3877. }
  3878. // The debug info in OtherPred doesn't cover the merged control flow that
  3879. // used to go through BB. We need to delete it or update it.
  3880. for (auto I = OtherPred->begin(), E = OtherPred->end();
  3881. I != E;) {
  3882. Instruction &Inst = *I; I++;
  3883. if (isa<DbgInfoIntrinsic>(Inst))
  3884. Inst.eraseFromParent();
  3885. }
  3886. SmallSet<BasicBlock *, 16> Succs;
  3887. Succs.insert(succ_begin(BB), succ_end(BB));
  3888. for (BasicBlock *Succ : Succs) {
  3889. Succ->removePredecessor(BB);
  3890. }
  3891. IRBuilder<> Builder(BI);
  3892. Builder.CreateUnreachable();
  3893. BI->eraseFromParent();
  3894. return true;
  3895. }
  3896. return false;
  3897. }
  3898. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
  3899. BasicBlock *BB = BI->getParent();
  3900. if (SinkCommon && SinkThenElseCodeToEnd(BI))
  3901. return true;
  3902. // If the Terminator is the only non-phi instruction, simplify the block.
  3903. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
  3904. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  3905. TryToSimplifyUncondBranchFromEmptyBlock(BB))
  3906. return true;
  3907. // If the only instruction in the block is a seteq/setne comparison
  3908. // against a constant, try to simplify the block.
  3909. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  3910. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  3911. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  3912. ;
  3913. if (I->isTerminator() &&
  3914. TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
  3915. BonusInstThreshold, AC))
  3916. return true;
  3917. }
  3918. // See if we can merge an empty landing pad block with another which is
  3919. // equivalent.
  3920. if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
  3921. for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
  3922. if (I->isTerminator() &&
  3923. TryToMergeLandingPad(LPad, BI, BB))
  3924. return true;
  3925. }
  3926. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3927. // branches to us and our successor, fold the comparison into the
  3928. // predecessor and use logical operations to update the incoming value
  3929. // for PHI nodes in common successor.
  3930. if (FoldBranchToCommonDest(BI, BonusInstThreshold))
  3931. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3932. return false;
  3933. }
  3934. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  3935. BasicBlock *BB = BI->getParent();
  3936. // Conditional branch
  3937. if (isValueEqualityComparison(BI)) {
  3938. // If we only have one predecessor, and if it is a branch on this value,
  3939. // see if that predecessor totally determines the outcome of this
  3940. // switch.
  3941. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3942. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  3943. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3944. // This block must be empty, except for the setcond inst, if it exists.
  3945. // Ignore dbg intrinsics.
  3946. BasicBlock::iterator I = BB->begin();
  3947. // Ignore dbg intrinsics.
  3948. while (isa<DbgInfoIntrinsic>(I))
  3949. ++I;
  3950. if (&*I == BI) {
  3951. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  3952. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3953. } else if (&*I == cast<Instruction>(BI->getCondition())){
  3954. ++I;
  3955. // Ignore dbg intrinsics.
  3956. while (isa<DbgInfoIntrinsic>(I))
  3957. ++I;
  3958. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  3959. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3960. }
  3961. }
  3962. #if 0 // HLSL Change Begins. This will not help for hlsl.
  3963. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  3964. if (SimplifyBranchOnICmpChain(BI, Builder, DL))
  3965. return true;
  3966. #endif // HLSL Change Ends.
  3967. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3968. // branches to us and one of our successors, fold the comparison into the
  3969. // predecessor and use logical operations to pick the right destination.
  3970. if (FoldBranchToCommonDest(BI, BonusInstThreshold))
  3971. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3972. // We have a conditional branch to two blocks that are only reachable
  3973. // from BI. We know that the condbr dominates the two blocks, so see if
  3974. // there is any identical code in the "then" and "else" blocks. If so, we
  3975. // can hoist it up to the branching block.
  3976. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  3977. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3978. if (HoistThenElseCodeToIf(BI, TTI))
  3979. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3980. } else {
  3981. // If Successor #1 has multiple preds, we may be able to conditionally
  3982. // execute Successor #0 if it branches to Successor #1.
  3983. TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
  3984. if (Succ0TI->getNumSuccessors() == 1 &&
  3985. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  3986. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
  3987. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3988. }
  3989. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3990. // If Successor #0 has multiple preds, we may be able to conditionally
  3991. // execute Successor #1 if it branches to Successor #0.
  3992. TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
  3993. if (Succ1TI->getNumSuccessors() == 1 &&
  3994. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  3995. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
  3996. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3997. }
  3998. #if 0 // HLSL Change - this transformation creates unstructured flow
  3999. // If this is a branch on a phi node in the current block, thread control
  4000. // through this block if any PHI node entries are constants.
  4001. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  4002. if (PN->getParent() == BI->getParent())
  4003. if (FoldCondBranchOnPHI(BI, DL))
  4004. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  4005. #endif // HLSL Change
  4006. // Scan predecessor blocks for conditional branches.
  4007. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  4008. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  4009. if (PBI != BI && PBI->isConditional())
  4010. if (SimplifyCondBranchToCondBranch(PBI, BI))
  4011. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  4012. return false;
  4013. }
  4014. /// Check if passing a value to an instruction will cause undefined behavior.
  4015. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  4016. Constant *C = dyn_cast<Constant>(V);
  4017. if (!C)
  4018. return false;
  4019. if (I->use_empty())
  4020. return false;
  4021. if (C->isNullValue()) {
  4022. // Only look at the first use, avoid hurting compile time with long uselists
  4023. User *Use = *I->user_begin();
  4024. // Now make sure that there are no instructions in between that can alter
  4025. // control flow (eg. calls)
  4026. for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
  4027. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  4028. return false;
  4029. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  4030. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  4031. if (GEP->getPointerOperand() == I)
  4032. return passingValueIsAlwaysUndefined(V, GEP);
  4033. // Look through bitcasts.
  4034. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  4035. return passingValueIsAlwaysUndefined(V, BC);
  4036. // Load from null is undefined.
  4037. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  4038. if (!LI->isVolatile())
  4039. return LI->getPointerAddressSpace() == 0;
  4040. // Store to null is undefined.
  4041. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  4042. if (!SI->isVolatile())
  4043. return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
  4044. }
  4045. return false;
  4046. }
  4047. /// If BB has an incoming value that will always trigger undefined behavior
  4048. /// (eg. null pointer dereference), remove the branch leading here.
  4049. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  4050. for (BasicBlock::iterator i = BB->begin();
  4051. PHINode *PHI = dyn_cast<PHINode>(i); ++i)
  4052. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
  4053. if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
  4054. TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
  4055. IRBuilder<> Builder(T);
  4056. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  4057. BB->removePredecessor(PHI->getIncomingBlock(i));
  4058. // Turn uncoditional branches into unreachables and remove the dead
  4059. // destination from conditional branches.
  4060. if (BI->isUnconditional())
  4061. Builder.CreateUnreachable();
  4062. else
  4063. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
  4064. BI->getSuccessor(0));
  4065. BI->eraseFromParent();
  4066. return true;
  4067. }
  4068. // TODO: SwitchInst.
  4069. }
  4070. return false;
  4071. }
  4072. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  4073. bool Changed = false;
  4074. assert(BB && BB->getParent() && "Block not embedded in function!");
  4075. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  4076. // Remove basic blocks that have no predecessors (except the entry block)...
  4077. // or that just have themself as a predecessor. These are unreachable.
  4078. if ((pred_empty(BB) &&
  4079. BB != &BB->getParent()->getEntryBlock()) ||
  4080. BB->getSinglePredecessor() == BB) {
  4081. DEBUG(dbgs() << "Removing BB: \n" << *BB);
  4082. DeleteDeadBlock(BB);
  4083. return true;
  4084. }
  4085. // Check to see if we can constant propagate this terminator instruction
  4086. // away...
  4087. Changed |= ConstantFoldTerminator(BB, true);
  4088. // Check for and eliminate duplicate PHI nodes in this block.
  4089. Changed |= EliminateDuplicatePHINodes(BB);
  4090. // Check for and remove branches that will always cause undefined behavior.
  4091. Changed |= removeUndefIntroducingPredecessor(BB);
  4092. // Merge basic blocks into their predecessor if there is only one distinct
  4093. // pred, and if there is only one distinct successor of the predecessor, and
  4094. // if there are no PHI nodes.
  4095. //
  4096. if (MergeBlockIntoPredecessor(BB))
  4097. return true;
  4098. IRBuilder<> Builder(BB);
  4099. // If there is a trivial two-entry PHI node in this basic block, and we can
  4100. // eliminate it, do so now.
  4101. if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
  4102. if (PN->getNumIncomingValues() == 2)
  4103. Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
  4104. Builder.SetInsertPoint(BB->getTerminator());
  4105. if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  4106. if (BI->isUnconditional()) {
  4107. if (SimplifyUncondBranch(BI, Builder)) return true;
  4108. } else {
  4109. if (SimplifyCondBranch(BI, Builder)) return true;
  4110. }
  4111. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  4112. if (SimplifyReturn(RI, Builder)) return true;
  4113. } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  4114. if (SimplifyResume(RI, Builder)) return true;
  4115. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  4116. if (SimplifySwitch(SI, Builder)) return true;
  4117. } else if (UnreachableInst *UI =
  4118. dyn_cast<UnreachableInst>(BB->getTerminator())) {
  4119. if (SimplifyUnreachable(UI)) return true;
  4120. } else if (IndirectBrInst *IBI =
  4121. dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  4122. if (SimplifyIndirectBr(IBI)) return true;
  4123. }
  4124. return Changed;
  4125. }
  4126. /// This function is used to do simplification of a CFG.
  4127. /// For example, it adjusts branches to branches to eliminate the extra hop,
  4128. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  4129. /// of the CFG. It returns true if a modification was made.
  4130. ///
  4131. bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  4132. unsigned BonusInstThreshold, AssumptionCache *AC) {
  4133. return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
  4134. BonusInstThreshold, AC).run(BB);
  4135. }