InstCombineAndOrXor.cpp 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317
  1. //===- InstCombineAndOrXor.cpp --------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the visitAnd, visitOr, and visitXor functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/Analysis/CmpInstAnalysis.h"
  14. #include "llvm/Analysis/InstructionSimplify.h"
  15. #include "llvm/IR/ConstantRange.h"
  16. #include "llvm/IR/Intrinsics.h"
  17. #include "llvm/IR/PatternMatch.h"
  18. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  19. #include "llvm/Transforms/Utils/Local.h"
  20. using namespace llvm;
  21. using namespace PatternMatch;
  22. #define DEBUG_TYPE "instcombine"
  23. /// This is the complement of getICmpCode, which turns an opcode and two
  24. /// operands into either a constant true or false, or a brand new ICmp
  25. /// instruction. The sign is passed in to determine which kind of predicate to
  26. /// use in the new icmp instruction.
  27. static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
  28. InstCombiner::BuilderTy &Builder) {
  29. ICmpInst::Predicate NewPred;
  30. if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
  31. return TorF;
  32. return Builder.CreateICmp(NewPred, LHS, RHS);
  33. }
  34. /// This is the complement of getFCmpCode, which turns an opcode and two
  35. /// operands into either a FCmp instruction, or a true/false constant.
  36. static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
  37. InstCombiner::BuilderTy &Builder) {
  38. FCmpInst::Predicate NewPred;
  39. if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
  40. return TorF;
  41. return Builder.CreateFCmp(NewPred, LHS, RHS);
  42. }
  43. /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
  44. /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
  45. /// \param I Binary operator to transform.
  46. /// \return Pointer to node that must replace the original binary operator, or
  47. /// null pointer if no transformation was made.
  48. static Value *SimplifyBSwap(BinaryOperator &I,
  49. InstCombiner::BuilderTy &Builder) {
  50. assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
  51. Value *OldLHS = I.getOperand(0);
  52. Value *OldRHS = I.getOperand(1);
  53. Value *NewLHS;
  54. if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
  55. return nullptr;
  56. Value *NewRHS;
  57. const APInt *C;
  58. if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
  59. // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
  60. if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
  61. return nullptr;
  62. // NewRHS initialized by the matcher.
  63. } else if (match(OldRHS, m_APInt(C))) {
  64. // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
  65. if (!OldLHS->hasOneUse())
  66. return nullptr;
  67. NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
  68. } else
  69. return nullptr;
  70. Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
  71. Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
  72. I.getType());
  73. return Builder.CreateCall(F, BinOp);
  74. }
  75. /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
  76. /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
  77. /// whether to treat V, Lo, and Hi as signed or not.
  78. Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
  79. const APInt &Hi, bool isSigned,
  80. bool Inside) {
  81. assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
  82. "Lo is not < Hi in range emission code!");
  83. Type *Ty = V->getType();
  84. // V >= Min && V < Hi --> V < Hi
  85. // V < Min || V >= Hi --> V >= Hi
  86. ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
  87. if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
  88. Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
  89. return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
  90. }
  91. // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
  92. // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
  93. Value *VMinusLo =
  94. Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
  95. Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
  96. return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
  97. }
  98. /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
  99. /// that can be simplified.
  100. /// One of A and B is considered the mask. The other is the value. This is
  101. /// described as the "AMask" or "BMask" part of the enum. If the enum contains
  102. /// only "Mask", then both A and B can be considered masks. If A is the mask,
  103. /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
  104. /// If both A and C are constants, this proof is also easy.
  105. /// For the following explanations, we assume that A is the mask.
  106. ///
  107. /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
  108. /// bits of A are set in B.
  109. /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
  110. ///
  111. /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
  112. /// bits of A are cleared in B.
  113. /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
  114. ///
  115. /// "Mixed" declares that (A & B) == C and C might or might not contain any
  116. /// number of one bits and zero bits.
  117. /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
  118. ///
  119. /// "Not" means that in above descriptions "==" should be replaced by "!=".
  120. /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
  121. ///
  122. /// If the mask A contains a single bit, then the following is equivalent:
  123. /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
  124. /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
  125. enum MaskedICmpType {
  126. AMask_AllOnes = 1,
  127. AMask_NotAllOnes = 2,
  128. BMask_AllOnes = 4,
  129. BMask_NotAllOnes = 8,
  130. Mask_AllZeros = 16,
  131. Mask_NotAllZeros = 32,
  132. AMask_Mixed = 64,
  133. AMask_NotMixed = 128,
  134. BMask_Mixed = 256,
  135. BMask_NotMixed = 512
  136. };
  137. /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
  138. /// satisfies.
  139. static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
  140. ICmpInst::Predicate Pred) {
  141. const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
  142. match(A, m_APInt(ConstA));
  143. match(B, m_APInt(ConstB));
  144. match(C, m_APInt(ConstC));
  145. bool IsEq = (Pred == ICmpInst::ICMP_EQ);
  146. bool IsAPow2 = ConstA && ConstA->isPowerOf2();
  147. bool IsBPow2 = ConstB && ConstB->isPowerOf2();
  148. unsigned MaskVal = 0;
  149. if (ConstC && ConstC->isZero()) {
  150. // if C is zero, then both A and B qualify as mask
  151. MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
  152. : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
  153. if (IsAPow2)
  154. MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
  155. : (AMask_AllOnes | AMask_Mixed));
  156. if (IsBPow2)
  157. MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
  158. : (BMask_AllOnes | BMask_Mixed));
  159. return MaskVal;
  160. }
  161. if (A == C) {
  162. MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
  163. : (AMask_NotAllOnes | AMask_NotMixed));
  164. if (IsAPow2)
  165. MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
  166. : (Mask_AllZeros | AMask_Mixed));
  167. } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
  168. MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
  169. }
  170. if (B == C) {
  171. MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
  172. : (BMask_NotAllOnes | BMask_NotMixed));
  173. if (IsBPow2)
  174. MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
  175. : (Mask_AllZeros | BMask_Mixed));
  176. } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
  177. MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
  178. }
  179. return MaskVal;
  180. }
  181. /// Convert an analysis of a masked ICmp into its equivalent if all boolean
  182. /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
  183. /// is adjacent to the corresponding normal flag (recording ==), this just
  184. /// involves swapping those bits over.
  185. static unsigned conjugateICmpMask(unsigned Mask) {
  186. unsigned NewMask;
  187. NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
  188. AMask_Mixed | BMask_Mixed))
  189. << 1;
  190. NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
  191. AMask_NotMixed | BMask_NotMixed))
  192. >> 1;
  193. return NewMask;
  194. }
  195. // Adapts the external decomposeBitTestICmp for local use.
  196. static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
  197. Value *&X, Value *&Y, Value *&Z) {
  198. APInt Mask;
  199. if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
  200. return false;
  201. Y = ConstantInt::get(X->getType(), Mask);
  202. Z = ConstantInt::get(X->getType(), 0);
  203. return true;
  204. }
  205. /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
  206. /// Return the pattern classes (from MaskedICmpType) for the left hand side and
  207. /// the right hand side as a pair.
  208. /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
  209. /// and PredR are their predicates, respectively.
  210. static std::optional<std::pair<unsigned, unsigned>> getMaskedTypeForICmpPair(
  211. Value *&A, Value *&B, Value *&C, Value *&D, Value *&E, ICmpInst *LHS,
  212. ICmpInst *RHS, ICmpInst::Predicate &PredL, ICmpInst::Predicate &PredR) {
  213. // Don't allow pointers. Splat vectors are fine.
  214. if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
  215. !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
  216. return std::nullopt;
  217. // Here comes the tricky part:
  218. // LHS might be of the form L11 & L12 == X, X == L21 & L22,
  219. // and L11 & L12 == L21 & L22. The same goes for RHS.
  220. // Now we must find those components L** and R**, that are equal, so
  221. // that we can extract the parameters A, B, C, D, and E for the canonical
  222. // above.
  223. Value *L1 = LHS->getOperand(0);
  224. Value *L2 = LHS->getOperand(1);
  225. Value *L11, *L12, *L21, *L22;
  226. // Check whether the icmp can be decomposed into a bit test.
  227. if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
  228. L21 = L22 = L1 = nullptr;
  229. } else {
  230. // Look for ANDs in the LHS icmp.
  231. if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
  232. // Any icmp can be viewed as being trivially masked; if it allows us to
  233. // remove one, it's worth it.
  234. L11 = L1;
  235. L12 = Constant::getAllOnesValue(L1->getType());
  236. }
  237. if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
  238. L21 = L2;
  239. L22 = Constant::getAllOnesValue(L2->getType());
  240. }
  241. }
  242. // Bail if LHS was a icmp that can't be decomposed into an equality.
  243. if (!ICmpInst::isEquality(PredL))
  244. return std::nullopt;
  245. Value *R1 = RHS->getOperand(0);
  246. Value *R2 = RHS->getOperand(1);
  247. Value *R11, *R12;
  248. bool Ok = false;
  249. if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
  250. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  251. A = R11;
  252. D = R12;
  253. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  254. A = R12;
  255. D = R11;
  256. } else {
  257. return std::nullopt;
  258. }
  259. E = R2;
  260. R1 = nullptr;
  261. Ok = true;
  262. } else {
  263. if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
  264. // As before, model no mask as a trivial mask if it'll let us do an
  265. // optimization.
  266. R11 = R1;
  267. R12 = Constant::getAllOnesValue(R1->getType());
  268. }
  269. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  270. A = R11;
  271. D = R12;
  272. E = R2;
  273. Ok = true;
  274. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  275. A = R12;
  276. D = R11;
  277. E = R2;
  278. Ok = true;
  279. }
  280. }
  281. // Bail if RHS was a icmp that can't be decomposed into an equality.
  282. if (!ICmpInst::isEquality(PredR))
  283. return std::nullopt;
  284. // Look for ANDs on the right side of the RHS icmp.
  285. if (!Ok) {
  286. if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
  287. R11 = R2;
  288. R12 = Constant::getAllOnesValue(R2->getType());
  289. }
  290. if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
  291. A = R11;
  292. D = R12;
  293. E = R1;
  294. Ok = true;
  295. } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
  296. A = R12;
  297. D = R11;
  298. E = R1;
  299. Ok = true;
  300. } else {
  301. return std::nullopt;
  302. }
  303. assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
  304. }
  305. if (L11 == A) {
  306. B = L12;
  307. C = L2;
  308. } else if (L12 == A) {
  309. B = L11;
  310. C = L2;
  311. } else if (L21 == A) {
  312. B = L22;
  313. C = L1;
  314. } else if (L22 == A) {
  315. B = L21;
  316. C = L1;
  317. }
  318. unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
  319. unsigned RightType = getMaskedICmpType(A, D, E, PredR);
  320. return std::optional<std::pair<unsigned, unsigned>>(
  321. std::make_pair(LeftType, RightType));
  322. }
  323. /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
  324. /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
  325. /// and the right hand side is of type BMask_Mixed. For example,
  326. /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
  327. /// Also used for logical and/or, must be poison safe.
  328. static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  329. ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
  330. Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
  331. InstCombiner::BuilderTy &Builder) {
  332. // We are given the canonical form:
  333. // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
  334. // where D & E == E.
  335. //
  336. // If IsAnd is false, we get it in negated form:
  337. // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
  338. // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
  339. //
  340. // We currently handle the case of B, C, D, E are constant.
  341. //
  342. const APInt *BCst, *CCst, *DCst, *OrigECst;
  343. if (!match(B, m_APInt(BCst)) || !match(C, m_APInt(CCst)) ||
  344. !match(D, m_APInt(DCst)) || !match(E, m_APInt(OrigECst)))
  345. return nullptr;
  346. ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  347. // Update E to the canonical form when D is a power of two and RHS is
  348. // canonicalized as,
  349. // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
  350. // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
  351. APInt ECst = *OrigECst;
  352. if (PredR != NewCC)
  353. ECst ^= *DCst;
  354. // If B or D is zero, skip because if LHS or RHS can be trivially folded by
  355. // other folding rules and this pattern won't apply any more.
  356. if (*BCst == 0 || *DCst == 0)
  357. return nullptr;
  358. // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
  359. // deduce anything from it.
  360. // For example,
  361. // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
  362. if ((*BCst & *DCst) == 0)
  363. return nullptr;
  364. // If the following two conditions are met:
  365. //
  366. // 1. mask B covers only a single bit that's not covered by mask D, that is,
  367. // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
  368. // B and D has only one bit set) and,
  369. //
  370. // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
  371. // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
  372. //
  373. // then that single bit in B must be one and thus the whole expression can be
  374. // folded to
  375. // (A & (B | D)) == (B & (B ^ D)) | E.
  376. //
  377. // For example,
  378. // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
  379. // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
  380. if ((((*BCst & *DCst) & ECst) == 0) &&
  381. (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
  382. APInt BorD = *BCst | *DCst;
  383. APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
  384. Value *NewMask = ConstantInt::get(A->getType(), BorD);
  385. Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
  386. Value *NewAnd = Builder.CreateAnd(A, NewMask);
  387. return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
  388. }
  389. auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
  390. return (*C1 & *C2) == *C1;
  391. };
  392. auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
  393. return (*C1 & *C2) == *C2;
  394. };
  395. // In the following, we consider only the cases where B is a superset of D, B
  396. // is a subset of D, or B == D because otherwise there's at least one bit
  397. // covered by B but not D, in which case we can't deduce much from it, so
  398. // no folding (aside from the single must-be-one bit case right above.)
  399. // For example,
  400. // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
  401. if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
  402. return nullptr;
  403. // At this point, either B is a superset of D, B is a subset of D or B == D.
  404. // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
  405. // and the whole expression becomes false (or true if negated), otherwise, no
  406. // folding.
  407. // For example,
  408. // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
  409. // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
  410. if (ECst.isZero()) {
  411. if (IsSubSetOrEqual(BCst, DCst))
  412. return ConstantInt::get(LHS->getType(), !IsAnd);
  413. return nullptr;
  414. }
  415. // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
  416. // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
  417. // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
  418. // RHS. For example,
  419. // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  420. // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  421. if (IsSuperSetOrEqual(BCst, DCst))
  422. return RHS;
  423. // Otherwise, B is a subset of D. If B and E have a common bit set,
  424. // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
  425. // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
  426. assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
  427. if ((*BCst & ECst) != 0)
  428. return RHS;
  429. // Otherwise, LHS and RHS contradict and the whole expression becomes false
  430. // (or true if negated.) For example,
  431. // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
  432. // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
  433. return ConstantInt::get(LHS->getType(), !IsAnd);
  434. }
  435. /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
  436. /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
  437. /// aren't of the common mask pattern type.
  438. /// Also used for logical and/or, must be poison safe.
  439. static Value *foldLogOpOfMaskedICmpsAsymmetric(
  440. ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
  441. Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
  442. unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
  443. assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
  444. "Expected equality predicates for masked type of icmps.");
  445. // Handle Mask_NotAllZeros-BMask_Mixed cases.
  446. // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
  447. // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
  448. // which gets swapped to
  449. // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
  450. if (!IsAnd) {
  451. LHSMask = conjugateICmpMask(LHSMask);
  452. RHSMask = conjugateICmpMask(RHSMask);
  453. }
  454. if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
  455. if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  456. LHS, RHS, IsAnd, A, B, C, D, E,
  457. PredL, PredR, Builder)) {
  458. return V;
  459. }
  460. } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
  461. if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
  462. RHS, LHS, IsAnd, A, D, E, B, C,
  463. PredR, PredL, Builder)) {
  464. return V;
  465. }
  466. }
  467. return nullptr;
  468. }
  469. /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
  470. /// into a single (icmp(A & X) ==/!= Y).
  471. static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
  472. bool IsLogical,
  473. InstCombiner::BuilderTy &Builder) {
  474. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
  475. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  476. std::optional<std::pair<unsigned, unsigned>> MaskPair =
  477. getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
  478. if (!MaskPair)
  479. return nullptr;
  480. assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
  481. "Expected equality predicates for masked type of icmps.");
  482. unsigned LHSMask = MaskPair->first;
  483. unsigned RHSMask = MaskPair->second;
  484. unsigned Mask = LHSMask & RHSMask;
  485. if (Mask == 0) {
  486. // Even if the two sides don't share a common pattern, check if folding can
  487. // still happen.
  488. if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
  489. LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
  490. Builder))
  491. return V;
  492. return nullptr;
  493. }
  494. // In full generality:
  495. // (icmp (A & B) Op C) | (icmp (A & D) Op E)
  496. // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
  497. //
  498. // If the latter can be converted into (icmp (A & X) Op Y) then the former is
  499. // equivalent to (icmp (A & X) !Op Y).
  500. //
  501. // Therefore, we can pretend for the rest of this function that we're dealing
  502. // with the conjunction, provided we flip the sense of any comparisons (both
  503. // input and output).
  504. // In most cases we're going to produce an EQ for the "&&" case.
  505. ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  506. if (!IsAnd) {
  507. // Convert the masking analysis into its equivalent with negated
  508. // comparisons.
  509. Mask = conjugateICmpMask(Mask);
  510. }
  511. if (Mask & Mask_AllZeros) {
  512. // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
  513. // -> (icmp eq (A & (B|D)), 0)
  514. if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
  515. return nullptr; // TODO: Use freeze?
  516. Value *NewOr = Builder.CreateOr(B, D);
  517. Value *NewAnd = Builder.CreateAnd(A, NewOr);
  518. // We can't use C as zero because we might actually handle
  519. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  520. // with B and D, having a single bit set.
  521. Value *Zero = Constant::getNullValue(A->getType());
  522. return Builder.CreateICmp(NewCC, NewAnd, Zero);
  523. }
  524. if (Mask & BMask_AllOnes) {
  525. // (icmp eq (A & B), B) & (icmp eq (A & D), D)
  526. // -> (icmp eq (A & (B|D)), (B|D))
  527. if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
  528. return nullptr; // TODO: Use freeze?
  529. Value *NewOr = Builder.CreateOr(B, D);
  530. Value *NewAnd = Builder.CreateAnd(A, NewOr);
  531. return Builder.CreateICmp(NewCC, NewAnd, NewOr);
  532. }
  533. if (Mask & AMask_AllOnes) {
  534. // (icmp eq (A & B), A) & (icmp eq (A & D), A)
  535. // -> (icmp eq (A & (B&D)), A)
  536. if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
  537. return nullptr; // TODO: Use freeze?
  538. Value *NewAnd1 = Builder.CreateAnd(B, D);
  539. Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
  540. return Builder.CreateICmp(NewCC, NewAnd2, A);
  541. }
  542. // Remaining cases assume at least that B and D are constant, and depend on
  543. // their actual values. This isn't strictly necessary, just a "handle the
  544. // easy cases for now" decision.
  545. const APInt *ConstB, *ConstD;
  546. if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
  547. return nullptr;
  548. if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
  549. // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
  550. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  551. // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
  552. // Only valid if one of the masks is a superset of the other (check "B&D" is
  553. // the same as either B or D).
  554. APInt NewMask = *ConstB & *ConstD;
  555. if (NewMask == *ConstB)
  556. return LHS;
  557. else if (NewMask == *ConstD)
  558. return RHS;
  559. }
  560. if (Mask & AMask_NotAllOnes) {
  561. // (icmp ne (A & B), B) & (icmp ne (A & D), D)
  562. // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
  563. // Only valid if one of the masks is a superset of the other (check "B|D" is
  564. // the same as either B or D).
  565. APInt NewMask = *ConstB | *ConstD;
  566. if (NewMask == *ConstB)
  567. return LHS;
  568. else if (NewMask == *ConstD)
  569. return RHS;
  570. }
  571. if (Mask & BMask_Mixed) {
  572. // (icmp eq (A & B), C) & (icmp eq (A & D), E)
  573. // We already know that B & C == C && D & E == E.
  574. // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
  575. // C and E, which are shared by both the mask B and the mask D, don't
  576. // contradict, then we can transform to
  577. // -> (icmp eq (A & (B|D)), (C|E))
  578. // Currently, we only handle the case of B, C, D, and E being constant.
  579. // We can't simply use C and E because we might actually handle
  580. // (icmp ne (A & B), B) & (icmp eq (A & D), D)
  581. // with B and D, having a single bit set.
  582. const APInt *OldConstC, *OldConstE;
  583. if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
  584. return nullptr;
  585. const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC;
  586. const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE;
  587. // If there is a conflict, we should actually return a false for the
  588. // whole construct.
  589. if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
  590. return ConstantInt::get(LHS->getType(), !IsAnd);
  591. Value *NewOr1 = Builder.CreateOr(B, D);
  592. Value *NewAnd = Builder.CreateAnd(A, NewOr1);
  593. Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE);
  594. return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
  595. }
  596. return nullptr;
  597. }
  598. /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
  599. /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
  600. /// If \p Inverted is true then the check is for the inverted range, e.g.
  601. /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
  602. Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
  603. bool Inverted) {
  604. // Check the lower range comparison, e.g. x >= 0
  605. // InstCombine already ensured that if there is a constant it's on the RHS.
  606. ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
  607. if (!RangeStart)
  608. return nullptr;
  609. ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
  610. Cmp0->getPredicate());
  611. // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
  612. if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
  613. (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
  614. return nullptr;
  615. ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
  616. Cmp1->getPredicate());
  617. Value *Input = Cmp0->getOperand(0);
  618. Value *RangeEnd;
  619. if (Cmp1->getOperand(0) == Input) {
  620. // For the upper range compare we have: icmp x, n
  621. RangeEnd = Cmp1->getOperand(1);
  622. } else if (Cmp1->getOperand(1) == Input) {
  623. // For the upper range compare we have: icmp n, x
  624. RangeEnd = Cmp1->getOperand(0);
  625. Pred1 = ICmpInst::getSwappedPredicate(Pred1);
  626. } else {
  627. return nullptr;
  628. }
  629. // Check the upper range comparison, e.g. x < n
  630. ICmpInst::Predicate NewPred;
  631. switch (Pred1) {
  632. case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
  633. case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
  634. default: return nullptr;
  635. }
  636. // This simplification is only valid if the upper range is not negative.
  637. KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
  638. if (!Known.isNonNegative())
  639. return nullptr;
  640. if (Inverted)
  641. NewPred = ICmpInst::getInversePredicate(NewPred);
  642. return Builder.CreateICmp(NewPred, Input, RangeEnd);
  643. }
  644. // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
  645. // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
  646. Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
  647. ICmpInst *RHS,
  648. Instruction *CxtI,
  649. bool IsAnd,
  650. bool IsLogical) {
  651. CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
  652. if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
  653. return nullptr;
  654. if (!match(LHS->getOperand(1), m_Zero()) ||
  655. !match(RHS->getOperand(1), m_Zero()))
  656. return nullptr;
  657. Value *L1, *L2, *R1, *R2;
  658. if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
  659. match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
  660. if (L1 == R2 || L2 == R2)
  661. std::swap(R1, R2);
  662. if (L2 == R1)
  663. std::swap(L1, L2);
  664. if (L1 == R1 &&
  665. isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
  666. isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
  667. // If this is a logical and/or, then we must prevent propagation of a
  668. // poison value from the RHS by inserting freeze.
  669. if (IsLogical)
  670. R2 = Builder.CreateFreeze(R2);
  671. Value *Mask = Builder.CreateOr(L2, R2);
  672. Value *Masked = Builder.CreateAnd(L1, Mask);
  673. auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
  674. return Builder.CreateICmp(NewPred, Masked, Mask);
  675. }
  676. }
  677. return nullptr;
  678. }
  679. /// General pattern:
  680. /// X & Y
  681. ///
  682. /// Where Y is checking that all the high bits (covered by a mask 4294967168)
  683. /// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
  684. /// Pattern can be one of:
  685. /// %t = add i32 %arg, 128
  686. /// %r = icmp ult i32 %t, 256
  687. /// Or
  688. /// %t0 = shl i32 %arg, 24
  689. /// %t1 = ashr i32 %t0, 24
  690. /// %r = icmp eq i32 %t1, %arg
  691. /// Or
  692. /// %t0 = trunc i32 %arg to i8
  693. /// %t1 = sext i8 %t0 to i32
  694. /// %r = icmp eq i32 %t1, %arg
  695. /// This pattern is a signed truncation check.
  696. ///
  697. /// And X is checking that some bit in that same mask is zero.
  698. /// I.e. can be one of:
  699. /// %r = icmp sgt i32 %arg, -1
  700. /// Or
  701. /// %t = and i32 %arg, 2147483648
  702. /// %r = icmp eq i32 %t, 0
  703. ///
  704. /// Since we are checking that all the bits in that mask are the same,
  705. /// and a particular bit is zero, what we are really checking is that all the
  706. /// masked bits are zero.
  707. /// So this should be transformed to:
  708. /// %r = icmp ult i32 %arg, 128
  709. static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
  710. Instruction &CxtI,
  711. InstCombiner::BuilderTy &Builder) {
  712. assert(CxtI.getOpcode() == Instruction::And);
  713. // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
  714. auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
  715. APInt &SignBitMask) -> bool {
  716. CmpInst::Predicate Pred;
  717. const APInt *I01, *I1; // powers of two; I1 == I01 << 1
  718. if (!(match(ICmp,
  719. m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
  720. Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
  721. return false;
  722. // Which bit is the new sign bit as per the 'signed truncation' pattern?
  723. SignBitMask = *I01;
  724. return true;
  725. };
  726. // One icmp needs to be 'signed truncation check'.
  727. // We need to match this first, else we will mismatch commutative cases.
  728. Value *X1;
  729. APInt HighestBit;
  730. ICmpInst *OtherICmp;
  731. if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
  732. OtherICmp = ICmp0;
  733. else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
  734. OtherICmp = ICmp1;
  735. else
  736. return nullptr;
  737. assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
  738. // Try to match/decompose into: icmp eq (X & Mask), 0
  739. auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
  740. APInt &UnsetBitsMask) -> bool {
  741. CmpInst::Predicate Pred = ICmp->getPredicate();
  742. // Can it be decomposed into icmp eq (X & Mask), 0 ?
  743. if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
  744. Pred, X, UnsetBitsMask,
  745. /*LookThroughTrunc=*/false) &&
  746. Pred == ICmpInst::ICMP_EQ)
  747. return true;
  748. // Is it icmp eq (X & Mask), 0 already?
  749. const APInt *Mask;
  750. if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
  751. Pred == ICmpInst::ICMP_EQ) {
  752. UnsetBitsMask = *Mask;
  753. return true;
  754. }
  755. return false;
  756. };
  757. // And the other icmp needs to be decomposable into a bit test.
  758. Value *X0;
  759. APInt UnsetBitsMask;
  760. if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
  761. return nullptr;
  762. assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
  763. // Are they working on the same value?
  764. Value *X;
  765. if (X1 == X0) {
  766. // Ok as is.
  767. X = X1;
  768. } else if (match(X0, m_Trunc(m_Specific(X1)))) {
  769. UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
  770. X = X1;
  771. } else
  772. return nullptr;
  773. // So which bits should be uniform as per the 'signed truncation check'?
  774. // (all the bits starting with (i.e. including) HighestBit)
  775. APInt SignBitsMask = ~(HighestBit - 1U);
  776. // UnsetBitsMask must have some common bits with SignBitsMask,
  777. if (!UnsetBitsMask.intersects(SignBitsMask))
  778. return nullptr;
  779. // Does UnsetBitsMask contain any bits outside of SignBitsMask?
  780. if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
  781. APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
  782. if (!OtherHighestBit.isPowerOf2())
  783. return nullptr;
  784. HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
  785. }
  786. // Else, if it does not, then all is ok as-is.
  787. // %r = icmp ult %X, SignBit
  788. return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
  789. CxtI.getName() + ".simplified");
  790. }
  791. /// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
  792. /// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
  793. /// Also used for logical and/or, must be poison safe.
  794. static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
  795. InstCombiner::BuilderTy &Builder) {
  796. CmpInst::Predicate Pred0, Pred1;
  797. Value *X;
  798. if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
  799. m_SpecificInt(1))) ||
  800. !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
  801. return nullptr;
  802. Value *CtPop = Cmp0->getOperand(0);
  803. if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
  804. return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
  805. if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
  806. return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
  807. return nullptr;
  808. }
  809. /// Reduce a pair of compares that check if a value has exactly 1 bit set.
  810. /// Also used for logical and/or, must be poison safe.
  811. static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
  812. InstCombiner::BuilderTy &Builder) {
  813. // Handle 'and' / 'or' commutation: make the equality check the first operand.
  814. if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
  815. std::swap(Cmp0, Cmp1);
  816. else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
  817. std::swap(Cmp0, Cmp1);
  818. // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
  819. CmpInst::Predicate Pred0, Pred1;
  820. Value *X;
  821. if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
  822. match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
  823. m_SpecificInt(2))) &&
  824. Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
  825. Value *CtPop = Cmp1->getOperand(0);
  826. return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
  827. }
  828. // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
  829. if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
  830. match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
  831. m_SpecificInt(1))) &&
  832. Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
  833. Value *CtPop = Cmp1->getOperand(0);
  834. return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
  835. }
  836. return nullptr;
  837. }
  838. /// Commuted variants are assumed to be handled by calling this function again
  839. /// with the parameters swapped.
  840. static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
  841. ICmpInst *UnsignedICmp, bool IsAnd,
  842. const SimplifyQuery &Q,
  843. InstCombiner::BuilderTy &Builder) {
  844. Value *ZeroCmpOp;
  845. ICmpInst::Predicate EqPred;
  846. if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
  847. !ICmpInst::isEquality(EqPred))
  848. return nullptr;
  849. auto IsKnownNonZero = [&](Value *V) {
  850. return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
  851. };
  852. ICmpInst::Predicate UnsignedPred;
  853. Value *A, *B;
  854. if (match(UnsignedICmp,
  855. m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
  856. match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
  857. (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
  858. auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
  859. if (!IsKnownNonZero(NonZero))
  860. std::swap(NonZero, Other);
  861. return IsKnownNonZero(NonZero);
  862. };
  863. // Given ZeroCmpOp = (A + B)
  864. // ZeroCmpOp < A && ZeroCmpOp != 0 --> (0-X) < Y iff
  865. // ZeroCmpOp >= A || ZeroCmpOp == 0 --> (0-X) >= Y iff
  866. // with X being the value (A/B) that is known to be non-zero,
  867. // and Y being remaining value.
  868. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
  869. IsAnd && GetKnownNonZeroAndOther(B, A))
  870. return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
  871. if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
  872. !IsAnd && GetKnownNonZeroAndOther(B, A))
  873. return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
  874. }
  875. Value *Base, *Offset;
  876. if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
  877. return nullptr;
  878. if (!match(UnsignedICmp,
  879. m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
  880. !ICmpInst::isUnsigned(UnsignedPred))
  881. return nullptr;
  882. // Base >=/> Offset && (Base - Offset) != 0 <--> Base > Offset
  883. // (no overflow and not null)
  884. if ((UnsignedPred == ICmpInst::ICMP_UGE ||
  885. UnsignedPred == ICmpInst::ICMP_UGT) &&
  886. EqPred == ICmpInst::ICMP_NE && IsAnd)
  887. return Builder.CreateICmpUGT(Base, Offset);
  888. // Base <=/< Offset || (Base - Offset) == 0 <--> Base <= Offset
  889. // (overflow or null)
  890. if ((UnsignedPred == ICmpInst::ICMP_ULE ||
  891. UnsignedPred == ICmpInst::ICMP_ULT) &&
  892. EqPred == ICmpInst::ICMP_EQ && !IsAnd)
  893. return Builder.CreateICmpULE(Base, Offset);
  894. // Base <= Offset && (Base - Offset) != 0 --> Base < Offset
  895. if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
  896. IsAnd)
  897. return Builder.CreateICmpULT(Base, Offset);
  898. // Base > Offset || (Base - Offset) == 0 --> Base >= Offset
  899. if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
  900. !IsAnd)
  901. return Builder.CreateICmpUGE(Base, Offset);
  902. return nullptr;
  903. }
  904. struct IntPart {
  905. Value *From;
  906. unsigned StartBit;
  907. unsigned NumBits;
  908. };
  909. /// Match an extraction of bits from an integer.
  910. static std::optional<IntPart> matchIntPart(Value *V) {
  911. Value *X;
  912. if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
  913. return std::nullopt;
  914. unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
  915. unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
  916. Value *Y;
  917. const APInt *Shift;
  918. // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
  919. // from Y, not any shifted-in zeroes.
  920. if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
  921. Shift->ule(NumOriginalBits - NumExtractedBits))
  922. return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
  923. return {{X, 0, NumExtractedBits}};
  924. }
  925. /// Materialize an extraction of bits from an integer in IR.
  926. static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
  927. Value *V = P.From;
  928. if (P.StartBit)
  929. V = Builder.CreateLShr(V, P.StartBit);
  930. Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
  931. if (TruncTy != V->getType())
  932. V = Builder.CreateTrunc(V, TruncTy);
  933. return V;
  934. }
  935. /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
  936. /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
  937. /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
  938. Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
  939. bool IsAnd) {
  940. if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
  941. return nullptr;
  942. CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
  943. if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
  944. return nullptr;
  945. std::optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
  946. std::optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
  947. std::optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
  948. std::optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
  949. if (!L0 || !R0 || !L1 || !R1)
  950. return nullptr;
  951. // Make sure the LHS/RHS compare a part of the same value, possibly after
  952. // an operand swap.
  953. if (L0->From != L1->From || R0->From != R1->From) {
  954. if (L0->From != R1->From || R0->From != L1->From)
  955. return nullptr;
  956. std::swap(L1, R1);
  957. }
  958. // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
  959. // the low part and L1/R1 being the high part.
  960. if (L0->StartBit + L0->NumBits != L1->StartBit ||
  961. R0->StartBit + R0->NumBits != R1->StartBit) {
  962. if (L1->StartBit + L1->NumBits != L0->StartBit ||
  963. R1->StartBit + R1->NumBits != R0->StartBit)
  964. return nullptr;
  965. std::swap(L0, L1);
  966. std::swap(R0, R1);
  967. }
  968. // We can simplify to a comparison of these larger parts of the integers.
  969. IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
  970. IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
  971. Value *LValue = extractIntPart(L, Builder);
  972. Value *RValue = extractIntPart(R, Builder);
  973. return Builder.CreateICmp(Pred, LValue, RValue);
  974. }
  975. /// Reduce logic-of-compares with equality to a constant by substituting a
  976. /// common operand with the constant. Callers are expected to call this with
  977. /// Cmp0/Cmp1 switched to handle logic op commutativity.
  978. static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
  979. bool IsAnd, bool IsLogical,
  980. InstCombiner::BuilderTy &Builder,
  981. const SimplifyQuery &Q) {
  982. // Match an equality compare with a non-poison constant as Cmp0.
  983. // Also, give up if the compare can be constant-folded to avoid looping.
  984. ICmpInst::Predicate Pred0;
  985. Value *X;
  986. Constant *C;
  987. if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
  988. !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
  989. return nullptr;
  990. if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
  991. (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
  992. return nullptr;
  993. // The other compare must include a common operand (X). Canonicalize the
  994. // common operand as operand 1 (Pred1 is swapped if the common operand was
  995. // operand 0).
  996. Value *Y;
  997. ICmpInst::Predicate Pred1;
  998. if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
  999. return nullptr;
  1000. // Replace variable with constant value equivalence to remove a variable use:
  1001. // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
  1002. // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
  1003. // Can think of the 'or' substitution with the 'and' bool equivalent:
  1004. // A || B --> A || (!A && B)
  1005. Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
  1006. if (!SubstituteCmp) {
  1007. // If we need to create a new instruction, require that the old compare can
  1008. // be removed.
  1009. if (!Cmp1->hasOneUse())
  1010. return nullptr;
  1011. SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
  1012. }
  1013. if (IsLogical)
  1014. return IsAnd ? Builder.CreateLogicalAnd(Cmp0, SubstituteCmp)
  1015. : Builder.CreateLogicalOr(Cmp0, SubstituteCmp);
  1016. return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
  1017. SubstituteCmp);
  1018. }
  1019. /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
  1020. /// or (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
  1021. /// into a single comparison using range-based reasoning.
  1022. /// NOTE: This is also used for logical and/or, must be poison-safe!
  1023. Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
  1024. ICmpInst *ICmp2,
  1025. bool IsAnd) {
  1026. ICmpInst::Predicate Pred1, Pred2;
  1027. Value *V1, *V2;
  1028. const APInt *C1, *C2;
  1029. if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
  1030. !match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
  1031. return nullptr;
  1032. // Look through add of a constant offset on V1, V2, or both operands. This
  1033. // allows us to interpret the V + C' < C'' range idiom into a proper range.
  1034. const APInt *Offset1 = nullptr, *Offset2 = nullptr;
  1035. if (V1 != V2) {
  1036. Value *X;
  1037. if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
  1038. V1 = X;
  1039. if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
  1040. V2 = X;
  1041. }
  1042. if (V1 != V2)
  1043. return nullptr;
  1044. ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
  1045. IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
  1046. if (Offset1)
  1047. CR1 = CR1.subtract(*Offset1);
  1048. ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
  1049. IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
  1050. if (Offset2)
  1051. CR2 = CR2.subtract(*Offset2);
  1052. Type *Ty = V1->getType();
  1053. Value *NewV = V1;
  1054. std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
  1055. if (!CR) {
  1056. if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
  1057. CR2.isWrappedSet())
  1058. return nullptr;
  1059. // Check whether we have equal-size ranges that only differ by one bit.
  1060. // In that case we can apply a mask to map one range onto the other.
  1061. APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
  1062. APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
  1063. APInt CR1Size = CR1.getUpper() - CR1.getLower();
  1064. if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
  1065. CR1Size != CR2.getUpper() - CR2.getLower())
  1066. return nullptr;
  1067. CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
  1068. NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
  1069. }
  1070. if (IsAnd)
  1071. CR = CR->inverse();
  1072. CmpInst::Predicate NewPred;
  1073. APInt NewC, Offset;
  1074. CR->getEquivalentICmp(NewPred, NewC, Offset);
  1075. if (Offset != 0)
  1076. NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
  1077. return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
  1078. }
  1079. /// Ignore all operations which only change the sign of a value, returning the
  1080. /// underlying magnitude value.
  1081. static Value *stripSignOnlyFPOps(Value *Val) {
  1082. match(Val, m_FNeg(m_Value(Val)));
  1083. match(Val, m_FAbs(m_Value(Val)));
  1084. match(Val, m_CopySign(m_Value(Val), m_Value()));
  1085. return Val;
  1086. }
  1087. /// Matches canonical form of isnan, fcmp ord x, 0
  1088. static bool matchIsNotNaN(FCmpInst::Predicate P, Value *LHS, Value *RHS) {
  1089. return P == FCmpInst::FCMP_ORD && match(RHS, m_AnyZeroFP());
  1090. }
  1091. /// Matches fcmp u__ x, +/-inf
  1092. static bool matchUnorderedInfCompare(FCmpInst::Predicate P, Value *LHS,
  1093. Value *RHS) {
  1094. return FCmpInst::isUnordered(P) && match(RHS, m_Inf());
  1095. }
  1096. /// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
  1097. ///
  1098. /// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
  1099. static Value *matchIsFiniteTest(InstCombiner::BuilderTy &Builder, FCmpInst *LHS,
  1100. FCmpInst *RHS) {
  1101. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  1102. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  1103. FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  1104. if (!matchIsNotNaN(PredL, LHS0, LHS1) ||
  1105. !matchUnorderedInfCompare(PredR, RHS0, RHS1))
  1106. return nullptr;
  1107. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  1108. FastMathFlags FMF = LHS->getFastMathFlags();
  1109. FMF &= RHS->getFastMathFlags();
  1110. Builder.setFastMathFlags(FMF);
  1111. return Builder.CreateFCmp(FCmpInst::getOrderedPredicate(PredR), RHS0, RHS1);
  1112. }
  1113. Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
  1114. bool IsAnd, bool IsLogicalSelect) {
  1115. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  1116. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  1117. FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  1118. if (LHS0 == RHS1 && RHS0 == LHS1) {
  1119. // Swap RHS operands to match LHS.
  1120. PredR = FCmpInst::getSwappedPredicate(PredR);
  1121. std::swap(RHS0, RHS1);
  1122. }
  1123. // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
  1124. // Suppose the relation between x and y is R, where R is one of
  1125. // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
  1126. // testing the desired relations.
  1127. //
  1128. // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
  1129. // bool(R & CC0) && bool(R & CC1)
  1130. // = bool((R & CC0) & (R & CC1))
  1131. // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
  1132. //
  1133. // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
  1134. // bool(R & CC0) || bool(R & CC1)
  1135. // = bool((R & CC0) | (R & CC1))
  1136. // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
  1137. if (LHS0 == RHS0 && LHS1 == RHS1) {
  1138. unsigned FCmpCodeL = getFCmpCode(PredL);
  1139. unsigned FCmpCodeR = getFCmpCode(PredR);
  1140. unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
  1141. // Intersect the fast math flags.
  1142. // TODO: We can union the fast math flags unless this is a logical select.
  1143. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  1144. FastMathFlags FMF = LHS->getFastMathFlags();
  1145. FMF &= RHS->getFastMathFlags();
  1146. Builder.setFastMathFlags(FMF);
  1147. return getFCmpValue(NewPred, LHS0, LHS1, Builder);
  1148. }
  1149. // This transform is not valid for a logical select.
  1150. if (!IsLogicalSelect &&
  1151. ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
  1152. (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
  1153. !IsAnd))) {
  1154. if (LHS0->getType() != RHS0->getType())
  1155. return nullptr;
  1156. // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
  1157. // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
  1158. if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
  1159. // Ignore the constants because they are obviously not NANs:
  1160. // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
  1161. // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
  1162. return Builder.CreateFCmp(PredL, LHS0, RHS0);
  1163. }
  1164. if (IsAnd && stripSignOnlyFPOps(LHS0) == stripSignOnlyFPOps(RHS0)) {
  1165. // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
  1166. // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
  1167. if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
  1168. return Left;
  1169. if (Value *Right = matchIsFiniteTest(Builder, RHS, LHS))
  1170. return Right;
  1171. }
  1172. return nullptr;
  1173. }
  1174. /// or (is_fpclass x, mask0), (is_fpclass x, mask1)
  1175. /// -> is_fpclass x, (mask0 | mask1)
  1176. /// and (is_fpclass x, mask0), (is_fpclass x, mask1)
  1177. /// -> is_fpclass x, (mask0 & mask1)
  1178. /// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
  1179. /// -> is_fpclass x, (mask0 ^ mask1)
  1180. Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
  1181. Value *Op0, Value *Op1) {
  1182. Value *ClassVal;
  1183. uint64_t ClassMask0, ClassMask1;
  1184. if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
  1185. m_Value(ClassVal), m_ConstantInt(ClassMask0)))) &&
  1186. match(Op1, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
  1187. m_Specific(ClassVal), m_ConstantInt(ClassMask1))))) {
  1188. unsigned NewClassMask;
  1189. switch (BO.getOpcode()) {
  1190. case Instruction::And:
  1191. NewClassMask = ClassMask0 & ClassMask1;
  1192. break;
  1193. case Instruction::Or:
  1194. NewClassMask = ClassMask0 | ClassMask1;
  1195. break;
  1196. case Instruction::Xor:
  1197. NewClassMask = ClassMask0 ^ ClassMask1;
  1198. break;
  1199. default:
  1200. llvm_unreachable("not a binary logic operator");
  1201. }
  1202. // TODO: Also check for special fcmps
  1203. auto *II = cast<IntrinsicInst>(Op0);
  1204. II->setArgOperand(
  1205. 1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
  1206. return replaceInstUsesWith(BO, II);
  1207. }
  1208. return nullptr;
  1209. }
  1210. /// Look for the pattern that conditionally negates a value via math operations:
  1211. /// cond.splat = sext i1 cond
  1212. /// sub = add cond.splat, x
  1213. /// xor = xor sub, cond.splat
  1214. /// and rewrite it to do the same, but via logical operations:
  1215. /// value.neg = sub 0, value
  1216. /// cond = select i1 neg, value.neg, value
  1217. Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
  1218. BinaryOperator &I) {
  1219. assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
  1220. Value *Cond, *X;
  1221. // As per complexity ordering, `xor` is not commutative here.
  1222. if (!match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())) ||
  1223. !match(I.getOperand(1), m_SExt(m_Value(Cond))) ||
  1224. !Cond->getType()->isIntOrIntVectorTy(1) ||
  1225. !match(I.getOperand(0), m_c_Add(m_SExt(m_Deferred(Cond)), m_Value(X))))
  1226. return nullptr;
  1227. return SelectInst::Create(Cond, Builder.CreateNeg(X, X->getName() + ".neg"),
  1228. X);
  1229. }
  1230. /// This a limited reassociation for a special case (see above) where we are
  1231. /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
  1232. /// This could be handled more generally in '-reassociation', but it seems like
  1233. /// an unlikely pattern for a large number of logic ops and fcmps.
  1234. static Instruction *reassociateFCmps(BinaryOperator &BO,
  1235. InstCombiner::BuilderTy &Builder) {
  1236. Instruction::BinaryOps Opcode = BO.getOpcode();
  1237. assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
  1238. "Expecting and/or op for fcmp transform");
  1239. // There are 4 commuted variants of the pattern. Canonicalize operands of this
  1240. // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
  1241. Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
  1242. FCmpInst::Predicate Pred;
  1243. if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
  1244. std::swap(Op0, Op1);
  1245. // Match inner binop and the predicate for combining 2 NAN checks into 1.
  1246. Value *BO10, *BO11;
  1247. FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
  1248. : FCmpInst::FCMP_UNO;
  1249. if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
  1250. !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
  1251. return nullptr;
  1252. // The inner logic op must have a matching fcmp operand.
  1253. Value *Y;
  1254. if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
  1255. Pred != NanPred || X->getType() != Y->getType())
  1256. std::swap(BO10, BO11);
  1257. if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
  1258. Pred != NanPred || X->getType() != Y->getType())
  1259. return nullptr;
  1260. // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
  1261. // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z
  1262. Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
  1263. if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
  1264. // Intersect FMF from the 2 source fcmps.
  1265. NewFCmpInst->copyIRFlags(Op0);
  1266. NewFCmpInst->andIRFlags(BO10);
  1267. }
  1268. return BinaryOperator::Create(Opcode, NewFCmp, BO11);
  1269. }
  1270. /// Match variations of De Morgan's Laws:
  1271. /// (~A & ~B) == (~(A | B))
  1272. /// (~A | ~B) == (~(A & B))
  1273. static Instruction *matchDeMorgansLaws(BinaryOperator &I,
  1274. InstCombiner::BuilderTy &Builder) {
  1275. const Instruction::BinaryOps Opcode = I.getOpcode();
  1276. assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
  1277. "Trying to match De Morgan's Laws with something other than and/or");
  1278. // Flip the logic operation.
  1279. const Instruction::BinaryOps FlippedOpcode =
  1280. (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
  1281. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1282. Value *A, *B;
  1283. if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
  1284. match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
  1285. !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
  1286. !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
  1287. Value *AndOr =
  1288. Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
  1289. return BinaryOperator::CreateNot(AndOr);
  1290. }
  1291. // The 'not' ops may require reassociation.
  1292. // (A & ~B) & ~C --> A & ~(B | C)
  1293. // (~B & A) & ~C --> A & ~(B | C)
  1294. // (A | ~B) | ~C --> A | ~(B & C)
  1295. // (~B | A) | ~C --> A | ~(B & C)
  1296. Value *C;
  1297. if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
  1298. match(Op1, m_Not(m_Value(C)))) {
  1299. Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
  1300. return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
  1301. }
  1302. return nullptr;
  1303. }
  1304. bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
  1305. Value *CastSrc = CI->getOperand(0);
  1306. // Noop casts and casts of constants should be eliminated trivially.
  1307. if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
  1308. return false;
  1309. // If this cast is paired with another cast that can be eliminated, we prefer
  1310. // to have it eliminated.
  1311. if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
  1312. if (isEliminableCastPair(PrecedingCI, CI))
  1313. return false;
  1314. return true;
  1315. }
  1316. /// Fold {and,or,xor} (cast X), C.
  1317. static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
  1318. InstCombiner::BuilderTy &Builder) {
  1319. Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
  1320. if (!C)
  1321. return nullptr;
  1322. auto LogicOpc = Logic.getOpcode();
  1323. Type *DestTy = Logic.getType();
  1324. Type *SrcTy = Cast->getSrcTy();
  1325. // Move the logic operation ahead of a zext or sext if the constant is
  1326. // unchanged in the smaller source type. Performing the logic in a smaller
  1327. // type may provide more information to later folds, and the smaller logic
  1328. // instruction may be cheaper (particularly in the case of vectors).
  1329. Value *X;
  1330. if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
  1331. Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
  1332. Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
  1333. if (ZextTruncC == C) {
  1334. // LogicOpc (zext X), C --> zext (LogicOpc X, C)
  1335. Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
  1336. return new ZExtInst(NewOp, DestTy);
  1337. }
  1338. }
  1339. if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
  1340. Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
  1341. Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
  1342. if (SextTruncC == C) {
  1343. // LogicOpc (sext X), C --> sext (LogicOpc X, C)
  1344. Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
  1345. return new SExtInst(NewOp, DestTy);
  1346. }
  1347. }
  1348. return nullptr;
  1349. }
  1350. /// Fold {and,or,xor} (cast X), Y.
  1351. Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
  1352. auto LogicOpc = I.getOpcode();
  1353. assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
  1354. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1355. CastInst *Cast0 = dyn_cast<CastInst>(Op0);
  1356. if (!Cast0)
  1357. return nullptr;
  1358. // This must be a cast from an integer or integer vector source type to allow
  1359. // transformation of the logic operation to the source type.
  1360. Type *DestTy = I.getType();
  1361. Type *SrcTy = Cast0->getSrcTy();
  1362. if (!SrcTy->isIntOrIntVectorTy())
  1363. return nullptr;
  1364. if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
  1365. return Ret;
  1366. CastInst *Cast1 = dyn_cast<CastInst>(Op1);
  1367. if (!Cast1)
  1368. return nullptr;
  1369. // Both operands of the logic operation are casts. The casts must be the
  1370. // same kind for reduction.
  1371. Instruction::CastOps CastOpcode = Cast0->getOpcode();
  1372. if (CastOpcode != Cast1->getOpcode())
  1373. return nullptr;
  1374. // If the source types do not match, but the casts are matching extends, we
  1375. // can still narrow the logic op.
  1376. if (SrcTy != Cast1->getSrcTy()) {
  1377. Value *X, *Y;
  1378. if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
  1379. match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
  1380. // Cast the narrower source to the wider source type.
  1381. unsigned XNumBits = X->getType()->getScalarSizeInBits();
  1382. unsigned YNumBits = Y->getType()->getScalarSizeInBits();
  1383. if (XNumBits < YNumBits)
  1384. X = Builder.CreateCast(CastOpcode, X, Y->getType());
  1385. else
  1386. Y = Builder.CreateCast(CastOpcode, Y, X->getType());
  1387. // Do the logic op in the intermediate width, then widen more.
  1388. Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
  1389. return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
  1390. }
  1391. // Give up for other cast opcodes.
  1392. return nullptr;
  1393. }
  1394. Value *Cast0Src = Cast0->getOperand(0);
  1395. Value *Cast1Src = Cast1->getOperand(0);
  1396. // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
  1397. if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
  1398. shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
  1399. Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
  1400. I.getName());
  1401. return CastInst::Create(CastOpcode, NewOp, DestTy);
  1402. }
  1403. // For now, only 'and'/'or' have optimizations after this.
  1404. if (LogicOpc == Instruction::Xor)
  1405. return nullptr;
  1406. // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
  1407. // cast is otherwise not optimizable. This happens for vector sexts.
  1408. ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
  1409. ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
  1410. if (ICmp0 && ICmp1) {
  1411. if (Value *Res =
  1412. foldAndOrOfICmps(ICmp0, ICmp1, I, LogicOpc == Instruction::And))
  1413. return CastInst::Create(CastOpcode, Res, DestTy);
  1414. return nullptr;
  1415. }
  1416. // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
  1417. // cast is otherwise not optimizable. This happens for vector sexts.
  1418. FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
  1419. FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
  1420. if (FCmp0 && FCmp1)
  1421. if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
  1422. return CastInst::Create(CastOpcode, R, DestTy);
  1423. return nullptr;
  1424. }
  1425. static Instruction *foldAndToXor(BinaryOperator &I,
  1426. InstCombiner::BuilderTy &Builder) {
  1427. assert(I.getOpcode() == Instruction::And);
  1428. Value *Op0 = I.getOperand(0);
  1429. Value *Op1 = I.getOperand(1);
  1430. Value *A, *B;
  1431. // Operand complexity canonicalization guarantees that the 'or' is Op0.
  1432. // (A | B) & ~(A & B) --> A ^ B
  1433. // (A | B) & ~(B & A) --> A ^ B
  1434. if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
  1435. m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
  1436. return BinaryOperator::CreateXor(A, B);
  1437. // (A | ~B) & (~A | B) --> ~(A ^ B)
  1438. // (A | ~B) & (B | ~A) --> ~(A ^ B)
  1439. // (~B | A) & (~A | B) --> ~(A ^ B)
  1440. // (~B | A) & (B | ~A) --> ~(A ^ B)
  1441. if (Op0->hasOneUse() || Op1->hasOneUse())
  1442. if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
  1443. m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
  1444. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  1445. return nullptr;
  1446. }
  1447. static Instruction *foldOrToXor(BinaryOperator &I,
  1448. InstCombiner::BuilderTy &Builder) {
  1449. assert(I.getOpcode() == Instruction::Or);
  1450. Value *Op0 = I.getOperand(0);
  1451. Value *Op1 = I.getOperand(1);
  1452. Value *A, *B;
  1453. // Operand complexity canonicalization guarantees that the 'and' is Op0.
  1454. // (A & B) | ~(A | B) --> ~(A ^ B)
  1455. // (A & B) | ~(B | A) --> ~(A ^ B)
  1456. if (Op0->hasOneUse() || Op1->hasOneUse())
  1457. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  1458. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
  1459. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  1460. // Operand complexity canonicalization guarantees that the 'xor' is Op0.
  1461. // (A ^ B) | ~(A | B) --> ~(A & B)
  1462. // (A ^ B) | ~(B | A) --> ~(A & B)
  1463. if (Op0->hasOneUse() || Op1->hasOneUse())
  1464. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  1465. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
  1466. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  1467. // (A & ~B) | (~A & B) --> A ^ B
  1468. // (A & ~B) | (B & ~A) --> A ^ B
  1469. // (~B & A) | (~A & B) --> A ^ B
  1470. // (~B & A) | (B & ~A) --> A ^ B
  1471. if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
  1472. match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
  1473. return BinaryOperator::CreateXor(A, B);
  1474. return nullptr;
  1475. }
  1476. /// Return true if a constant shift amount is always less than the specified
  1477. /// bit-width. If not, the shift could create poison in the narrower type.
  1478. static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
  1479. APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
  1480. return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
  1481. }
  1482. /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
  1483. /// a common zext operand: and (binop (zext X), C), (zext X).
  1484. Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
  1485. // This transform could also apply to {or, and, xor}, but there are better
  1486. // folds for those cases, so we don't expect those patterns here. AShr is not
  1487. // handled because it should always be transformed to LShr in this sequence.
  1488. // The subtract transform is different because it has a constant on the left.
  1489. // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
  1490. Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
  1491. Constant *C;
  1492. if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
  1493. !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
  1494. !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
  1495. !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
  1496. !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
  1497. return nullptr;
  1498. Value *X;
  1499. if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
  1500. return nullptr;
  1501. Type *Ty = And.getType();
  1502. if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
  1503. return nullptr;
  1504. // If we're narrowing a shift, the shift amount must be safe (less than the
  1505. // width) in the narrower type. If the shift amount is greater, instsimplify
  1506. // usually handles that case, but we can't guarantee/assert it.
  1507. Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
  1508. if (Opc == Instruction::LShr || Opc == Instruction::Shl)
  1509. if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
  1510. return nullptr;
  1511. // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
  1512. // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
  1513. Value *NewC = ConstantExpr::getTrunc(C, X->getType());
  1514. Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
  1515. : Builder.CreateBinOp(Opc, X, NewC);
  1516. return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
  1517. }
  1518. /// Try folding relatively complex patterns for both And and Or operations
  1519. /// with all And and Or swapped.
  1520. static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
  1521. InstCombiner::BuilderTy &Builder) {
  1522. const Instruction::BinaryOps Opcode = I.getOpcode();
  1523. assert(Opcode == Instruction::And || Opcode == Instruction::Or);
  1524. // Flip the logic operation.
  1525. const Instruction::BinaryOps FlippedOpcode =
  1526. (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
  1527. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1528. Value *A, *B, *C, *X, *Y, *Dummy;
  1529. // Match following expressions:
  1530. // (~(A | B) & C)
  1531. // (~(A & B) | C)
  1532. // Captures X = ~(A | B) or ~(A & B)
  1533. const auto matchNotOrAnd =
  1534. [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
  1535. Value *&X, bool CountUses = false) -> bool {
  1536. if (CountUses && !Op->hasOneUse())
  1537. return false;
  1538. if (match(Op, m_c_BinOp(FlippedOpcode,
  1539. m_CombineAnd(m_Value(X),
  1540. m_Not(m_c_BinOp(Opcode, m_A, m_B))),
  1541. m_C)))
  1542. return !CountUses || X->hasOneUse();
  1543. return false;
  1544. };
  1545. // (~(A | B) & C) | ... --> ...
  1546. // (~(A & B) | C) & ... --> ...
  1547. // TODO: One use checks are conservative. We just need to check that a total
  1548. // number of multiple used values does not exceed reduction
  1549. // in operations.
  1550. if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
  1551. // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
  1552. // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
  1553. if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
  1554. true)) {
  1555. Value *Xor = Builder.CreateXor(B, C);
  1556. return (Opcode == Instruction::Or)
  1557. ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
  1558. : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
  1559. }
  1560. // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
  1561. // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
  1562. if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
  1563. true)) {
  1564. Value *Xor = Builder.CreateXor(A, C);
  1565. return (Opcode == Instruction::Or)
  1566. ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
  1567. : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
  1568. }
  1569. // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
  1570. // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
  1571. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1572. m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
  1573. return BinaryOperator::CreateNot(Builder.CreateBinOp(
  1574. Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
  1575. // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
  1576. // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
  1577. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1578. m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
  1579. return BinaryOperator::CreateNot(Builder.CreateBinOp(
  1580. Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
  1581. // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
  1582. // Note, the pattern with swapped and/or is not handled because the
  1583. // result is more undefined than a source:
  1584. // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
  1585. if (Opcode == Instruction::Or && Op0->hasOneUse() &&
  1586. match(Op1, m_OneUse(m_Not(m_CombineAnd(
  1587. m_Value(Y),
  1588. m_c_BinOp(Opcode, m_Specific(C),
  1589. m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
  1590. // X = ~(A | B)
  1591. // Y = (C | (A ^ B)
  1592. Value *Or = cast<BinaryOperator>(X)->getOperand(0);
  1593. return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
  1594. }
  1595. }
  1596. // (~A & B & C) | ... --> ...
  1597. // (~A | B | C) | ... --> ...
  1598. // TODO: One use checks are conservative. We just need to check that a total
  1599. // number of multiple used values does not exceed reduction
  1600. // in operations.
  1601. if (match(Op0,
  1602. m_OneUse(m_c_BinOp(FlippedOpcode,
  1603. m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
  1604. m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
  1605. match(Op0, m_OneUse(m_c_BinOp(
  1606. FlippedOpcode,
  1607. m_c_BinOp(FlippedOpcode, m_Value(C),
  1608. m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
  1609. m_Value(B))))) {
  1610. // X = ~A
  1611. // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
  1612. // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
  1613. if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1614. Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
  1615. m_Specific(C))))) ||
  1616. match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1617. Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
  1618. m_Specific(A))))) ||
  1619. match(Op1, m_OneUse(m_Not(m_c_BinOp(
  1620. Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
  1621. m_Specific(B)))))) {
  1622. Value *Xor = Builder.CreateXor(B, C);
  1623. return (Opcode == Instruction::Or)
  1624. ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
  1625. : BinaryOperator::CreateOr(Xor, X);
  1626. }
  1627. // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
  1628. // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
  1629. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1630. m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
  1631. return BinaryOperator::Create(
  1632. FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
  1633. X);
  1634. // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
  1635. // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
  1636. if (match(Op1, m_OneUse(m_Not(m_OneUse(
  1637. m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
  1638. return BinaryOperator::Create(
  1639. FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
  1640. X);
  1641. }
  1642. return nullptr;
  1643. }
  1644. /// Try to reassociate a pair of binops so that values with one use only are
  1645. /// part of the same instruction. This may enable folds that are limited with
  1646. /// multi-use restrictions and makes it more likely to match other patterns that
  1647. /// are looking for a common operand.
  1648. static Instruction *reassociateForUses(BinaryOperator &BO,
  1649. InstCombinerImpl::BuilderTy &Builder) {
  1650. Instruction::BinaryOps Opcode = BO.getOpcode();
  1651. Value *X, *Y, *Z;
  1652. if (match(&BO,
  1653. m_c_BinOp(Opcode, m_OneUse(m_BinOp(Opcode, m_Value(X), m_Value(Y))),
  1654. m_OneUse(m_Value(Z))))) {
  1655. if (!isa<Constant>(X) && !isa<Constant>(Y) && !isa<Constant>(Z)) {
  1656. // (X op Y) op Z --> (Y op Z) op X
  1657. if (!X->hasOneUse()) {
  1658. Value *YZ = Builder.CreateBinOp(Opcode, Y, Z);
  1659. return BinaryOperator::Create(Opcode, YZ, X);
  1660. }
  1661. // (X op Y) op Z --> (X op Z) op Y
  1662. if (!Y->hasOneUse()) {
  1663. Value *XZ = Builder.CreateBinOp(Opcode, X, Z);
  1664. return BinaryOperator::Create(Opcode, XZ, Y);
  1665. }
  1666. }
  1667. }
  1668. return nullptr;
  1669. }
  1670. // Match
  1671. // (X + C2) | C
  1672. // (X + C2) ^ C
  1673. // (X + C2) & C
  1674. // and convert to do the bitwise logic first:
  1675. // (X | C) + C2
  1676. // (X ^ C) + C2
  1677. // (X & C) + C2
  1678. // iff bits affected by logic op are lower than last bit affected by math op
  1679. static Instruction *canonicalizeLogicFirst(BinaryOperator &I,
  1680. InstCombiner::BuilderTy &Builder) {
  1681. Type *Ty = I.getType();
  1682. Instruction::BinaryOps OpC = I.getOpcode();
  1683. Value *Op0 = I.getOperand(0);
  1684. Value *Op1 = I.getOperand(1);
  1685. Value *X;
  1686. const APInt *C, *C2;
  1687. if (!(match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C2)))) &&
  1688. match(Op1, m_APInt(C))))
  1689. return nullptr;
  1690. unsigned Width = Ty->getScalarSizeInBits();
  1691. unsigned LastOneMath = Width - C2->countTrailingZeros();
  1692. switch (OpC) {
  1693. case Instruction::And:
  1694. if (C->countLeadingOnes() < LastOneMath)
  1695. return nullptr;
  1696. break;
  1697. case Instruction::Xor:
  1698. case Instruction::Or:
  1699. if (C->countLeadingZeros() < LastOneMath)
  1700. return nullptr;
  1701. break;
  1702. default:
  1703. llvm_unreachable("Unexpected BinaryOp!");
  1704. }
  1705. Value *NewBinOp = Builder.CreateBinOp(OpC, X, ConstantInt::get(Ty, *C));
  1706. return BinaryOperator::CreateAdd(NewBinOp, ConstantInt::get(Ty, *C2));
  1707. }
  1708. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  1709. // here. We should standardize that construct where it is needed or choose some
  1710. // other way to ensure that commutated variants of patterns are not missed.
  1711. Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
  1712. Type *Ty = I.getType();
  1713. if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
  1714. SQ.getWithInstruction(&I)))
  1715. return replaceInstUsesWith(I, V);
  1716. if (SimplifyAssociativeOrCommutative(I))
  1717. return &I;
  1718. if (Instruction *X = foldVectorBinop(I))
  1719. return X;
  1720. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  1721. return Phi;
  1722. // See if we can simplify any instructions used by the instruction whose sole
  1723. // purpose is to compute bits we don't care about.
  1724. if (SimplifyDemandedInstructionBits(I))
  1725. return &I;
  1726. // Do this before using distributive laws to catch simple and/or/not patterns.
  1727. if (Instruction *Xor = foldAndToXor(I, Builder))
  1728. return Xor;
  1729. if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
  1730. return X;
  1731. // (A|B)&(A|C) -> A|(B&C) etc
  1732. if (Value *V = foldUsingDistributiveLaws(I))
  1733. return replaceInstUsesWith(I, V);
  1734. if (Value *V = SimplifyBSwap(I, Builder))
  1735. return replaceInstUsesWith(I, V);
  1736. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  1737. Value *X, *Y;
  1738. if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
  1739. match(Op1, m_One())) {
  1740. // (1 << X) & 1 --> zext(X == 0)
  1741. // (1 >> X) & 1 --> zext(X == 0)
  1742. Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
  1743. return new ZExtInst(IsZero, Ty);
  1744. }
  1745. // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
  1746. Value *Neg;
  1747. if (match(&I,
  1748. m_c_And(m_CombineAnd(m_Value(Neg),
  1749. m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
  1750. m_Value(Y)))) {
  1751. Value *Cmp = Builder.CreateIsNull(Neg);
  1752. return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Y);
  1753. }
  1754. const APInt *C;
  1755. if (match(Op1, m_APInt(C))) {
  1756. const APInt *XorC;
  1757. if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
  1758. // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
  1759. Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
  1760. Value *And = Builder.CreateAnd(X, Op1);
  1761. And->takeName(Op0);
  1762. return BinaryOperator::CreateXor(And, NewC);
  1763. }
  1764. const APInt *OrC;
  1765. if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
  1766. // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
  1767. // NOTE: This reduces the number of bits set in the & mask, which
  1768. // can expose opportunities for store narrowing for scalars.
  1769. // NOTE: SimplifyDemandedBits should have already removed bits from C1
  1770. // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
  1771. // above, but this feels safer.
  1772. APInt Together = *C & *OrC;
  1773. Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
  1774. And->takeName(Op0);
  1775. return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
  1776. }
  1777. unsigned Width = Ty->getScalarSizeInBits();
  1778. const APInt *ShiftC;
  1779. if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
  1780. ShiftC->ult(Width)) {
  1781. if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
  1782. // We are clearing high bits that were potentially set by sext+ashr:
  1783. // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
  1784. Value *Sext = Builder.CreateSExt(X, Ty);
  1785. Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
  1786. return BinaryOperator::CreateLShr(Sext, ShAmtC);
  1787. }
  1788. }
  1789. // If this 'and' clears the sign-bits added by ashr, replace with lshr:
  1790. // and (ashr X, ShiftC), C --> lshr X, ShiftC
  1791. if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
  1792. C->isMask(Width - ShiftC->getZExtValue()))
  1793. return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
  1794. const APInt *AddC;
  1795. if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
  1796. // If we add zeros to every bit below a mask, the add has no effect:
  1797. // (X + AddC) & LowMaskC --> X & LowMaskC
  1798. unsigned Ctlz = C->countLeadingZeros();
  1799. APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
  1800. if ((*AddC & LowMask).isZero())
  1801. return BinaryOperator::CreateAnd(X, Op1);
  1802. // If we are masking the result of the add down to exactly one bit and
  1803. // the constant we are adding has no bits set below that bit, then the
  1804. // add is flipping a single bit. Example:
  1805. // (X + 4) & 4 --> (X & 4) ^ 4
  1806. if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
  1807. assert((*C & *AddC) != 0 && "Expected common bit");
  1808. Value *NewAnd = Builder.CreateAnd(X, Op1);
  1809. return BinaryOperator::CreateXor(NewAnd, Op1);
  1810. }
  1811. }
  1812. // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
  1813. // bitwidth of X and OP behaves well when given trunc(C1) and X.
  1814. auto isNarrowableBinOpcode = [](BinaryOperator *B) {
  1815. switch (B->getOpcode()) {
  1816. case Instruction::Xor:
  1817. case Instruction::Or:
  1818. case Instruction::Mul:
  1819. case Instruction::Add:
  1820. case Instruction::Sub:
  1821. return true;
  1822. default:
  1823. return false;
  1824. }
  1825. };
  1826. BinaryOperator *BO;
  1827. if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
  1828. Instruction::BinaryOps BOpcode = BO->getOpcode();
  1829. Value *X;
  1830. const APInt *C1;
  1831. // TODO: The one-use restrictions could be relaxed a little if the AND
  1832. // is going to be removed.
  1833. // Try to narrow the 'and' and a binop with constant operand:
  1834. // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
  1835. if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
  1836. C->isIntN(X->getType()->getScalarSizeInBits())) {
  1837. unsigned XWidth = X->getType()->getScalarSizeInBits();
  1838. Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
  1839. Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
  1840. ? Builder.CreateBinOp(BOpcode, X, TruncC1)
  1841. : Builder.CreateBinOp(BOpcode, TruncC1, X);
  1842. Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
  1843. Value *And = Builder.CreateAnd(BinOp, TruncC);
  1844. return new ZExtInst(And, Ty);
  1845. }
  1846. // Similar to above: if the mask matches the zext input width, then the
  1847. // 'and' can be eliminated, so we can truncate the other variable op:
  1848. // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
  1849. if (isa<Instruction>(BO->getOperand(0)) &&
  1850. match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
  1851. C->isMask(X->getType()->getScalarSizeInBits())) {
  1852. Y = BO->getOperand(1);
  1853. Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
  1854. Value *NewBO =
  1855. Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
  1856. return new ZExtInst(NewBO, Ty);
  1857. }
  1858. // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
  1859. if (isa<Instruction>(BO->getOperand(1)) &&
  1860. match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
  1861. C->isMask(X->getType()->getScalarSizeInBits())) {
  1862. Y = BO->getOperand(0);
  1863. Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
  1864. Value *NewBO =
  1865. Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
  1866. return new ZExtInst(NewBO, Ty);
  1867. }
  1868. }
  1869. // This is intentionally placed after the narrowing transforms for
  1870. // efficiency (transform directly to the narrow logic op if possible).
  1871. // If the mask is only needed on one incoming arm, push the 'and' op up.
  1872. if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
  1873. match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
  1874. APInt NotAndMask(~(*C));
  1875. BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
  1876. if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
  1877. // Not masking anything out for the LHS, move mask to RHS.
  1878. // and ({x}or X, Y), C --> {x}or X, (and Y, C)
  1879. Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
  1880. return BinaryOperator::Create(BinOp, X, NewRHS);
  1881. }
  1882. if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
  1883. // Not masking anything out for the RHS, move mask to LHS.
  1884. // and ({x}or X, Y), C --> {x}or (and X, C), Y
  1885. Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
  1886. return BinaryOperator::Create(BinOp, NewLHS, Y);
  1887. }
  1888. }
  1889. // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
  1890. // constant, test if the shift amount equals the offset bit index:
  1891. // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
  1892. // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
  1893. if (C->isPowerOf2() &&
  1894. match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
  1895. int Log2ShiftC = ShiftC->exactLogBase2();
  1896. int Log2C = C->exactLogBase2();
  1897. bool IsShiftLeft =
  1898. cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
  1899. int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
  1900. assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
  1901. Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
  1902. return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
  1903. ConstantInt::getNullValue(Ty));
  1904. }
  1905. Constant *C1, *C2;
  1906. const APInt *C3 = C;
  1907. Value *X;
  1908. if (C3->isPowerOf2()) {
  1909. Constant *Log2C3 = ConstantInt::get(Ty, C3->countTrailingZeros());
  1910. if (match(Op0, m_OneUse(m_LShr(m_Shl(m_ImmConstant(C1), m_Value(X)),
  1911. m_ImmConstant(C2)))) &&
  1912. match(C1, m_Power2())) {
  1913. Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
  1914. Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
  1915. KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
  1916. if (KnownLShrc.getMaxValue().ult(Width)) {
  1917. // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
  1918. // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
  1919. Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
  1920. Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
  1921. return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
  1922. ConstantInt::getNullValue(Ty));
  1923. }
  1924. }
  1925. if (match(Op0, m_OneUse(m_Shl(m_LShr(m_ImmConstant(C1), m_Value(X)),
  1926. m_ImmConstant(C2)))) &&
  1927. match(C1, m_Power2())) {
  1928. Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
  1929. Constant *Cmp =
  1930. ConstantExpr::getCompare(ICmpInst::ICMP_ULT, Log2C3, C2);
  1931. if (Cmp->isZeroValue()) {
  1932. // iff C1,C3 is pow2 and Log2(C3) >= C2:
  1933. // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
  1934. Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
  1935. Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
  1936. Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
  1937. return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
  1938. ConstantInt::getNullValue(Ty));
  1939. }
  1940. }
  1941. }
  1942. }
  1943. if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
  1944. m_SignMask())) &&
  1945. match(Y, m_SpecificInt_ICMP(
  1946. ICmpInst::Predicate::ICMP_EQ,
  1947. APInt(Ty->getScalarSizeInBits(),
  1948. Ty->getScalarSizeInBits() -
  1949. X->getType()->getScalarSizeInBits())))) {
  1950. auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
  1951. auto *SanitizedSignMask = cast<Constant>(Op1);
  1952. // We must be careful with the undef elements of the sign bit mask, however:
  1953. // the mask elt can be undef iff the shift amount for that lane was undef,
  1954. // otherwise we need to sanitize undef masks to zero.
  1955. SanitizedSignMask = Constant::replaceUndefsWith(
  1956. SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
  1957. SanitizedSignMask =
  1958. Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
  1959. return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
  1960. }
  1961. if (Instruction *Z = narrowMaskedBinOp(I))
  1962. return Z;
  1963. if (I.getType()->isIntOrIntVectorTy(1)) {
  1964. if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
  1965. if (auto *I =
  1966. foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
  1967. return I;
  1968. }
  1969. if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
  1970. if (auto *I =
  1971. foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
  1972. return I;
  1973. }
  1974. }
  1975. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  1976. return FoldedLogic;
  1977. if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
  1978. return DeMorgan;
  1979. {
  1980. Value *A, *B, *C;
  1981. // A & (A ^ B) --> A & ~B
  1982. if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
  1983. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
  1984. // (A ^ B) & A --> A & ~B
  1985. if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
  1986. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
  1987. // A & ~(A ^ B) --> A & B
  1988. if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
  1989. return BinaryOperator::CreateAnd(Op0, B);
  1990. // ~(A ^ B) & A --> A & B
  1991. if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
  1992. return BinaryOperator::CreateAnd(Op1, B);
  1993. // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
  1994. if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
  1995. if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
  1996. if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
  1997. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
  1998. // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
  1999. if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
  2000. if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
  2001. if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
  2002. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
  2003. // (A | B) & (~A ^ B) -> A & B
  2004. // (A | B) & (B ^ ~A) -> A & B
  2005. // (B | A) & (~A ^ B) -> A & B
  2006. // (B | A) & (B ^ ~A) -> A & B
  2007. if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
  2008. match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
  2009. return BinaryOperator::CreateAnd(A, B);
  2010. // (~A ^ B) & (A | B) -> A & B
  2011. // (~A ^ B) & (B | A) -> A & B
  2012. // (B ^ ~A) & (A | B) -> A & B
  2013. // (B ^ ~A) & (B | A) -> A & B
  2014. if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
  2015. match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
  2016. return BinaryOperator::CreateAnd(A, B);
  2017. // (~A | B) & (A ^ B) -> ~A & B
  2018. // (~A | B) & (B ^ A) -> ~A & B
  2019. // (B | ~A) & (A ^ B) -> ~A & B
  2020. // (B | ~A) & (B ^ A) -> ~A & B
  2021. if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
  2022. match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
  2023. return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
  2024. // (A ^ B) & (~A | B) -> ~A & B
  2025. // (B ^ A) & (~A | B) -> ~A & B
  2026. // (A ^ B) & (B | ~A) -> ~A & B
  2027. // (B ^ A) & (B | ~A) -> ~A & B
  2028. if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
  2029. match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
  2030. return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
  2031. }
  2032. {
  2033. ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
  2034. ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
  2035. if (LHS && RHS)
  2036. if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true))
  2037. return replaceInstUsesWith(I, Res);
  2038. // TODO: Make this recursive; it's a little tricky because an arbitrary
  2039. // number of 'and' instructions might have to be created.
  2040. if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
  2041. bool IsLogical = isa<SelectInst>(Op1);
  2042. // LHS & (X && Y) --> (LHS && X) && Y
  2043. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2044. if (Value *Res =
  2045. foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true, IsLogical))
  2046. return replaceInstUsesWith(I, IsLogical
  2047. ? Builder.CreateLogicalAnd(Res, Y)
  2048. : Builder.CreateAnd(Res, Y));
  2049. // LHS & (X && Y) --> X && (LHS & Y)
  2050. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2051. if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true,
  2052. /* IsLogical */ false))
  2053. return replaceInstUsesWith(I, IsLogical
  2054. ? Builder.CreateLogicalAnd(X, Res)
  2055. : Builder.CreateAnd(X, Res));
  2056. }
  2057. if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
  2058. bool IsLogical = isa<SelectInst>(Op0);
  2059. // (X && Y) & RHS --> (X && RHS) && Y
  2060. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2061. if (Value *Res =
  2062. foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true, IsLogical))
  2063. return replaceInstUsesWith(I, IsLogical
  2064. ? Builder.CreateLogicalAnd(Res, Y)
  2065. : Builder.CreateAnd(Res, Y));
  2066. // (X && Y) & RHS --> X && (Y & RHS)
  2067. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2068. if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true,
  2069. /* IsLogical */ false))
  2070. return replaceInstUsesWith(I, IsLogical
  2071. ? Builder.CreateLogicalAnd(X, Res)
  2072. : Builder.CreateAnd(X, Res));
  2073. }
  2074. }
  2075. if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
  2076. if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
  2077. if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
  2078. return replaceInstUsesWith(I, Res);
  2079. if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
  2080. return FoldedFCmps;
  2081. if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
  2082. return CastedAnd;
  2083. if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
  2084. return Sel;
  2085. // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
  2086. // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
  2087. // with binop identity constant. But creating a select with non-constant
  2088. // arm may not be reversible due to poison semantics. Is that a good
  2089. // canonicalization?
  2090. Value *A;
  2091. if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
  2092. A->getType()->isIntOrIntVectorTy(1))
  2093. return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
  2094. if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
  2095. A->getType()->isIntOrIntVectorTy(1))
  2096. return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
  2097. // Similarly, a 'not' of the bool translates to a swap of the select arms:
  2098. // ~sext(A) & Op1 --> A ? 0 : Op1
  2099. // Op0 & ~sext(A) --> A ? 0 : Op0
  2100. if (match(Op0, m_Not(m_SExt(m_Value(A)))) &&
  2101. A->getType()->isIntOrIntVectorTy(1))
  2102. return SelectInst::Create(A, Constant::getNullValue(Ty), Op1);
  2103. if (match(Op1, m_Not(m_SExt(m_Value(A)))) &&
  2104. A->getType()->isIntOrIntVectorTy(1))
  2105. return SelectInst::Create(A, Constant::getNullValue(Ty), Op0);
  2106. // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
  2107. if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
  2108. m_AShr(m_Value(X), m_APIntAllowUndef(C)))),
  2109. m_Value(Y))) &&
  2110. *C == X->getType()->getScalarSizeInBits() - 1) {
  2111. Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
  2112. return SelectInst::Create(IsNeg, Y, ConstantInt::getNullValue(Ty));
  2113. }
  2114. // If there's a 'not' of the shifted value, swap the select operands:
  2115. // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
  2116. if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
  2117. m_Not(m_AShr(m_Value(X), m_APIntAllowUndef(C))))),
  2118. m_Value(Y))) &&
  2119. *C == X->getType()->getScalarSizeInBits() - 1) {
  2120. Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
  2121. return SelectInst::Create(IsNeg, ConstantInt::getNullValue(Ty), Y);
  2122. }
  2123. // (~x) & y --> ~(x | (~y)) iff that gets rid of inversions
  2124. if (sinkNotIntoOtherHandOfLogicalOp(I))
  2125. return &I;
  2126. // An and recurrence w/loop invariant step is equivelent to (and start, step)
  2127. PHINode *PN = nullptr;
  2128. Value *Start = nullptr, *Step = nullptr;
  2129. if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
  2130. return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
  2131. if (Instruction *R = reassociateForUses(I, Builder))
  2132. return R;
  2133. if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
  2134. return Canonicalized;
  2135. if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
  2136. return Folded;
  2137. return nullptr;
  2138. }
  2139. Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
  2140. bool MatchBSwaps,
  2141. bool MatchBitReversals) {
  2142. SmallVector<Instruction *, 4> Insts;
  2143. if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
  2144. Insts))
  2145. return nullptr;
  2146. Instruction *LastInst = Insts.pop_back_val();
  2147. LastInst->removeFromParent();
  2148. for (auto *Inst : Insts)
  2149. Worklist.push(Inst);
  2150. return LastInst;
  2151. }
  2152. /// Match UB-safe variants of the funnel shift intrinsic.
  2153. static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
  2154. // TODO: Can we reduce the code duplication between this and the related
  2155. // rotate matching code under visitSelect and visitTrunc?
  2156. unsigned Width = Or.getType()->getScalarSizeInBits();
  2157. // First, find an or'd pair of opposite shifts:
  2158. // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
  2159. BinaryOperator *Or0, *Or1;
  2160. if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
  2161. !match(Or.getOperand(1), m_BinOp(Or1)))
  2162. return nullptr;
  2163. Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
  2164. if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
  2165. !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
  2166. Or0->getOpcode() == Or1->getOpcode())
  2167. return nullptr;
  2168. // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
  2169. if (Or0->getOpcode() == BinaryOperator::LShr) {
  2170. std::swap(Or0, Or1);
  2171. std::swap(ShVal0, ShVal1);
  2172. std::swap(ShAmt0, ShAmt1);
  2173. }
  2174. assert(Or0->getOpcode() == BinaryOperator::Shl &&
  2175. Or1->getOpcode() == BinaryOperator::LShr &&
  2176. "Illegal or(shift,shift) pair");
  2177. // Match the shift amount operands for a funnel shift pattern. This always
  2178. // matches a subtraction on the R operand.
  2179. auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
  2180. // Check for constant shift amounts that sum to the bitwidth.
  2181. const APInt *LI, *RI;
  2182. if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
  2183. if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
  2184. return ConstantInt::get(L->getType(), *LI);
  2185. Constant *LC, *RC;
  2186. if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
  2187. match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
  2188. match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
  2189. match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
  2190. return ConstantExpr::mergeUndefsWith(LC, RC);
  2191. // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
  2192. // We limit this to X < Width in case the backend re-expands the intrinsic,
  2193. // and has to reintroduce a shift modulo operation (InstCombine might remove
  2194. // it after this fold). This still doesn't guarantee that the final codegen
  2195. // will match this original pattern.
  2196. if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
  2197. KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
  2198. return KnownL.getMaxValue().ult(Width) ? L : nullptr;
  2199. }
  2200. // For non-constant cases, the following patterns currently only work for
  2201. // rotation patterns.
  2202. // TODO: Add general funnel-shift compatible patterns.
  2203. if (ShVal0 != ShVal1)
  2204. return nullptr;
  2205. // For non-constant cases we don't support non-pow2 shift masks.
  2206. // TODO: Is it worth matching urem as well?
  2207. if (!isPowerOf2_32(Width))
  2208. return nullptr;
  2209. // The shift amount may be masked with negation:
  2210. // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
  2211. Value *X;
  2212. unsigned Mask = Width - 1;
  2213. if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
  2214. match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
  2215. return X;
  2216. // Similar to above, but the shift amount may be extended after masking,
  2217. // so return the extended value as the parameter for the intrinsic.
  2218. if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
  2219. match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
  2220. m_SpecificInt(Mask))))
  2221. return L;
  2222. if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
  2223. match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
  2224. return L;
  2225. return nullptr;
  2226. };
  2227. Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
  2228. bool IsFshl = true; // Sub on LSHR.
  2229. if (!ShAmt) {
  2230. ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
  2231. IsFshl = false; // Sub on SHL.
  2232. }
  2233. if (!ShAmt)
  2234. return nullptr;
  2235. Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
  2236. Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
  2237. return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
  2238. }
  2239. /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
  2240. static Instruction *matchOrConcat(Instruction &Or,
  2241. InstCombiner::BuilderTy &Builder) {
  2242. assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
  2243. Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
  2244. Type *Ty = Or.getType();
  2245. unsigned Width = Ty->getScalarSizeInBits();
  2246. if ((Width & 1) != 0)
  2247. return nullptr;
  2248. unsigned HalfWidth = Width / 2;
  2249. // Canonicalize zext (lower half) to LHS.
  2250. if (!isa<ZExtInst>(Op0))
  2251. std::swap(Op0, Op1);
  2252. // Find lower/upper half.
  2253. Value *LowerSrc, *ShlVal, *UpperSrc;
  2254. const APInt *C;
  2255. if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
  2256. !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
  2257. !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
  2258. return nullptr;
  2259. if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
  2260. LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
  2261. return nullptr;
  2262. auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
  2263. Value *NewLower = Builder.CreateZExt(Lo, Ty);
  2264. Value *NewUpper = Builder.CreateZExt(Hi, Ty);
  2265. NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
  2266. Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
  2267. Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
  2268. return Builder.CreateCall(F, BinOp);
  2269. };
  2270. // BSWAP: Push the concat down, swapping the lower/upper sources.
  2271. // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
  2272. Value *LowerBSwap, *UpperBSwap;
  2273. if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
  2274. match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
  2275. return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
  2276. // BITREVERSE: Push the concat down, swapping the lower/upper sources.
  2277. // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
  2278. Value *LowerBRev, *UpperBRev;
  2279. if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
  2280. match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
  2281. return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
  2282. return nullptr;
  2283. }
  2284. /// If all elements of two constant vectors are 0/-1 and inverses, return true.
  2285. static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
  2286. unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
  2287. for (unsigned i = 0; i != NumElts; ++i) {
  2288. Constant *EltC1 = C1->getAggregateElement(i);
  2289. Constant *EltC2 = C2->getAggregateElement(i);
  2290. if (!EltC1 || !EltC2)
  2291. return false;
  2292. // One element must be all ones, and the other must be all zeros.
  2293. if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
  2294. (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
  2295. return false;
  2296. }
  2297. return true;
  2298. }
  2299. /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
  2300. /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
  2301. /// B, it can be used as the condition operand of a select instruction.
  2302. /// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
  2303. Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
  2304. bool ABIsTheSame) {
  2305. // We may have peeked through bitcasts in the caller.
  2306. // Exit immediately if we don't have (vector) integer types.
  2307. Type *Ty = A->getType();
  2308. if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
  2309. return nullptr;
  2310. // If A is the 'not' operand of B and has enough signbits, we have our answer.
  2311. if (ABIsTheSame ? (A == B) : match(B, m_Not(m_Specific(A)))) {
  2312. // If these are scalars or vectors of i1, A can be used directly.
  2313. if (Ty->isIntOrIntVectorTy(1))
  2314. return A;
  2315. // If we look through a vector bitcast, the caller will bitcast the operands
  2316. // to match the condition's number of bits (N x i1).
  2317. // To make this poison-safe, disallow bitcast from wide element to narrow
  2318. // element. That could allow poison in lanes where it was not present in the
  2319. // original code.
  2320. A = peekThroughBitcast(A);
  2321. if (A->getType()->isIntOrIntVectorTy()) {
  2322. unsigned NumSignBits = ComputeNumSignBits(A);
  2323. if (NumSignBits == A->getType()->getScalarSizeInBits() &&
  2324. NumSignBits <= Ty->getScalarSizeInBits())
  2325. return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
  2326. }
  2327. return nullptr;
  2328. }
  2329. // TODO: add support for sext and constant case
  2330. if (ABIsTheSame)
  2331. return nullptr;
  2332. // If both operands are constants, see if the constants are inverse bitmasks.
  2333. Constant *AConst, *BConst;
  2334. if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
  2335. if (AConst == ConstantExpr::getNot(BConst) &&
  2336. ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
  2337. return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
  2338. // Look for more complex patterns. The 'not' op may be hidden behind various
  2339. // casts. Look through sexts and bitcasts to find the booleans.
  2340. Value *Cond;
  2341. Value *NotB;
  2342. if (match(A, m_SExt(m_Value(Cond))) &&
  2343. Cond->getType()->isIntOrIntVectorTy(1)) {
  2344. // A = sext i1 Cond; B = sext (not (i1 Cond))
  2345. if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
  2346. return Cond;
  2347. // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
  2348. // TODO: The one-use checks are unnecessary or misplaced. If the caller
  2349. // checked for uses on logic ops/casts, that should be enough to
  2350. // make this transform worthwhile.
  2351. if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
  2352. NotB = peekThroughBitcast(NotB, true);
  2353. if (match(NotB, m_SExt(m_Specific(Cond))))
  2354. return Cond;
  2355. }
  2356. }
  2357. // All scalar (and most vector) possibilities should be handled now.
  2358. // Try more matches that only apply to non-splat constant vectors.
  2359. if (!Ty->isVectorTy())
  2360. return nullptr;
  2361. // If both operands are xor'd with constants using the same sexted boolean
  2362. // operand, see if the constants are inverse bitmasks.
  2363. // TODO: Use ConstantExpr::getNot()?
  2364. if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
  2365. match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
  2366. Cond->getType()->isIntOrIntVectorTy(1) &&
  2367. areInverseVectorBitmasks(AConst, BConst)) {
  2368. AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
  2369. return Builder.CreateXor(Cond, AConst);
  2370. }
  2371. return nullptr;
  2372. }
  2373. /// We have an expression of the form (A & C) | (B & D). Try to simplify this
  2374. /// to "A' ? C : D", where A' is a boolean or vector of booleans.
  2375. /// When InvertFalseVal is set to true, we try to match the pattern
  2376. /// where we have peeked through a 'not' op and A and B are the same:
  2377. /// (A & C) | ~(A | D) --> (A & C) | (~A & ~D) --> A' ? C : ~D
  2378. Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
  2379. Value *D, bool InvertFalseVal) {
  2380. // The potential condition of the select may be bitcasted. In that case, look
  2381. // through its bitcast and the corresponding bitcast of the 'not' condition.
  2382. Type *OrigType = A->getType();
  2383. A = peekThroughBitcast(A, true);
  2384. B = peekThroughBitcast(B, true);
  2385. if (Value *Cond = getSelectCondition(A, B, InvertFalseVal)) {
  2386. // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
  2387. // If this is a vector, we may need to cast to match the condition's length.
  2388. // The bitcasts will either all exist or all not exist. The builder will
  2389. // not create unnecessary casts if the types already match.
  2390. Type *SelTy = A->getType();
  2391. if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
  2392. // For a fixed or scalable vector get N from <{vscale x} N x iM>
  2393. unsigned Elts = VecTy->getElementCount().getKnownMinValue();
  2394. // For a fixed or scalable vector, get the size in bits of N x iM; for a
  2395. // scalar this is just M.
  2396. unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
  2397. Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
  2398. SelTy = VectorType::get(EltTy, VecTy->getElementCount());
  2399. }
  2400. Value *BitcastC = Builder.CreateBitCast(C, SelTy);
  2401. if (InvertFalseVal)
  2402. D = Builder.CreateNot(D);
  2403. Value *BitcastD = Builder.CreateBitCast(D, SelTy);
  2404. Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
  2405. return Builder.CreateBitCast(Select, OrigType);
  2406. }
  2407. return nullptr;
  2408. }
  2409. // (icmp eq X, 0) | (icmp ult Other, X) -> (icmp ule Other, X-1)
  2410. // (icmp ne X, 0) & (icmp uge Other, X) -> (icmp ugt Other, X-1)
  2411. static Value *foldAndOrOfICmpEqZeroAndICmp(ICmpInst *LHS, ICmpInst *RHS,
  2412. bool IsAnd, bool IsLogical,
  2413. IRBuilderBase &Builder) {
  2414. ICmpInst::Predicate LPred =
  2415. IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
  2416. ICmpInst::Predicate RPred =
  2417. IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
  2418. Value *LHS0 = LHS->getOperand(0);
  2419. if (LPred != ICmpInst::ICMP_EQ || !match(LHS->getOperand(1), m_Zero()) ||
  2420. !LHS0->getType()->isIntOrIntVectorTy() ||
  2421. !(LHS->hasOneUse() || RHS->hasOneUse()))
  2422. return nullptr;
  2423. Value *Other;
  2424. if (RPred == ICmpInst::ICMP_ULT && RHS->getOperand(1) == LHS0)
  2425. Other = RHS->getOperand(0);
  2426. else if (RPred == ICmpInst::ICMP_UGT && RHS->getOperand(0) == LHS0)
  2427. Other = RHS->getOperand(1);
  2428. else
  2429. return nullptr;
  2430. if (IsLogical)
  2431. Other = Builder.CreateFreeze(Other);
  2432. return Builder.CreateICmp(
  2433. IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
  2434. Builder.CreateAdd(LHS0, Constant::getAllOnesValue(LHS0->getType())),
  2435. Other);
  2436. }
  2437. /// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
  2438. /// If IsLogical is true, then the and/or is in select form and the transform
  2439. /// must be poison-safe.
  2440. Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
  2441. Instruction &I, bool IsAnd,
  2442. bool IsLogical) {
  2443. const SimplifyQuery Q = SQ.getWithInstruction(&I);
  2444. // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
  2445. // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
  2446. // if K1 and K2 are a one-bit mask.
  2447. if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
  2448. return V;
  2449. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  2450. Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
  2451. Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
  2452. const APInt *LHSC = nullptr, *RHSC = nullptr;
  2453. match(LHS1, m_APInt(LHSC));
  2454. match(RHS1, m_APInt(RHSC));
  2455. // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
  2456. // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
  2457. if (predicatesFoldable(PredL, PredR)) {
  2458. if (LHS0 == RHS1 && LHS1 == RHS0) {
  2459. PredL = ICmpInst::getSwappedPredicate(PredL);
  2460. std::swap(LHS0, LHS1);
  2461. }
  2462. if (LHS0 == RHS0 && LHS1 == RHS1) {
  2463. unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
  2464. : getICmpCode(PredL) | getICmpCode(PredR);
  2465. bool IsSigned = LHS->isSigned() || RHS->isSigned();
  2466. return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
  2467. }
  2468. }
  2469. // handle (roughly):
  2470. // (icmp ne (A & B), C) | (icmp ne (A & D), E)
  2471. // (icmp eq (A & B), C) & (icmp eq (A & D), E)
  2472. if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
  2473. return V;
  2474. if (Value *V =
  2475. foldAndOrOfICmpEqZeroAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
  2476. return V;
  2477. // We can treat logical like bitwise here, because both operands are used on
  2478. // the LHS, and as such poison from both will propagate.
  2479. if (Value *V = foldAndOrOfICmpEqZeroAndICmp(RHS, LHS, IsAnd,
  2480. /*IsLogical*/ false, Builder))
  2481. return V;
  2482. if (Value *V =
  2483. foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, IsLogical, Builder, Q))
  2484. return V;
  2485. // We can convert this case to bitwise and, because both operands are used
  2486. // on the LHS, and as such poison from both will propagate.
  2487. if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd,
  2488. /*IsLogical*/ false, Builder, Q))
  2489. return V;
  2490. if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
  2491. return V;
  2492. if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
  2493. return V;
  2494. // TODO: One of these directions is fine with logical and/or, the other could
  2495. // be supported by inserting freeze.
  2496. if (!IsLogical) {
  2497. // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
  2498. // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
  2499. if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd))
  2500. return V;
  2501. // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
  2502. // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
  2503. if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd))
  2504. return V;
  2505. }
  2506. // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
  2507. if (IsAnd && !IsLogical)
  2508. if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
  2509. return V;
  2510. if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder))
  2511. return V;
  2512. // TODO: Verify whether this is safe for logical and/or.
  2513. if (!IsLogical) {
  2514. if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
  2515. return X;
  2516. if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
  2517. return X;
  2518. }
  2519. if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
  2520. return X;
  2521. // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
  2522. // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
  2523. // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs.
  2524. if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
  2525. PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
  2526. LHS0->getType() == RHS0->getType()) {
  2527. Value *NewOr = Builder.CreateOr(LHS0, RHS0);
  2528. return Builder.CreateICmp(PredL, NewOr,
  2529. Constant::getNullValue(NewOr->getType()));
  2530. }
  2531. // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
  2532. if (!LHSC || !RHSC)
  2533. return nullptr;
  2534. // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
  2535. // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
  2536. // where CMAX is the all ones value for the truncated type,
  2537. // iff the lower bits of C2 and CA are zero.
  2538. if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
  2539. PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
  2540. Value *V;
  2541. const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
  2542. // (trunc x) == C1 & (and x, CA) == C2
  2543. // (and x, CA) == C2 & (trunc x) == C1
  2544. if (match(RHS0, m_Trunc(m_Value(V))) &&
  2545. match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
  2546. SmallC = RHSC;
  2547. BigC = LHSC;
  2548. } else if (match(LHS0, m_Trunc(m_Value(V))) &&
  2549. match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
  2550. SmallC = LHSC;
  2551. BigC = RHSC;
  2552. }
  2553. if (SmallC && BigC) {
  2554. unsigned BigBitSize = BigC->getBitWidth();
  2555. unsigned SmallBitSize = SmallC->getBitWidth();
  2556. // Check that the low bits are zero.
  2557. APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
  2558. if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
  2559. Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
  2560. APInt N = SmallC->zext(BigBitSize) | *BigC;
  2561. Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
  2562. return Builder.CreateICmp(PredL, NewAnd, NewVal);
  2563. }
  2564. }
  2565. }
  2566. // Match naive pattern (and its inverted form) for checking if two values
  2567. // share same sign. An example of the pattern:
  2568. // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
  2569. // Inverted form (example):
  2570. // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
  2571. bool TrueIfSignedL, TrueIfSignedR;
  2572. if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
  2573. isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
  2574. (RHS->hasOneUse() || LHS->hasOneUse())) {
  2575. Value *X, *Y;
  2576. if (IsAnd) {
  2577. if ((TrueIfSignedL && !TrueIfSignedR &&
  2578. match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
  2579. match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
  2580. (!TrueIfSignedL && TrueIfSignedR &&
  2581. match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
  2582. match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
  2583. Value *NewXor = Builder.CreateXor(X, Y);
  2584. return Builder.CreateIsNeg(NewXor);
  2585. }
  2586. } else {
  2587. if ((TrueIfSignedL && !TrueIfSignedR &&
  2588. match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
  2589. match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
  2590. (!TrueIfSignedL && TrueIfSignedR &&
  2591. match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
  2592. match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
  2593. Value *NewXor = Builder.CreateXor(X, Y);
  2594. return Builder.CreateIsNotNeg(NewXor);
  2595. }
  2596. }
  2597. }
  2598. return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
  2599. }
  2600. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  2601. // here. We should standardize that construct where it is needed or choose some
  2602. // other way to ensure that commutated variants of patterns are not missed.
  2603. Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
  2604. if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
  2605. SQ.getWithInstruction(&I)))
  2606. return replaceInstUsesWith(I, V);
  2607. if (SimplifyAssociativeOrCommutative(I))
  2608. return &I;
  2609. if (Instruction *X = foldVectorBinop(I))
  2610. return X;
  2611. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  2612. return Phi;
  2613. // See if we can simplify any instructions used by the instruction whose sole
  2614. // purpose is to compute bits we don't care about.
  2615. if (SimplifyDemandedInstructionBits(I))
  2616. return &I;
  2617. // Do this before using distributive laws to catch simple and/or/not patterns.
  2618. if (Instruction *Xor = foldOrToXor(I, Builder))
  2619. return Xor;
  2620. if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
  2621. return X;
  2622. // (A&B)|(A&C) -> A&(B|C) etc
  2623. if (Value *V = foldUsingDistributiveLaws(I))
  2624. return replaceInstUsesWith(I, V);
  2625. if (Value *V = SimplifyBSwap(I, Builder))
  2626. return replaceInstUsesWith(I, V);
  2627. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  2628. Type *Ty = I.getType();
  2629. if (Ty->isIntOrIntVectorTy(1)) {
  2630. if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
  2631. if (auto *I =
  2632. foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
  2633. return I;
  2634. }
  2635. if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
  2636. if (auto *I =
  2637. foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
  2638. return I;
  2639. }
  2640. }
  2641. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  2642. return FoldedLogic;
  2643. if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
  2644. /*MatchBitReversals*/ true))
  2645. return BitOp;
  2646. if (Instruction *Funnel = matchFunnelShift(I, *this))
  2647. return Funnel;
  2648. if (Instruction *Concat = matchOrConcat(I, Builder))
  2649. return replaceInstUsesWith(I, Concat);
  2650. Value *X, *Y;
  2651. const APInt *CV;
  2652. if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
  2653. !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
  2654. // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
  2655. // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
  2656. Value *Or = Builder.CreateOr(X, Y);
  2657. return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
  2658. }
  2659. // If the operands have no common bits set:
  2660. // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
  2661. if (match(&I,
  2662. m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) &&
  2663. haveNoCommonBitsSet(Op0, Op1, DL)) {
  2664. Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
  2665. return BinaryOperator::CreateMul(X, IncrementY);
  2666. }
  2667. // X | (X ^ Y) --> X | Y (4 commuted patterns)
  2668. if (match(&I, m_c_Or(m_Value(X), m_c_Xor(m_Deferred(X), m_Value(Y)))))
  2669. return BinaryOperator::CreateOr(X, Y);
  2670. // (A & C) | (B & D)
  2671. Value *A, *B, *C, *D;
  2672. if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
  2673. match(Op1, m_And(m_Value(B), m_Value(D)))) {
  2674. // (A & C0) | (B & C1)
  2675. const APInt *C0, *C1;
  2676. if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
  2677. Value *X;
  2678. if (*C0 == ~*C1) {
  2679. // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
  2680. if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
  2681. return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
  2682. // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
  2683. if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
  2684. return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
  2685. // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
  2686. if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
  2687. return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
  2688. // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
  2689. if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
  2690. return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
  2691. }
  2692. if ((*C0 & *C1).isZero()) {
  2693. // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
  2694. // iff (C0 & C1) == 0 and (X & ~C0) == 0
  2695. if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
  2696. MaskedValueIsZero(X, ~*C0, 0, &I)) {
  2697. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2698. return BinaryOperator::CreateAnd(A, C01);
  2699. }
  2700. // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
  2701. // iff (C0 & C1) == 0 and (X & ~C1) == 0
  2702. if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
  2703. MaskedValueIsZero(X, ~*C1, 0, &I)) {
  2704. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2705. return BinaryOperator::CreateAnd(B, C01);
  2706. }
  2707. // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
  2708. // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
  2709. const APInt *C2, *C3;
  2710. if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
  2711. match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
  2712. (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
  2713. Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
  2714. Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
  2715. return BinaryOperator::CreateAnd(Or, C01);
  2716. }
  2717. }
  2718. }
  2719. // Don't try to form a select if it's unlikely that we'll get rid of at
  2720. // least one of the operands. A select is generally more expensive than the
  2721. // 'or' that it is replacing.
  2722. if (Op0->hasOneUse() || Op1->hasOneUse()) {
  2723. // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
  2724. if (Value *V = matchSelectFromAndOr(A, C, B, D))
  2725. return replaceInstUsesWith(I, V);
  2726. if (Value *V = matchSelectFromAndOr(A, C, D, B))
  2727. return replaceInstUsesWith(I, V);
  2728. if (Value *V = matchSelectFromAndOr(C, A, B, D))
  2729. return replaceInstUsesWith(I, V);
  2730. if (Value *V = matchSelectFromAndOr(C, A, D, B))
  2731. return replaceInstUsesWith(I, V);
  2732. if (Value *V = matchSelectFromAndOr(B, D, A, C))
  2733. return replaceInstUsesWith(I, V);
  2734. if (Value *V = matchSelectFromAndOr(B, D, C, A))
  2735. return replaceInstUsesWith(I, V);
  2736. if (Value *V = matchSelectFromAndOr(D, B, A, C))
  2737. return replaceInstUsesWith(I, V);
  2738. if (Value *V = matchSelectFromAndOr(D, B, C, A))
  2739. return replaceInstUsesWith(I, V);
  2740. }
  2741. }
  2742. if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
  2743. match(Op1, m_Not(m_Or(m_Value(B), m_Value(D)))) &&
  2744. (Op0->hasOneUse() || Op1->hasOneUse())) {
  2745. // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
  2746. if (Value *V = matchSelectFromAndOr(A, C, B, D, true))
  2747. return replaceInstUsesWith(I, V);
  2748. if (Value *V = matchSelectFromAndOr(A, C, D, B, true))
  2749. return replaceInstUsesWith(I, V);
  2750. if (Value *V = matchSelectFromAndOr(C, A, B, D, true))
  2751. return replaceInstUsesWith(I, V);
  2752. if (Value *V = matchSelectFromAndOr(C, A, D, B, true))
  2753. return replaceInstUsesWith(I, V);
  2754. }
  2755. // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
  2756. if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
  2757. if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
  2758. return BinaryOperator::CreateOr(Op0, C);
  2759. // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
  2760. if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
  2761. if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
  2762. return BinaryOperator::CreateOr(Op1, C);
  2763. // ((A & B) ^ C) | B -> C | B
  2764. if (match(Op0, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op1)), m_Value(C))))
  2765. return BinaryOperator::CreateOr(C, Op1);
  2766. // B | ((A & B) ^ C) -> B | C
  2767. if (match(Op1, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op0)), m_Value(C))))
  2768. return BinaryOperator::CreateOr(Op0, C);
  2769. // ((B | C) & A) | B -> B | (A & C)
  2770. if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
  2771. return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
  2772. if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
  2773. return DeMorgan;
  2774. // Canonicalize xor to the RHS.
  2775. bool SwappedForXor = false;
  2776. if (match(Op0, m_Xor(m_Value(), m_Value()))) {
  2777. std::swap(Op0, Op1);
  2778. SwappedForXor = true;
  2779. }
  2780. if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
  2781. // (A | ?) | (A ^ B) --> (A | ?) | B
  2782. // (B | ?) | (A ^ B) --> (B | ?) | A
  2783. if (match(Op0, m_c_Or(m_Specific(A), m_Value())))
  2784. return BinaryOperator::CreateOr(Op0, B);
  2785. if (match(Op0, m_c_Or(m_Specific(B), m_Value())))
  2786. return BinaryOperator::CreateOr(Op0, A);
  2787. // (A & B) | (A ^ B) --> A | B
  2788. // (B & A) | (A ^ B) --> A | B
  2789. if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
  2790. match(Op0, m_And(m_Specific(B), m_Specific(A))))
  2791. return BinaryOperator::CreateOr(A, B);
  2792. // ~A | (A ^ B) --> ~(A & B)
  2793. // ~B | (A ^ B) --> ~(A & B)
  2794. // The swap above should always make Op0 the 'not'.
  2795. if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
  2796. (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
  2797. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  2798. // Same as above, but peek through an 'and' to the common operand:
  2799. // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
  2800. // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
  2801. Instruction *And;
  2802. if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
  2803. match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
  2804. m_c_And(m_Specific(A), m_Value())))))
  2805. return BinaryOperator::CreateNot(Builder.CreateAnd(And, B));
  2806. if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
  2807. match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
  2808. m_c_And(m_Specific(B), m_Value())))))
  2809. return BinaryOperator::CreateNot(Builder.CreateAnd(And, A));
  2810. // (~A | C) | (A ^ B) --> ~(A & B) | C
  2811. // (~B | C) | (A ^ B) --> ~(A & B) | C
  2812. if (Op0->hasOneUse() && Op1->hasOneUse() &&
  2813. (match(Op0, m_c_Or(m_Not(m_Specific(A)), m_Value(C))) ||
  2814. match(Op0, m_c_Or(m_Not(m_Specific(B)), m_Value(C))))) {
  2815. Value *Nand = Builder.CreateNot(Builder.CreateAnd(A, B), "nand");
  2816. return BinaryOperator::CreateOr(Nand, C);
  2817. }
  2818. // A | (~A ^ B) --> ~B | A
  2819. // B | (A ^ ~B) --> ~A | B
  2820. if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
  2821. Value *NotB = Builder.CreateNot(B, B->getName() + ".not");
  2822. return BinaryOperator::CreateOr(NotB, Op0);
  2823. }
  2824. if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
  2825. Value *NotA = Builder.CreateNot(A, A->getName() + ".not");
  2826. return BinaryOperator::CreateOr(NotA, Op0);
  2827. }
  2828. }
  2829. // A | ~(A | B) -> A | ~B
  2830. // A | ~(A ^ B) -> A | ~B
  2831. if (match(Op1, m_Not(m_Value(A))))
  2832. if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
  2833. if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
  2834. Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
  2835. B->getOpcode() == Instruction::Xor)) {
  2836. Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
  2837. B->getOperand(0);
  2838. Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
  2839. return BinaryOperator::CreateOr(Not, Op0);
  2840. }
  2841. if (SwappedForXor)
  2842. std::swap(Op0, Op1);
  2843. {
  2844. ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
  2845. ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
  2846. if (LHS && RHS)
  2847. if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false))
  2848. return replaceInstUsesWith(I, Res);
  2849. // TODO: Make this recursive; it's a little tricky because an arbitrary
  2850. // number of 'or' instructions might have to be created.
  2851. Value *X, *Y;
  2852. if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
  2853. bool IsLogical = isa<SelectInst>(Op1);
  2854. // LHS | (X || Y) --> (LHS || X) || Y
  2855. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2856. if (Value *Res =
  2857. foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false, IsLogical))
  2858. return replaceInstUsesWith(I, IsLogical
  2859. ? Builder.CreateLogicalOr(Res, Y)
  2860. : Builder.CreateOr(Res, Y));
  2861. // LHS | (X || Y) --> X || (LHS | Y)
  2862. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2863. if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false,
  2864. /* IsLogical */ false))
  2865. return replaceInstUsesWith(I, IsLogical
  2866. ? Builder.CreateLogicalOr(X, Res)
  2867. : Builder.CreateOr(X, Res));
  2868. }
  2869. if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
  2870. bool IsLogical = isa<SelectInst>(Op0);
  2871. // (X || Y) | RHS --> (X || RHS) || Y
  2872. if (auto *Cmp = dyn_cast<ICmpInst>(X))
  2873. if (Value *Res =
  2874. foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false, IsLogical))
  2875. return replaceInstUsesWith(I, IsLogical
  2876. ? Builder.CreateLogicalOr(Res, Y)
  2877. : Builder.CreateOr(Res, Y));
  2878. // (X || Y) | RHS --> X || (Y | RHS)
  2879. if (auto *Cmp = dyn_cast<ICmpInst>(Y))
  2880. if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false,
  2881. /* IsLogical */ false))
  2882. return replaceInstUsesWith(I, IsLogical
  2883. ? Builder.CreateLogicalOr(X, Res)
  2884. : Builder.CreateOr(X, Res));
  2885. }
  2886. }
  2887. if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
  2888. if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
  2889. if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
  2890. return replaceInstUsesWith(I, Res);
  2891. if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
  2892. return FoldedFCmps;
  2893. if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
  2894. return CastedOr;
  2895. if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
  2896. return Sel;
  2897. // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
  2898. // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
  2899. // with binop identity constant. But creating a select with non-constant
  2900. // arm may not be reversible due to poison semantics. Is that a good
  2901. // canonicalization?
  2902. if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
  2903. A->getType()->isIntOrIntVectorTy(1))
  2904. return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1);
  2905. if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
  2906. A->getType()->isIntOrIntVectorTy(1))
  2907. return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0);
  2908. // Note: If we've gotten to the point of visiting the outer OR, then the
  2909. // inner one couldn't be simplified. If it was a constant, then it won't
  2910. // be simplified by a later pass either, so we try swapping the inner/outer
  2911. // ORs in the hopes that we'll be able to simplify it this way.
  2912. // (X|C) | V --> (X|V) | C
  2913. ConstantInt *CI;
  2914. if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
  2915. match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
  2916. Value *Inner = Builder.CreateOr(A, Op1);
  2917. Inner->takeName(Op0);
  2918. return BinaryOperator::CreateOr(Inner, CI);
  2919. }
  2920. // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
  2921. // Since this OR statement hasn't been optimized further yet, we hope
  2922. // that this transformation will allow the new ORs to be optimized.
  2923. {
  2924. Value *X = nullptr, *Y = nullptr;
  2925. if (Op0->hasOneUse() && Op1->hasOneUse() &&
  2926. match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
  2927. match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
  2928. Value *orTrue = Builder.CreateOr(A, C);
  2929. Value *orFalse = Builder.CreateOr(B, D);
  2930. return SelectInst::Create(X, orTrue, orFalse);
  2931. }
  2932. }
  2933. // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X) --> X s> Y ? -1 : X.
  2934. {
  2935. Value *X, *Y;
  2936. if (match(&I, m_c_Or(m_OneUse(m_AShr(
  2937. m_NSWSub(m_Value(Y), m_Value(X)),
  2938. m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
  2939. m_Deferred(X)))) {
  2940. Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
  2941. Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
  2942. return SelectInst::Create(NewICmpInst, AllOnes, X);
  2943. }
  2944. }
  2945. if (Instruction *V =
  2946. canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
  2947. return V;
  2948. CmpInst::Predicate Pred;
  2949. Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
  2950. // Check if the OR weakens the overflow condition for umul.with.overflow by
  2951. // treating any non-zero result as overflow. In that case, we overflow if both
  2952. // umul.with.overflow operands are != 0, as in that case the result can only
  2953. // be 0, iff the multiplication overflows.
  2954. if (match(&I,
  2955. m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
  2956. m_Value(Ov)),
  2957. m_CombineAnd(m_ICmp(Pred,
  2958. m_CombineAnd(m_ExtractValue<0>(
  2959. m_Deferred(UMulWithOv)),
  2960. m_Value(Mul)),
  2961. m_ZeroInt()),
  2962. m_Value(MulIsNotZero)))) &&
  2963. (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
  2964. Pred == CmpInst::ICMP_NE) {
  2965. Value *A, *B;
  2966. if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
  2967. m_Value(A), m_Value(B)))) {
  2968. Value *NotNullA = Builder.CreateIsNotNull(A);
  2969. Value *NotNullB = Builder.CreateIsNotNull(B);
  2970. return BinaryOperator::CreateAnd(NotNullA, NotNullB);
  2971. }
  2972. }
  2973. // (~x) | y --> ~(x & (~y)) iff that gets rid of inversions
  2974. if (sinkNotIntoOtherHandOfLogicalOp(I))
  2975. return &I;
  2976. // Improve "get low bit mask up to and including bit X" pattern:
  2977. // (1 << X) | ((1 << X) + -1) --> -1 l>> (bitwidth(x) - 1 - X)
  2978. if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
  2979. m_Shl(m_One(), m_Deferred(X)))) &&
  2980. match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
  2981. Value *Sub = Builder.CreateSub(
  2982. ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
  2983. return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
  2984. }
  2985. // An or recurrence w/loop invariant step is equivelent to (or start, step)
  2986. PHINode *PN = nullptr;
  2987. Value *Start = nullptr, *Step = nullptr;
  2988. if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
  2989. return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
  2990. // (A & B) | (C | D) or (C | D) | (A & B)
  2991. // Can be combined if C or D is of type (A/B & X)
  2992. if (match(&I, m_c_Or(m_OneUse(m_And(m_Value(A), m_Value(B))),
  2993. m_OneUse(m_Or(m_Value(C), m_Value(D)))))) {
  2994. // (A & B) | (C | ?) -> C | (? | (A & B))
  2995. // (A & B) | (C | ?) -> C | (? | (A & B))
  2996. // (A & B) | (C | ?) -> C | (? | (A & B))
  2997. // (A & B) | (C | ?) -> C | (? | (A & B))
  2998. // (C | ?) | (A & B) -> C | (? | (A & B))
  2999. // (C | ?) | (A & B) -> C | (? | (A & B))
  3000. // (C | ?) | (A & B) -> C | (? | (A & B))
  3001. // (C | ?) | (A & B) -> C | (? | (A & B))
  3002. if (match(D, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
  3003. match(D, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
  3004. return BinaryOperator::CreateOr(
  3005. C, Builder.CreateOr(D, Builder.CreateAnd(A, B)));
  3006. // (A & B) | (? | D) -> (? | (A & B)) | D
  3007. // (A & B) | (? | D) -> (? | (A & B)) | D
  3008. // (A & B) | (? | D) -> (? | (A & B)) | D
  3009. // (A & B) | (? | D) -> (? | (A & B)) | D
  3010. // (? | D) | (A & B) -> (? | (A & B)) | D
  3011. // (? | D) | (A & B) -> (? | (A & B)) | D
  3012. // (? | D) | (A & B) -> (? | (A & B)) | D
  3013. // (? | D) | (A & B) -> (? | (A & B)) | D
  3014. if (match(C, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
  3015. match(C, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
  3016. return BinaryOperator::CreateOr(
  3017. Builder.CreateOr(C, Builder.CreateAnd(A, B)), D);
  3018. }
  3019. if (Instruction *R = reassociateForUses(I, Builder))
  3020. return R;
  3021. if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
  3022. return Canonicalized;
  3023. if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
  3024. return Folded;
  3025. return nullptr;
  3026. }
  3027. /// A ^ B can be specified using other logic ops in a variety of patterns. We
  3028. /// can fold these early and efficiently by morphing an existing instruction.
  3029. static Instruction *foldXorToXor(BinaryOperator &I,
  3030. InstCombiner::BuilderTy &Builder) {
  3031. assert(I.getOpcode() == Instruction::Xor);
  3032. Value *Op0 = I.getOperand(0);
  3033. Value *Op1 = I.getOperand(1);
  3034. Value *A, *B;
  3035. // There are 4 commuted variants for each of the basic patterns.
  3036. // (A & B) ^ (A | B) -> A ^ B
  3037. // (A & B) ^ (B | A) -> A ^ B
  3038. // (A | B) ^ (A & B) -> A ^ B
  3039. // (A | B) ^ (B & A) -> A ^ B
  3040. if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
  3041. m_c_Or(m_Deferred(A), m_Deferred(B)))))
  3042. return BinaryOperator::CreateXor(A, B);
  3043. // (A | ~B) ^ (~A | B) -> A ^ B
  3044. // (~B | A) ^ (~A | B) -> A ^ B
  3045. // (~A | B) ^ (A | ~B) -> A ^ B
  3046. // (B | ~A) ^ (A | ~B) -> A ^ B
  3047. if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
  3048. m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
  3049. return BinaryOperator::CreateXor(A, B);
  3050. // (A & ~B) ^ (~A & B) -> A ^ B
  3051. // (~B & A) ^ (~A & B) -> A ^ B
  3052. // (~A & B) ^ (A & ~B) -> A ^ B
  3053. // (B & ~A) ^ (A & ~B) -> A ^ B
  3054. if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
  3055. m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
  3056. return BinaryOperator::CreateXor(A, B);
  3057. // For the remaining cases we need to get rid of one of the operands.
  3058. if (!Op0->hasOneUse() && !Op1->hasOneUse())
  3059. return nullptr;
  3060. // (A | B) ^ ~(A & B) -> ~(A ^ B)
  3061. // (A | B) ^ ~(B & A) -> ~(A ^ B)
  3062. // (A & B) ^ ~(A | B) -> ~(A ^ B)
  3063. // (A & B) ^ ~(B | A) -> ~(A ^ B)
  3064. // Complexity sorting ensures the not will be on the right side.
  3065. if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
  3066. match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
  3067. (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  3068. match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
  3069. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  3070. return nullptr;
  3071. }
  3072. Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
  3073. BinaryOperator &I) {
  3074. assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
  3075. I.getOperand(1) == RHS && "Should be 'xor' with these operands");
  3076. ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  3077. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  3078. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  3079. if (predicatesFoldable(PredL, PredR)) {
  3080. if (LHS0 == RHS1 && LHS1 == RHS0) {
  3081. std::swap(LHS0, LHS1);
  3082. PredL = ICmpInst::getSwappedPredicate(PredL);
  3083. }
  3084. if (LHS0 == RHS0 && LHS1 == RHS1) {
  3085. // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
  3086. unsigned Code = getICmpCode(PredL) ^ getICmpCode(PredR);
  3087. bool IsSigned = LHS->isSigned() || RHS->isSigned();
  3088. return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
  3089. }
  3090. }
  3091. // TODO: This can be generalized to compares of non-signbits using
  3092. // decomposeBitTestICmp(). It could be enhanced more by using (something like)
  3093. // foldLogOpOfMaskedICmps().
  3094. const APInt *LC, *RC;
  3095. if (match(LHS1, m_APInt(LC)) && match(RHS1, m_APInt(RC)) &&
  3096. LHS0->getType() == RHS0->getType() &&
  3097. LHS0->getType()->isIntOrIntVectorTy() &&
  3098. (LHS->hasOneUse() || RHS->hasOneUse())) {
  3099. // Convert xor of signbit tests to signbit test of xor'd values:
  3100. // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
  3101. // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
  3102. // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
  3103. // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
  3104. bool TrueIfSignedL, TrueIfSignedR;
  3105. if (isSignBitCheck(PredL, *LC, TrueIfSignedL) &&
  3106. isSignBitCheck(PredR, *RC, TrueIfSignedR)) {
  3107. Value *XorLR = Builder.CreateXor(LHS0, RHS0);
  3108. return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(XorLR) :
  3109. Builder.CreateIsNotNeg(XorLR);
  3110. }
  3111. // (X > C) ^ (X < C + 2) --> X != C + 1
  3112. // (X < C + 2) ^ (X > C) --> X != C + 1
  3113. // Considering the correctness of this pattern, we should avoid that C is
  3114. // non-negative and C + 2 is negative, although it will be matched by other
  3115. // patterns.
  3116. const APInt *C1, *C2;
  3117. if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_APInt(C1)) &&
  3118. PredR == CmpInst::ICMP_SLT && match(RHS1, m_APInt(C2))) ||
  3119. (PredL == CmpInst::ICMP_SLT && match(LHS1, m_APInt(C2)) &&
  3120. PredR == CmpInst::ICMP_SGT && match(RHS1, m_APInt(C1))))
  3121. if (LHS0 == RHS0 && *C1 + 2 == *C2 &&
  3122. (C1->isNegative() || C2->isNonNegative()))
  3123. return Builder.CreateICmpNE(LHS0,
  3124. ConstantInt::get(LHS0->getType(), *C1 + 1));
  3125. }
  3126. // Instead of trying to imitate the folds for and/or, decompose this 'xor'
  3127. // into those logic ops. That is, try to turn this into an and-of-icmps
  3128. // because we have many folds for that pattern.
  3129. //
  3130. // This is based on a truth table definition of xor:
  3131. // X ^ Y --> (X | Y) & !(X & Y)
  3132. if (Value *OrICmp = simplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
  3133. // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
  3134. // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
  3135. if (Value *AndICmp = simplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
  3136. // TODO: Independently handle cases where the 'and' side is a constant.
  3137. ICmpInst *X = nullptr, *Y = nullptr;
  3138. if (OrICmp == LHS && AndICmp == RHS) {
  3139. // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS --> X & !Y
  3140. X = LHS;
  3141. Y = RHS;
  3142. }
  3143. if (OrICmp == RHS && AndICmp == LHS) {
  3144. // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS --> !Y & X
  3145. X = RHS;
  3146. Y = LHS;
  3147. }
  3148. if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
  3149. // Invert the predicate of 'Y', thus inverting its output.
  3150. Y->setPredicate(Y->getInversePredicate());
  3151. // So, are there other uses of Y?
  3152. if (!Y->hasOneUse()) {
  3153. // We need to adapt other uses of Y though. Get a value that matches
  3154. // the original value of Y before inversion. While this increases
  3155. // immediate instruction count, we have just ensured that all the
  3156. // users are freely-invertible, so that 'not' *will* get folded away.
  3157. BuilderTy::InsertPointGuard Guard(Builder);
  3158. // Set insertion point to right after the Y.
  3159. Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
  3160. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  3161. // Replace all uses of Y (excluding the one in NotY!) with NotY.
  3162. Worklist.pushUsersToWorkList(*Y);
  3163. Y->replaceUsesWithIf(NotY,
  3164. [NotY](Use &U) { return U.getUser() != NotY; });
  3165. }
  3166. // All done.
  3167. return Builder.CreateAnd(LHS, RHS);
  3168. }
  3169. }
  3170. }
  3171. return nullptr;
  3172. }
  3173. /// If we have a masked merge, in the canonical form of:
  3174. /// (assuming that A only has one use.)
  3175. /// | A | |B|
  3176. /// ((x ^ y) & M) ^ y
  3177. /// | D |
  3178. /// * If M is inverted:
  3179. /// | D |
  3180. /// ((x ^ y) & ~M) ^ y
  3181. /// We can canonicalize by swapping the final xor operand
  3182. /// to eliminate the 'not' of the mask.
  3183. /// ((x ^ y) & M) ^ x
  3184. /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
  3185. /// because that shortens the dependency chain and improves analysis:
  3186. /// (x & M) | (y & ~M)
  3187. static Instruction *visitMaskedMerge(BinaryOperator &I,
  3188. InstCombiner::BuilderTy &Builder) {
  3189. Value *B, *X, *D;
  3190. Value *M;
  3191. if (!match(&I, m_c_Xor(m_Value(B),
  3192. m_OneUse(m_c_And(
  3193. m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
  3194. m_Value(D)),
  3195. m_Value(M))))))
  3196. return nullptr;
  3197. Value *NotM;
  3198. if (match(M, m_Not(m_Value(NotM)))) {
  3199. // De-invert the mask and swap the value in B part.
  3200. Value *NewA = Builder.CreateAnd(D, NotM);
  3201. return BinaryOperator::CreateXor(NewA, X);
  3202. }
  3203. Constant *C;
  3204. if (D->hasOneUse() && match(M, m_Constant(C))) {
  3205. // Propagating undef is unsafe. Clamp undef elements to -1.
  3206. Type *EltTy = C->getType()->getScalarType();
  3207. C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
  3208. // Unfold.
  3209. Value *LHS = Builder.CreateAnd(X, C);
  3210. Value *NotC = Builder.CreateNot(C);
  3211. Value *RHS = Builder.CreateAnd(B, NotC);
  3212. return BinaryOperator::CreateOr(LHS, RHS);
  3213. }
  3214. return nullptr;
  3215. }
  3216. // Transform
  3217. // ~(x ^ y)
  3218. // into:
  3219. // (~x) ^ y
  3220. // or into
  3221. // x ^ (~y)
  3222. static Instruction *sinkNotIntoXor(BinaryOperator &I, Value *X, Value *Y,
  3223. InstCombiner::BuilderTy &Builder) {
  3224. // We only want to do the transform if it is free to do.
  3225. if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
  3226. // Ok, good.
  3227. } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
  3228. std::swap(X, Y);
  3229. } else
  3230. return nullptr;
  3231. Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
  3232. return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
  3233. }
  3234. static Instruction *foldNotXor(BinaryOperator &I,
  3235. InstCombiner::BuilderTy &Builder) {
  3236. Value *X, *Y;
  3237. // FIXME: one-use check is not needed in general, but currently we are unable
  3238. // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
  3239. if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
  3240. return nullptr;
  3241. if (Instruction *NewXor = sinkNotIntoXor(I, X, Y, Builder))
  3242. return NewXor;
  3243. auto hasCommonOperand = [](Value *A, Value *B, Value *C, Value *D) {
  3244. return A == C || A == D || B == C || B == D;
  3245. };
  3246. Value *A, *B, *C, *D;
  3247. // Canonicalize ~((A & B) ^ (A | ?)) -> (A & B) | ~(A | ?)
  3248. // 4 commuted variants
  3249. if (match(X, m_And(m_Value(A), m_Value(B))) &&
  3250. match(Y, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
  3251. Value *NotY = Builder.CreateNot(Y);
  3252. return BinaryOperator::CreateOr(X, NotY);
  3253. };
  3254. // Canonicalize ~((A | ?) ^ (A & B)) -> (A & B) | ~(A | ?)
  3255. // 4 commuted variants
  3256. if (match(Y, m_And(m_Value(A), m_Value(B))) &&
  3257. match(X, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
  3258. Value *NotX = Builder.CreateNot(X);
  3259. return BinaryOperator::CreateOr(Y, NotX);
  3260. };
  3261. return nullptr;
  3262. }
  3263. /// Canonicalize a shifty way to code absolute value to the more common pattern
  3264. /// that uses negation and select.
  3265. static Instruction *canonicalizeAbs(BinaryOperator &Xor,
  3266. InstCombiner::BuilderTy &Builder) {
  3267. assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
  3268. // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
  3269. // We're relying on the fact that we only do this transform when the shift has
  3270. // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
  3271. // instructions).
  3272. Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
  3273. if (Op0->hasNUses(2))
  3274. std::swap(Op0, Op1);
  3275. Type *Ty = Xor.getType();
  3276. Value *A;
  3277. const APInt *ShAmt;
  3278. if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
  3279. Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
  3280. match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
  3281. // Op1 = ashr i32 A, 31 ; smear the sign bit
  3282. // xor (add A, Op1), Op1 ; add -1 and flip bits if negative
  3283. // --> (A < 0) ? -A : A
  3284. Value *IsNeg = Builder.CreateIsNeg(A);
  3285. // Copy the nuw/nsw flags from the add to the negate.
  3286. auto *Add = cast<BinaryOperator>(Op0);
  3287. Value *NegA = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
  3288. Add->hasNoSignedWrap());
  3289. return SelectInst::Create(IsNeg, NegA, A);
  3290. }
  3291. return nullptr;
  3292. }
  3293. // Transform
  3294. // z = ~(x &/| y)
  3295. // into:
  3296. // z = ((~x) |/& (~y))
  3297. // iff both x and y are free to invert and all uses of z can be freely updated.
  3298. bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
  3299. Value *Op0, *Op1;
  3300. if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
  3301. return false;
  3302. // If this logic op has not been simplified yet, just bail out and let that
  3303. // happen first. Otherwise, the code below may wrongly invert.
  3304. if (Op0 == Op1)
  3305. return false;
  3306. Instruction::BinaryOps NewOpc =
  3307. match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
  3308. bool IsBinaryOp = isa<BinaryOperator>(I);
  3309. // Can our users be adapted?
  3310. if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
  3311. return false;
  3312. // And can the operands be adapted?
  3313. for (Value *Op : {Op0, Op1})
  3314. if (!(InstCombiner::isFreeToInvert(Op, /*WillInvertAllUses=*/true) &&
  3315. (match(Op, m_ImmConstant()) ||
  3316. (isa<Instruction>(Op) &&
  3317. InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(Op),
  3318. /*IgnoredUser=*/&I)))))
  3319. return false;
  3320. for (Value **Op : {&Op0, &Op1}) {
  3321. Value *NotOp;
  3322. if (auto *C = dyn_cast<Constant>(*Op)) {
  3323. NotOp = ConstantExpr::getNot(C);
  3324. } else {
  3325. Builder.SetInsertPoint(
  3326. &*cast<Instruction>(*Op)->getInsertionPointAfterDef());
  3327. NotOp = Builder.CreateNot(*Op, (*Op)->getName() + ".not");
  3328. (*Op)->replaceUsesWithIf(
  3329. NotOp, [NotOp](Use &U) { return U.getUser() != NotOp; });
  3330. freelyInvertAllUsersOf(NotOp, /*IgnoredUser=*/&I);
  3331. }
  3332. *Op = NotOp;
  3333. }
  3334. Builder.SetInsertPoint(I.getInsertionPointAfterDef());
  3335. Value *NewLogicOp;
  3336. if (IsBinaryOp)
  3337. NewLogicOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
  3338. else
  3339. NewLogicOp =
  3340. Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
  3341. replaceInstUsesWith(I, NewLogicOp);
  3342. // We can not just create an outer `not`, it will most likely be immediately
  3343. // folded back, reconstructing our initial pattern, and causing an
  3344. // infinite combine loop, so immediately manually fold it away.
  3345. freelyInvertAllUsersOf(NewLogicOp);
  3346. return true;
  3347. }
  3348. // Transform
  3349. // z = (~x) &/| y
  3350. // into:
  3351. // z = ~(x |/& (~y))
  3352. // iff y is free to invert and all uses of z can be freely updated.
  3353. bool InstCombinerImpl::sinkNotIntoOtherHandOfLogicalOp(Instruction &I) {
  3354. Value *Op0, *Op1;
  3355. if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
  3356. return false;
  3357. Instruction::BinaryOps NewOpc =
  3358. match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
  3359. bool IsBinaryOp = isa<BinaryOperator>(I);
  3360. Value *NotOp0 = nullptr;
  3361. Value *NotOp1 = nullptr;
  3362. Value **OpToInvert = nullptr;
  3363. if (match(Op0, m_Not(m_Value(NotOp0))) &&
  3364. InstCombiner::isFreeToInvert(Op1, /*WillInvertAllUses=*/true) &&
  3365. (match(Op1, m_ImmConstant()) ||
  3366. (isa<Instruction>(Op1) &&
  3367. InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(Op1),
  3368. /*IgnoredUser=*/&I)))) {
  3369. Op0 = NotOp0;
  3370. OpToInvert = &Op1;
  3371. } else if (match(Op1, m_Not(m_Value(NotOp1))) &&
  3372. InstCombiner::isFreeToInvert(Op0, /*WillInvertAllUses=*/true) &&
  3373. (match(Op0, m_ImmConstant()) ||
  3374. (isa<Instruction>(Op0) &&
  3375. InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(Op0),
  3376. /*IgnoredUser=*/&I)))) {
  3377. Op1 = NotOp1;
  3378. OpToInvert = &Op0;
  3379. } else
  3380. return false;
  3381. // And can our users be adapted?
  3382. if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
  3383. return false;
  3384. if (auto *C = dyn_cast<Constant>(*OpToInvert)) {
  3385. *OpToInvert = ConstantExpr::getNot(C);
  3386. } else {
  3387. Builder.SetInsertPoint(
  3388. &*cast<Instruction>(*OpToInvert)->getInsertionPointAfterDef());
  3389. Value *NotOpToInvert =
  3390. Builder.CreateNot(*OpToInvert, (*OpToInvert)->getName() + ".not");
  3391. (*OpToInvert)->replaceUsesWithIf(NotOpToInvert, [NotOpToInvert](Use &U) {
  3392. return U.getUser() != NotOpToInvert;
  3393. });
  3394. freelyInvertAllUsersOf(NotOpToInvert, /*IgnoredUser=*/&I);
  3395. *OpToInvert = NotOpToInvert;
  3396. }
  3397. Builder.SetInsertPoint(&*I.getInsertionPointAfterDef());
  3398. Value *NewBinOp;
  3399. if (IsBinaryOp)
  3400. NewBinOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
  3401. else
  3402. NewBinOp = Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
  3403. replaceInstUsesWith(I, NewBinOp);
  3404. // We can not just create an outer `not`, it will most likely be immediately
  3405. // folded back, reconstructing our initial pattern, and causing an
  3406. // infinite combine loop, so immediately manually fold it away.
  3407. freelyInvertAllUsersOf(NewBinOp);
  3408. return true;
  3409. }
  3410. Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
  3411. Value *NotOp;
  3412. if (!match(&I, m_Not(m_Value(NotOp))))
  3413. return nullptr;
  3414. // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
  3415. // We must eliminate the and/or (one-use) for these transforms to not increase
  3416. // the instruction count.
  3417. //
  3418. // ~(~X & Y) --> (X | ~Y)
  3419. // ~(Y & ~X) --> (X | ~Y)
  3420. //
  3421. // Note: The logical matches do not check for the commuted patterns because
  3422. // those are handled via SimplifySelectsFeedingBinaryOp().
  3423. Type *Ty = I.getType();
  3424. Value *X, *Y;
  3425. if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
  3426. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  3427. return BinaryOperator::CreateOr(X, NotY);
  3428. }
  3429. if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
  3430. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  3431. return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
  3432. }
  3433. // ~(~X | Y) --> (X & ~Y)
  3434. // ~(Y | ~X) --> (X & ~Y)
  3435. if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
  3436. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  3437. return BinaryOperator::CreateAnd(X, NotY);
  3438. }
  3439. if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
  3440. Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
  3441. return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
  3442. }
  3443. // Is this a 'not' (~) fed by a binary operator?
  3444. BinaryOperator *NotVal;
  3445. if (match(NotOp, m_BinOp(NotVal))) {
  3446. // ~((-X) | Y) --> (X - 1) & (~Y)
  3447. if (match(NotVal,
  3448. m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
  3449. Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
  3450. Value *NotY = Builder.CreateNot(Y);
  3451. return BinaryOperator::CreateAnd(DecX, NotY);
  3452. }
  3453. // ~(~X >>s Y) --> (X >>s Y)
  3454. if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
  3455. return BinaryOperator::CreateAShr(X, Y);
  3456. // Bit-hack form of a signbit test:
  3457. // iN ~X >>s (N-1) --> sext i1 (X > -1) to iN
  3458. unsigned FullShift = Ty->getScalarSizeInBits() - 1;
  3459. if (match(NotVal, m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))))) {
  3460. Value *IsNotNeg = Builder.CreateIsNotNeg(X, "isnotneg");
  3461. return new SExtInst(IsNotNeg, Ty);
  3462. }
  3463. // If we are inverting a right-shifted constant, we may be able to eliminate
  3464. // the 'not' by inverting the constant and using the opposite shift type.
  3465. // Canonicalization rules ensure that only a negative constant uses 'ashr',
  3466. // but we must check that in case that transform has not fired yet.
  3467. // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
  3468. Constant *C;
  3469. if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
  3470. match(C, m_Negative())) {
  3471. // We matched a negative constant, so propagating undef is unsafe.
  3472. // Clamp undef elements to -1.
  3473. Type *EltTy = Ty->getScalarType();
  3474. C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
  3475. return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
  3476. }
  3477. // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
  3478. if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
  3479. match(C, m_NonNegative())) {
  3480. // We matched a non-negative constant, so propagating undef is unsafe.
  3481. // Clamp undef elements to 0.
  3482. Type *EltTy = Ty->getScalarType();
  3483. C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
  3484. return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
  3485. }
  3486. // ~(X + C) --> ~C - X
  3487. if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
  3488. return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
  3489. // ~(X - Y) --> ~X + Y
  3490. // FIXME: is it really beneficial to sink the `not` here?
  3491. if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
  3492. if (isa<Constant>(X) || NotVal->hasOneUse())
  3493. return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
  3494. // ~(~X + Y) --> X - Y
  3495. if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
  3496. return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
  3497. NotVal);
  3498. }
  3499. // not (cmp A, B) = !cmp A, B
  3500. CmpInst::Predicate Pred;
  3501. if (match(NotOp, m_Cmp(Pred, m_Value(), m_Value())) &&
  3502. (NotOp->hasOneUse() ||
  3503. InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(NotOp),
  3504. /*IgnoredUser=*/nullptr))) {
  3505. cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
  3506. freelyInvertAllUsersOf(NotOp);
  3507. return &I;
  3508. }
  3509. // Move a 'not' ahead of casts of a bool to enable logic reduction:
  3510. // not (bitcast (sext i1 X)) --> bitcast (sext (not i1 X))
  3511. if (match(NotOp, m_OneUse(m_BitCast(m_OneUse(m_SExt(m_Value(X)))))) && X->getType()->isIntOrIntVectorTy(1)) {
  3512. Type *SextTy = cast<BitCastOperator>(NotOp)->getSrcTy();
  3513. Value *NotX = Builder.CreateNot(X);
  3514. Value *Sext = Builder.CreateSExt(NotX, SextTy);
  3515. return CastInst::CreateBitOrPointerCast(Sext, Ty);
  3516. }
  3517. if (auto *NotOpI = dyn_cast<Instruction>(NotOp))
  3518. if (sinkNotIntoLogicalOp(*NotOpI))
  3519. return &I;
  3520. // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
  3521. // ~min(~X, ~Y) --> max(X, Y)
  3522. // ~max(~X, Y) --> min(X, ~Y)
  3523. auto *II = dyn_cast<IntrinsicInst>(NotOp);
  3524. if (II && II->hasOneUse()) {
  3525. if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
  3526. isFreeToInvert(X, X->hasOneUse()) &&
  3527. isFreeToInvert(Y, Y->hasOneUse())) {
  3528. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
  3529. Value *NotX = Builder.CreateNot(X);
  3530. Value *NotY = Builder.CreateNot(Y);
  3531. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
  3532. return replaceInstUsesWith(I, InvMaxMin);
  3533. }
  3534. if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
  3535. Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
  3536. Value *NotY = Builder.CreateNot(Y);
  3537. Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
  3538. return replaceInstUsesWith(I, InvMaxMin);
  3539. }
  3540. if (II->getIntrinsicID() == Intrinsic::is_fpclass) {
  3541. ConstantInt *ClassMask = cast<ConstantInt>(II->getArgOperand(1));
  3542. II->setArgOperand(
  3543. 1, ConstantInt::get(ClassMask->getType(),
  3544. ~ClassMask->getZExtValue() & fcAllFlags));
  3545. return replaceInstUsesWith(I, II);
  3546. }
  3547. }
  3548. if (NotOp->hasOneUse()) {
  3549. // Pull 'not' into operands of select if both operands are one-use compares
  3550. // or one is one-use compare and the other one is a constant.
  3551. // Inverting the predicates eliminates the 'not' operation.
  3552. // Example:
  3553. // not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
  3554. // select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
  3555. // not (select ?, (cmp TPred, ?, ?), true -->
  3556. // select ?, (cmp InvTPred, ?, ?), false
  3557. if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
  3558. Value *TV = Sel->getTrueValue();
  3559. Value *FV = Sel->getFalseValue();
  3560. auto *CmpT = dyn_cast<CmpInst>(TV);
  3561. auto *CmpF = dyn_cast<CmpInst>(FV);
  3562. bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
  3563. bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
  3564. if (InvertibleT && InvertibleF) {
  3565. if (CmpT)
  3566. CmpT->setPredicate(CmpT->getInversePredicate());
  3567. else
  3568. Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
  3569. if (CmpF)
  3570. CmpF->setPredicate(CmpF->getInversePredicate());
  3571. else
  3572. Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
  3573. return replaceInstUsesWith(I, Sel);
  3574. }
  3575. }
  3576. }
  3577. if (Instruction *NewXor = foldNotXor(I, Builder))
  3578. return NewXor;
  3579. return nullptr;
  3580. }
  3581. // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
  3582. // here. We should standardize that construct where it is needed or choose some
  3583. // other way to ensure that commutated variants of patterns are not missed.
  3584. Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
  3585. if (Value *V = simplifyXorInst(I.getOperand(0), I.getOperand(1),
  3586. SQ.getWithInstruction(&I)))
  3587. return replaceInstUsesWith(I, V);
  3588. if (SimplifyAssociativeOrCommutative(I))
  3589. return &I;
  3590. if (Instruction *X = foldVectorBinop(I))
  3591. return X;
  3592. if (Instruction *Phi = foldBinopWithPhiOperands(I))
  3593. return Phi;
  3594. if (Instruction *NewXor = foldXorToXor(I, Builder))
  3595. return NewXor;
  3596. // (A&B)^(A&C) -> A&(B^C) etc
  3597. if (Value *V = foldUsingDistributiveLaws(I))
  3598. return replaceInstUsesWith(I, V);
  3599. // See if we can simplify any instructions used by the instruction whose sole
  3600. // purpose is to compute bits we don't care about.
  3601. if (SimplifyDemandedInstructionBits(I))
  3602. return &I;
  3603. if (Value *V = SimplifyBSwap(I, Builder))
  3604. return replaceInstUsesWith(I, V);
  3605. if (Instruction *R = foldNot(I))
  3606. return R;
  3607. // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
  3608. // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
  3609. // calls in there are unnecessary as SimplifyDemandedInstructionBits should
  3610. // have already taken care of those cases.
  3611. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  3612. Value *M;
  3613. if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
  3614. m_c_And(m_Deferred(M), m_Value()))))
  3615. return BinaryOperator::CreateOr(Op0, Op1);
  3616. if (Instruction *Xor = visitMaskedMerge(I, Builder))
  3617. return Xor;
  3618. Value *X, *Y;
  3619. Constant *C1;
  3620. if (match(Op1, m_Constant(C1))) {
  3621. Constant *C2;
  3622. if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) &&
  3623. match(C1, m_ImmConstant())) {
  3624. // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2)
  3625. C2 = Constant::replaceUndefsWith(
  3626. C2, Constant::getAllOnesValue(C2->getType()->getScalarType()));
  3627. Value *And = Builder.CreateAnd(
  3628. X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1));
  3629. return BinaryOperator::CreateXor(
  3630. And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1));
  3631. }
  3632. // Use DeMorgan and reassociation to eliminate a 'not' op.
  3633. if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
  3634. // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
  3635. Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
  3636. return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
  3637. }
  3638. if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
  3639. // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
  3640. Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
  3641. return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
  3642. }
  3643. // Convert xor ([trunc] (ashr X, BW-1)), C =>
  3644. // select(X >s -1, C, ~C)
  3645. // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
  3646. // constant depending on whether this input is less than 0.
  3647. const APInt *CA;
  3648. if (match(Op0, m_OneUse(m_TruncOrSelf(
  3649. m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
  3650. *CA == X->getType()->getScalarSizeInBits() - 1 &&
  3651. !match(C1, m_AllOnes())) {
  3652. assert(!C1->isZeroValue() && "Unexpected xor with 0");
  3653. Value *IsNotNeg = Builder.CreateIsNotNeg(X);
  3654. return SelectInst::Create(IsNotNeg, Op1, Builder.CreateNot(Op1));
  3655. }
  3656. }
  3657. Type *Ty = I.getType();
  3658. {
  3659. const APInt *RHSC;
  3660. if (match(Op1, m_APInt(RHSC))) {
  3661. Value *X;
  3662. const APInt *C;
  3663. // (C - X) ^ signmaskC --> (C + signmaskC) - X
  3664. if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
  3665. return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
  3666. // (X + C) ^ signmaskC --> X + (C + signmaskC)
  3667. if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
  3668. return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
  3669. // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
  3670. if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
  3671. MaskedValueIsZero(X, *C, 0, &I))
  3672. return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
  3673. // When X is a power-of-two or zero and zero input is poison:
  3674. // ctlz(i32 X) ^ 31 --> cttz(X)
  3675. // cttz(i32 X) ^ 31 --> ctlz(X)
  3676. auto *II = dyn_cast<IntrinsicInst>(Op0);
  3677. if (II && II->hasOneUse() && *RHSC == Ty->getScalarSizeInBits() - 1) {
  3678. Intrinsic::ID IID = II->getIntrinsicID();
  3679. if ((IID == Intrinsic::ctlz || IID == Intrinsic::cttz) &&
  3680. match(II->getArgOperand(1), m_One()) &&
  3681. isKnownToBeAPowerOfTwo(II->getArgOperand(0), /*OrZero */ true)) {
  3682. IID = (IID == Intrinsic::ctlz) ? Intrinsic::cttz : Intrinsic::ctlz;
  3683. Function *F = Intrinsic::getDeclaration(II->getModule(), IID, Ty);
  3684. return CallInst::Create(F, {II->getArgOperand(0), Builder.getTrue()});
  3685. }
  3686. }
  3687. // If RHSC is inverting the remaining bits of shifted X,
  3688. // canonicalize to a 'not' before the shift to help SCEV and codegen:
  3689. // (X << C) ^ RHSC --> ~X << C
  3690. if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
  3691. *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
  3692. Value *NotX = Builder.CreateNot(X);
  3693. return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
  3694. }
  3695. // (X >>u C) ^ RHSC --> ~X >>u C
  3696. if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
  3697. *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
  3698. Value *NotX = Builder.CreateNot(X);
  3699. return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
  3700. }
  3701. // TODO: We could handle 'ashr' here as well. That would be matching
  3702. // a 'not' op and moving it before the shift. Doing that requires
  3703. // preventing the inverse fold in canShiftBinOpWithConstantRHS().
  3704. }
  3705. }
  3706. // FIXME: This should not be limited to scalar (pull into APInt match above).
  3707. {
  3708. Value *X;
  3709. ConstantInt *C1, *C2, *C3;
  3710. // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
  3711. if (match(Op1, m_ConstantInt(C3)) &&
  3712. match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
  3713. m_ConstantInt(C2))) &&
  3714. Op0->hasOneUse()) {
  3715. // fold (C1 >> C2) ^ C3
  3716. APInt FoldConst = C1->getValue().lshr(C2->getValue());
  3717. FoldConst ^= C3->getValue();
  3718. // Prepare the two operands.
  3719. auto *Opnd0 = Builder.CreateLShr(X, C2);
  3720. Opnd0->takeName(Op0);
  3721. return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
  3722. }
  3723. }
  3724. if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
  3725. return FoldedLogic;
  3726. // Y ^ (X | Y) --> X & ~Y
  3727. // Y ^ (Y | X) --> X & ~Y
  3728. if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
  3729. return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
  3730. // (X | Y) ^ Y --> X & ~Y
  3731. // (Y | X) ^ Y --> X & ~Y
  3732. if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
  3733. return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
  3734. // Y ^ (X & Y) --> ~X & Y
  3735. // Y ^ (Y & X) --> ~X & Y
  3736. if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
  3737. return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
  3738. // (X & Y) ^ Y --> ~X & Y
  3739. // (Y & X) ^ Y --> ~X & Y
  3740. // Canonical form is (X & C) ^ C; don't touch that.
  3741. // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
  3742. // be fixed to prefer that (otherwise we get infinite looping).
  3743. if (!match(Op1, m_Constant()) &&
  3744. match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
  3745. return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
  3746. Value *A, *B, *C;
  3747. // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
  3748. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
  3749. m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
  3750. return BinaryOperator::CreateXor(
  3751. Builder.CreateAnd(Builder.CreateNot(A), C), B);
  3752. // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
  3753. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
  3754. m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
  3755. return BinaryOperator::CreateXor(
  3756. Builder.CreateAnd(Builder.CreateNot(B), C), A);
  3757. // (A & B) ^ (A ^ B) -> (A | B)
  3758. if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
  3759. match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
  3760. return BinaryOperator::CreateOr(A, B);
  3761. // (A ^ B) ^ (A & B) -> (A | B)
  3762. if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
  3763. match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
  3764. return BinaryOperator::CreateOr(A, B);
  3765. // (A & ~B) ^ ~A -> ~(A & B)
  3766. // (~B & A) ^ ~A -> ~(A & B)
  3767. if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
  3768. match(Op1, m_Not(m_Specific(A))))
  3769. return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
  3770. // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
  3771. if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
  3772. return BinaryOperator::CreateOr(A, B);
  3773. // (~A | B) ^ A --> ~(A & B)
  3774. if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
  3775. return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
  3776. // A ^ (~A | B) --> ~(A & B)
  3777. if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
  3778. return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
  3779. // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
  3780. // TODO: Loosen one-use restriction if common operand is a constant.
  3781. Value *D;
  3782. if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
  3783. match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
  3784. if (B == C || B == D)
  3785. std::swap(A, B);
  3786. if (A == C)
  3787. std::swap(C, D);
  3788. if (A == D) {
  3789. Value *NotA = Builder.CreateNot(A);
  3790. return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
  3791. }
  3792. }
  3793. if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
  3794. if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
  3795. if (Value *V = foldXorOfICmps(LHS, RHS, I))
  3796. return replaceInstUsesWith(I, V);
  3797. if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
  3798. return CastedXor;
  3799. if (Instruction *Abs = canonicalizeAbs(I, Builder))
  3800. return Abs;
  3801. // Otherwise, if all else failed, try to hoist the xor-by-constant:
  3802. // (X ^ C) ^ Y --> (X ^ Y) ^ C
  3803. // Just like we do in other places, we completely avoid the fold
  3804. // for constantexprs, at least to avoid endless combine loop.
  3805. if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
  3806. m_Unless(m_ConstantExpr())),
  3807. m_ImmConstant(C1))),
  3808. m_Value(Y))))
  3809. return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
  3810. if (Instruction *R = reassociateForUses(I, Builder))
  3811. return R;
  3812. if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
  3813. return Canonicalized;
  3814. if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
  3815. return Folded;
  3816. if (Instruction *Folded = canonicalizeConditionalNegationViaMathToSelect(I))
  3817. return Folded;
  3818. return nullptr;
  3819. }