InstCombineSelect.cpp 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  1. //===- InstCombineSelect.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 visitSelect function.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/CmpInstAnalysis.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/OverflowInstAnalysis.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/Analysis/VectorUtils.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/Constant.h"
  24. #include "llvm/IR/ConstantRange.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/IRBuilder.h"
  28. #include "llvm/IR/InstrTypes.h"
  29. #include "llvm/IR/Instruction.h"
  30. #include "llvm/IR/Instructions.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "llvm/IR/PatternMatch.h"
  35. #include "llvm/IR/Type.h"
  36. #include "llvm/IR/User.h"
  37. #include "llvm/IR/Value.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. #include "llvm/Support/KnownBits.h"
  41. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  42. #include <cassert>
  43. #include <utility>
  44. #define DEBUG_TYPE "instcombine"
  45. #include "llvm/Transforms/Utils/InstructionWorklist.h"
  46. using namespace llvm;
  47. using namespace PatternMatch;
  48. /// Replace a select operand based on an equality comparison with the identity
  49. /// constant of a binop.
  50. static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
  51. const TargetLibraryInfo &TLI,
  52. InstCombinerImpl &IC) {
  53. // The select condition must be an equality compare with a constant operand.
  54. Value *X;
  55. Constant *C;
  56. CmpInst::Predicate Pred;
  57. if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
  58. return nullptr;
  59. bool IsEq;
  60. if (ICmpInst::isEquality(Pred))
  61. IsEq = Pred == ICmpInst::ICMP_EQ;
  62. else if (Pred == FCmpInst::FCMP_OEQ)
  63. IsEq = true;
  64. else if (Pred == FCmpInst::FCMP_UNE)
  65. IsEq = false;
  66. else
  67. return nullptr;
  68. // A select operand must be a binop.
  69. BinaryOperator *BO;
  70. if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
  71. return nullptr;
  72. // The compare constant must be the identity constant for that binop.
  73. // If this a floating-point compare with 0.0, any zero constant will do.
  74. Type *Ty = BO->getType();
  75. Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
  76. if (IdC != C) {
  77. if (!IdC || !CmpInst::isFPPredicate(Pred))
  78. return nullptr;
  79. if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
  80. return nullptr;
  81. }
  82. // Last, match the compare variable operand with a binop operand.
  83. Value *Y;
  84. if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
  85. return nullptr;
  86. if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
  87. return nullptr;
  88. // +0.0 compares equal to -0.0, and so it does not behave as required for this
  89. // transform. Bail out if we can not exclude that possibility.
  90. if (isa<FPMathOperator>(BO))
  91. if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
  92. return nullptr;
  93. // BO = binop Y, X
  94. // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
  95. // =>
  96. // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
  97. return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
  98. }
  99. /// This folds:
  100. /// select (icmp eq (and X, C1)), TC, FC
  101. /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
  102. /// To something like:
  103. /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
  104. /// Or:
  105. /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
  106. /// With some variations depending if FC is larger than TC, or the shift
  107. /// isn't needed, or the bit widths don't match.
  108. static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
  109. InstCombiner::BuilderTy &Builder) {
  110. const APInt *SelTC, *SelFC;
  111. if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
  112. !match(Sel.getFalseValue(), m_APInt(SelFC)))
  113. return nullptr;
  114. // If this is a vector select, we need a vector compare.
  115. Type *SelType = Sel.getType();
  116. if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
  117. return nullptr;
  118. Value *V;
  119. APInt AndMask;
  120. bool CreateAnd = false;
  121. ICmpInst::Predicate Pred = Cmp->getPredicate();
  122. if (ICmpInst::isEquality(Pred)) {
  123. if (!match(Cmp->getOperand(1), m_Zero()))
  124. return nullptr;
  125. V = Cmp->getOperand(0);
  126. const APInt *AndRHS;
  127. if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
  128. return nullptr;
  129. AndMask = *AndRHS;
  130. } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
  131. Pred, V, AndMask)) {
  132. assert(ICmpInst::isEquality(Pred) && "Not equality test?");
  133. if (!AndMask.isPowerOf2())
  134. return nullptr;
  135. CreateAnd = true;
  136. } else {
  137. return nullptr;
  138. }
  139. // In general, when both constants are non-zero, we would need an offset to
  140. // replace the select. This would require more instructions than we started
  141. // with. But there's one special-case that we handle here because it can
  142. // simplify/reduce the instructions.
  143. APInt TC = *SelTC;
  144. APInt FC = *SelFC;
  145. if (!TC.isZero() && !FC.isZero()) {
  146. // If the select constants differ by exactly one bit and that's the same
  147. // bit that is masked and checked by the select condition, the select can
  148. // be replaced by bitwise logic to set/clear one bit of the constant result.
  149. if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
  150. return nullptr;
  151. if (CreateAnd) {
  152. // If we have to create an 'and', then we must kill the cmp to not
  153. // increase the instruction count.
  154. if (!Cmp->hasOneUse())
  155. return nullptr;
  156. V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
  157. }
  158. bool ExtraBitInTC = TC.ugt(FC);
  159. if (Pred == ICmpInst::ICMP_EQ) {
  160. // If the masked bit in V is clear, clear or set the bit in the result:
  161. // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
  162. // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
  163. Constant *C = ConstantInt::get(SelType, TC);
  164. return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
  165. }
  166. if (Pred == ICmpInst::ICMP_NE) {
  167. // If the masked bit in V is set, set or clear the bit in the result:
  168. // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
  169. // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
  170. Constant *C = ConstantInt::get(SelType, FC);
  171. return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
  172. }
  173. llvm_unreachable("Only expecting equality predicates");
  174. }
  175. // Make sure one of the select arms is a power-of-2.
  176. if (!TC.isPowerOf2() && !FC.isPowerOf2())
  177. return nullptr;
  178. // Determine which shift is needed to transform result of the 'and' into the
  179. // desired result.
  180. const APInt &ValC = !TC.isZero() ? TC : FC;
  181. unsigned ValZeros = ValC.logBase2();
  182. unsigned AndZeros = AndMask.logBase2();
  183. // Insert the 'and' instruction on the input to the truncate.
  184. if (CreateAnd)
  185. V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
  186. // If types don't match, we can still convert the select by introducing a zext
  187. // or a trunc of the 'and'.
  188. if (ValZeros > AndZeros) {
  189. V = Builder.CreateZExtOrTrunc(V, SelType);
  190. V = Builder.CreateShl(V, ValZeros - AndZeros);
  191. } else if (ValZeros < AndZeros) {
  192. V = Builder.CreateLShr(V, AndZeros - ValZeros);
  193. V = Builder.CreateZExtOrTrunc(V, SelType);
  194. } else {
  195. V = Builder.CreateZExtOrTrunc(V, SelType);
  196. }
  197. // Okay, now we know that everything is set up, we just don't know whether we
  198. // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
  199. bool ShouldNotVal = !TC.isZero();
  200. ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
  201. if (ShouldNotVal)
  202. V = Builder.CreateXor(V, ValC);
  203. return V;
  204. }
  205. /// We want to turn code that looks like this:
  206. /// %C = or %A, %B
  207. /// %D = select %cond, %C, %A
  208. /// into:
  209. /// %C = select %cond, %B, 0
  210. /// %D = or %A, %C
  211. ///
  212. /// Assuming that the specified instruction is an operand to the select, return
  213. /// a bitmask indicating which operands of this instruction are foldable if they
  214. /// equal the other incoming value of the select.
  215. static unsigned getSelectFoldableOperands(BinaryOperator *I) {
  216. switch (I->getOpcode()) {
  217. case Instruction::Add:
  218. case Instruction::FAdd:
  219. case Instruction::Mul:
  220. case Instruction::FMul:
  221. case Instruction::And:
  222. case Instruction::Or:
  223. case Instruction::Xor:
  224. return 3; // Can fold through either operand.
  225. case Instruction::Sub: // Can only fold on the amount subtracted.
  226. case Instruction::FSub:
  227. case Instruction::FDiv: // Can only fold on the divisor amount.
  228. case Instruction::Shl: // Can only fold on the shift amount.
  229. case Instruction::LShr:
  230. case Instruction::AShr:
  231. return 1;
  232. default:
  233. return 0; // Cannot fold
  234. }
  235. }
  236. /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
  237. Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
  238. Instruction *FI) {
  239. // Don't break up min/max patterns. The hasOneUse checks below prevent that
  240. // for most cases, but vector min/max with bitcasts can be transformed. If the
  241. // one-use restrictions are eased for other patterns, we still don't want to
  242. // obfuscate min/max.
  243. if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
  244. match(&SI, m_SMax(m_Value(), m_Value())) ||
  245. match(&SI, m_UMin(m_Value(), m_Value())) ||
  246. match(&SI, m_UMax(m_Value(), m_Value()))))
  247. return nullptr;
  248. // If this is a cast from the same type, merge.
  249. Value *Cond = SI.getCondition();
  250. Type *CondTy = Cond->getType();
  251. if (TI->getNumOperands() == 1 && TI->isCast()) {
  252. Type *FIOpndTy = FI->getOperand(0)->getType();
  253. if (TI->getOperand(0)->getType() != FIOpndTy)
  254. return nullptr;
  255. // The select condition may be a vector. We may only change the operand
  256. // type if the vector width remains the same (and matches the condition).
  257. if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
  258. if (!FIOpndTy->isVectorTy() ||
  259. CondVTy->getElementCount() !=
  260. cast<VectorType>(FIOpndTy)->getElementCount())
  261. return nullptr;
  262. // TODO: If the backend knew how to deal with casts better, we could
  263. // remove this limitation. For now, there's too much potential to create
  264. // worse codegen by promoting the select ahead of size-altering casts
  265. // (PR28160).
  266. //
  267. // Note that ValueTracking's matchSelectPattern() looks through casts
  268. // without checking 'hasOneUse' when it matches min/max patterns, so this
  269. // transform may end up happening anyway.
  270. if (TI->getOpcode() != Instruction::BitCast &&
  271. (!TI->hasOneUse() || !FI->hasOneUse()))
  272. return nullptr;
  273. } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
  274. // TODO: The one-use restrictions for a scalar select could be eased if
  275. // the fold of a select in visitLoadInst() was enhanced to match a pattern
  276. // that includes a cast.
  277. return nullptr;
  278. }
  279. // Fold this by inserting a select from the input values.
  280. Value *NewSI =
  281. Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
  282. SI.getName() + ".v", &SI);
  283. return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
  284. TI->getType());
  285. }
  286. Value *OtherOpT, *OtherOpF;
  287. bool MatchIsOpZero;
  288. auto getCommonOp = [&](Instruction *TI, Instruction *FI, bool Commute,
  289. bool Swapped = false) -> Value * {
  290. assert(!(Commute && Swapped) &&
  291. "Commute and Swapped can't set at the same time");
  292. if (!Swapped) {
  293. if (TI->getOperand(0) == FI->getOperand(0)) {
  294. OtherOpT = TI->getOperand(1);
  295. OtherOpF = FI->getOperand(1);
  296. MatchIsOpZero = true;
  297. return TI->getOperand(0);
  298. } else if (TI->getOperand(1) == FI->getOperand(1)) {
  299. OtherOpT = TI->getOperand(0);
  300. OtherOpF = FI->getOperand(0);
  301. MatchIsOpZero = false;
  302. return TI->getOperand(1);
  303. }
  304. }
  305. if (!Commute && !Swapped)
  306. return nullptr;
  307. // If we are allowing commute or swap of operands, then
  308. // allow a cross-operand match. In that case, MatchIsOpZero
  309. // means that TI's operand 0 (FI's operand 1) is the common op.
  310. if (TI->getOperand(0) == FI->getOperand(1)) {
  311. OtherOpT = TI->getOperand(1);
  312. OtherOpF = FI->getOperand(0);
  313. MatchIsOpZero = true;
  314. return TI->getOperand(0);
  315. } else if (TI->getOperand(1) == FI->getOperand(0)) {
  316. OtherOpT = TI->getOperand(0);
  317. OtherOpF = FI->getOperand(1);
  318. MatchIsOpZero = false;
  319. return TI->getOperand(1);
  320. }
  321. return nullptr;
  322. };
  323. if (TI->hasOneUse() || FI->hasOneUse()) {
  324. // Cond ? -X : -Y --> -(Cond ? X : Y)
  325. Value *X, *Y;
  326. if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y)))) {
  327. // Intersect FMF from the fneg instructions and union those with the
  328. // select.
  329. FastMathFlags FMF = TI->getFastMathFlags();
  330. FMF &= FI->getFastMathFlags();
  331. FMF |= SI.getFastMathFlags();
  332. Value *NewSel =
  333. Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
  334. if (auto *NewSelI = dyn_cast<Instruction>(NewSel))
  335. NewSelI->setFastMathFlags(FMF);
  336. Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewSel);
  337. NewFNeg->setFastMathFlags(FMF);
  338. return NewFNeg;
  339. }
  340. // Min/max intrinsic with a common operand can have the common operand
  341. // pulled after the select. This is the same transform as below for binops,
  342. // but specialized for intrinsic matching and without the restrictive uses
  343. // clause.
  344. auto *TII = dyn_cast<IntrinsicInst>(TI);
  345. auto *FII = dyn_cast<IntrinsicInst>(FI);
  346. if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID()) {
  347. if (match(TII, m_MaxOrMin(m_Value(), m_Value()))) {
  348. if (Value *MatchOp = getCommonOp(TI, FI, true)) {
  349. Value *NewSel =
  350. Builder.CreateSelect(Cond, OtherOpT, OtherOpF, "minmaxop", &SI);
  351. return CallInst::Create(TII->getCalledFunction(), {NewSel, MatchOp});
  352. }
  353. }
  354. }
  355. // icmp with a common operand also can have the common operand
  356. // pulled after the select.
  357. ICmpInst::Predicate TPred, FPred;
  358. if (match(TI, m_ICmp(TPred, m_Value(), m_Value())) &&
  359. match(FI, m_ICmp(FPred, m_Value(), m_Value()))) {
  360. if (TPred == FPred || TPred == CmpInst::getSwappedPredicate(FPred)) {
  361. bool Swapped = TPred != FPred;
  362. if (Value *MatchOp =
  363. getCommonOp(TI, FI, ICmpInst::isEquality(TPred), Swapped)) {
  364. Value *NewSel = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
  365. SI.getName() + ".v", &SI);
  366. return new ICmpInst(
  367. MatchIsOpZero ? TPred : CmpInst::getSwappedPredicate(TPred),
  368. MatchOp, NewSel);
  369. }
  370. }
  371. }
  372. }
  373. // Only handle binary operators (including two-operand getelementptr) with
  374. // one-use here. As with the cast case above, it may be possible to relax the
  375. // one-use constraint, but that needs be examined carefully since it may not
  376. // reduce the total number of instructions.
  377. if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
  378. !TI->isSameOperationAs(FI) ||
  379. (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
  380. !TI->hasOneUse() || !FI->hasOneUse())
  381. return nullptr;
  382. // Figure out if the operations have any operands in common.
  383. Value *MatchOp = getCommonOp(TI, FI, TI->isCommutative());
  384. if (!MatchOp)
  385. return nullptr;
  386. // If the select condition is a vector, the operands of the original select's
  387. // operands also must be vectors. This may not be the case for getelementptr
  388. // for example.
  389. if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
  390. !OtherOpF->getType()->isVectorTy()))
  391. return nullptr;
  392. // If we reach here, they do have operations in common.
  393. Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
  394. SI.getName() + ".v", &SI);
  395. Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
  396. Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
  397. if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
  398. BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
  399. NewBO->copyIRFlags(TI);
  400. NewBO->andIRFlags(FI);
  401. return NewBO;
  402. }
  403. if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
  404. auto *FGEP = cast<GetElementPtrInst>(FI);
  405. Type *ElementType = TGEP->getResultElementType();
  406. return TGEP->isInBounds() && FGEP->isInBounds()
  407. ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
  408. : GetElementPtrInst::Create(ElementType, Op0, {Op1});
  409. }
  410. llvm_unreachable("Expected BinaryOperator or GEP");
  411. return nullptr;
  412. }
  413. static bool isSelect01(const APInt &C1I, const APInt &C2I) {
  414. if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
  415. return false;
  416. return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
  417. }
  418. /// Try to fold the select into one of the operands to allow further
  419. /// optimization.
  420. Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
  421. Value *FalseVal) {
  422. // See the comment above GetSelectFoldableOperands for a description of the
  423. // transformation we are doing here.
  424. auto TryFoldSelectIntoOp = [&](SelectInst &SI, Value *TrueVal,
  425. Value *FalseVal,
  426. bool Swapped) -> Instruction * {
  427. auto *TVI = dyn_cast<BinaryOperator>(TrueVal);
  428. if (!TVI || !TVI->hasOneUse() || isa<Constant>(FalseVal))
  429. return nullptr;
  430. unsigned SFO = getSelectFoldableOperands(TVI);
  431. unsigned OpToFold = 0;
  432. if ((SFO & 1) && FalseVal == TVI->getOperand(0))
  433. OpToFold = 1;
  434. else if ((SFO & 2) && FalseVal == TVI->getOperand(1))
  435. OpToFold = 2;
  436. if (!OpToFold)
  437. return nullptr;
  438. // TODO: We probably ought to revisit cases where the select and FP
  439. // instructions have different flags and add tests to ensure the
  440. // behaviour is correct.
  441. FastMathFlags FMF;
  442. if (isa<FPMathOperator>(&SI))
  443. FMF = SI.getFastMathFlags();
  444. Constant *C = ConstantExpr::getBinOpIdentity(
  445. TVI->getOpcode(), TVI->getType(), true, FMF.noSignedZeros());
  446. Value *OOp = TVI->getOperand(2 - OpToFold);
  447. // Avoid creating select between 2 constants unless it's selecting
  448. // between 0, 1 and -1.
  449. const APInt *OOpC;
  450. bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
  451. if (!isa<Constant>(OOp) ||
  452. (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
  453. Value *NewSel = Builder.CreateSelect(SI.getCondition(), Swapped ? C : OOp,
  454. Swapped ? OOp : C);
  455. if (isa<FPMathOperator>(&SI))
  456. cast<Instruction>(NewSel)->setFastMathFlags(FMF);
  457. NewSel->takeName(TVI);
  458. BinaryOperator *BO =
  459. BinaryOperator::Create(TVI->getOpcode(), FalseVal, NewSel);
  460. BO->copyIRFlags(TVI);
  461. return BO;
  462. }
  463. return nullptr;
  464. };
  465. if (Instruction *R = TryFoldSelectIntoOp(SI, TrueVal, FalseVal, false))
  466. return R;
  467. if (Instruction *R = TryFoldSelectIntoOp(SI, FalseVal, TrueVal, true))
  468. return R;
  469. return nullptr;
  470. }
  471. /// We want to turn:
  472. /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
  473. /// into:
  474. /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
  475. /// Note:
  476. /// Z may be 0 if lshr is missing.
  477. /// Worst-case scenario is that we will replace 5 instructions with 5 different
  478. /// instructions, but we got rid of select.
  479. static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
  480. Value *TVal, Value *FVal,
  481. InstCombiner::BuilderTy &Builder) {
  482. if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
  483. Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
  484. match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
  485. return nullptr;
  486. // The TrueVal has general form of: and %B, 1
  487. Value *B;
  488. if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
  489. return nullptr;
  490. // Where %B may be optionally shifted: lshr %X, %Z.
  491. Value *X, *Z;
  492. const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
  493. // The shift must be valid.
  494. // TODO: This restricts the fold to constant shift amounts. Is there a way to
  495. // handle variable shifts safely? PR47012
  496. if (HasShift &&
  497. !match(Z, m_SpecificInt_ICMP(CmpInst::ICMP_ULT,
  498. APInt(SelType->getScalarSizeInBits(),
  499. SelType->getScalarSizeInBits()))))
  500. return nullptr;
  501. if (!HasShift)
  502. X = B;
  503. Value *Y;
  504. if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
  505. return nullptr;
  506. // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
  507. // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
  508. Constant *One = ConstantInt::get(SelType, 1);
  509. Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
  510. Value *FullMask = Builder.CreateOr(Y, MaskB);
  511. Value *MaskedX = Builder.CreateAnd(X, FullMask);
  512. Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
  513. return new ZExtInst(ICmpNeZero, SelType);
  514. }
  515. /// We want to turn:
  516. /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
  517. /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
  518. /// into:
  519. /// ashr (X, Y)
  520. static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
  521. Value *FalseVal,
  522. InstCombiner::BuilderTy &Builder) {
  523. ICmpInst::Predicate Pred = IC->getPredicate();
  524. Value *CmpLHS = IC->getOperand(0);
  525. Value *CmpRHS = IC->getOperand(1);
  526. if (!CmpRHS->getType()->isIntOrIntVectorTy())
  527. return nullptr;
  528. Value *X, *Y;
  529. unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
  530. if ((Pred != ICmpInst::ICMP_SGT ||
  531. !match(CmpRHS,
  532. m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
  533. (Pred != ICmpInst::ICMP_SLT ||
  534. !match(CmpRHS,
  535. m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
  536. return nullptr;
  537. // Canonicalize so that ashr is in FalseVal.
  538. if (Pred == ICmpInst::ICMP_SLT)
  539. std::swap(TrueVal, FalseVal);
  540. if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
  541. match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
  542. match(CmpLHS, m_Specific(X))) {
  543. const auto *Ashr = cast<Instruction>(FalseVal);
  544. // if lshr is not exact and ashr is, this new ashr must not be exact.
  545. bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
  546. return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
  547. }
  548. return nullptr;
  549. }
  550. /// We want to turn:
  551. /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
  552. /// into:
  553. /// (or (shl (and X, C1), C3), Y)
  554. /// iff:
  555. /// C1 and C2 are both powers of 2
  556. /// where:
  557. /// C3 = Log(C2) - Log(C1)
  558. ///
  559. /// This transform handles cases where:
  560. /// 1. The icmp predicate is inverted
  561. /// 2. The select operands are reversed
  562. /// 3. The magnitude of C2 and C1 are flipped
  563. static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
  564. Value *FalseVal,
  565. InstCombiner::BuilderTy &Builder) {
  566. // Only handle integer compares. Also, if this is a vector select, we need a
  567. // vector compare.
  568. if (!TrueVal->getType()->isIntOrIntVectorTy() ||
  569. TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
  570. return nullptr;
  571. Value *CmpLHS = IC->getOperand(0);
  572. Value *CmpRHS = IC->getOperand(1);
  573. Value *V;
  574. unsigned C1Log;
  575. bool IsEqualZero;
  576. bool NeedAnd = false;
  577. if (IC->isEquality()) {
  578. if (!match(CmpRHS, m_Zero()))
  579. return nullptr;
  580. const APInt *C1;
  581. if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
  582. return nullptr;
  583. V = CmpLHS;
  584. C1Log = C1->logBase2();
  585. IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
  586. } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
  587. IC->getPredicate() == ICmpInst::ICMP_SGT) {
  588. // We also need to recognize (icmp slt (trunc (X)), 0) and
  589. // (icmp sgt (trunc (X)), -1).
  590. IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
  591. if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
  592. (!IsEqualZero && !match(CmpRHS, m_Zero())))
  593. return nullptr;
  594. if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
  595. return nullptr;
  596. C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
  597. NeedAnd = true;
  598. } else {
  599. return nullptr;
  600. }
  601. const APInt *C2;
  602. bool OrOnTrueVal = false;
  603. bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
  604. if (!OrOnFalseVal)
  605. OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
  606. if (!OrOnFalseVal && !OrOnTrueVal)
  607. return nullptr;
  608. Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
  609. unsigned C2Log = C2->logBase2();
  610. bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
  611. bool NeedShift = C1Log != C2Log;
  612. bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
  613. V->getType()->getScalarSizeInBits();
  614. // Make sure we don't create more instructions than we save.
  615. Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
  616. if ((NeedShift + NeedXor + NeedZExtTrunc) >
  617. (IC->hasOneUse() + Or->hasOneUse()))
  618. return nullptr;
  619. if (NeedAnd) {
  620. // Insert the AND instruction on the input to the truncate.
  621. APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
  622. V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
  623. }
  624. if (C2Log > C1Log) {
  625. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  626. V = Builder.CreateShl(V, C2Log - C1Log);
  627. } else if (C1Log > C2Log) {
  628. V = Builder.CreateLShr(V, C1Log - C2Log);
  629. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  630. } else
  631. V = Builder.CreateZExtOrTrunc(V, Y->getType());
  632. if (NeedXor)
  633. V = Builder.CreateXor(V, *C2);
  634. return Builder.CreateOr(V, Y);
  635. }
  636. /// Canonicalize a set or clear of a masked set of constant bits to
  637. /// select-of-constants form.
  638. static Instruction *foldSetClearBits(SelectInst &Sel,
  639. InstCombiner::BuilderTy &Builder) {
  640. Value *Cond = Sel.getCondition();
  641. Value *T = Sel.getTrueValue();
  642. Value *F = Sel.getFalseValue();
  643. Type *Ty = Sel.getType();
  644. Value *X;
  645. const APInt *NotC, *C;
  646. // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
  647. if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
  648. match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
  649. Constant *Zero = ConstantInt::getNullValue(Ty);
  650. Constant *OrC = ConstantInt::get(Ty, *C);
  651. Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
  652. return BinaryOperator::CreateOr(T, NewSel);
  653. }
  654. // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
  655. if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
  656. match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
  657. Constant *Zero = ConstantInt::getNullValue(Ty);
  658. Constant *OrC = ConstantInt::get(Ty, *C);
  659. Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
  660. return BinaryOperator::CreateOr(F, NewSel);
  661. }
  662. return nullptr;
  663. }
  664. // select (x == 0), 0, x * y --> freeze(y) * x
  665. // select (y == 0), 0, x * y --> freeze(x) * y
  666. // select (x == 0), undef, x * y --> freeze(y) * x
  667. // select (x == undef), 0, x * y --> freeze(y) * x
  668. // Usage of mul instead of 0 will make the result more poisonous,
  669. // so the operand that was not checked in the condition should be frozen.
  670. // The latter folding is applied only when a constant compared with x is
  671. // is a vector consisting of 0 and undefs. If a constant compared with x
  672. // is a scalar undefined value or undefined vector then an expression
  673. // should be already folded into a constant.
  674. static Instruction *foldSelectZeroOrMul(SelectInst &SI, InstCombinerImpl &IC) {
  675. auto *CondVal = SI.getCondition();
  676. auto *TrueVal = SI.getTrueValue();
  677. auto *FalseVal = SI.getFalseValue();
  678. Value *X, *Y;
  679. ICmpInst::Predicate Predicate;
  680. // Assuming that constant compared with zero is not undef (but it may be
  681. // a vector with some undef elements). Otherwise (when a constant is undef)
  682. // the select expression should be already simplified.
  683. if (!match(CondVal, m_ICmp(Predicate, m_Value(X), m_Zero())) ||
  684. !ICmpInst::isEquality(Predicate))
  685. return nullptr;
  686. if (Predicate == ICmpInst::ICMP_NE)
  687. std::swap(TrueVal, FalseVal);
  688. // Check that TrueVal is a constant instead of matching it with m_Zero()
  689. // to handle the case when it is a scalar undef value or a vector containing
  690. // non-zero elements that are masked by undef elements in the compare
  691. // constant.
  692. auto *TrueValC = dyn_cast<Constant>(TrueVal);
  693. if (TrueValC == nullptr ||
  694. !match(FalseVal, m_c_Mul(m_Specific(X), m_Value(Y))) ||
  695. !isa<Instruction>(FalseVal))
  696. return nullptr;
  697. auto *ZeroC = cast<Constant>(cast<Instruction>(CondVal)->getOperand(1));
  698. auto *MergedC = Constant::mergeUndefsWith(TrueValC, ZeroC);
  699. // If X is compared with 0 then TrueVal could be either zero or undef.
  700. // m_Zero match vectors containing some undef elements, but for scalars
  701. // m_Undef should be used explicitly.
  702. if (!match(MergedC, m_Zero()) && !match(MergedC, m_Undef()))
  703. return nullptr;
  704. auto *FalseValI = cast<Instruction>(FalseVal);
  705. auto *FrY = IC.InsertNewInstBefore(new FreezeInst(Y, Y->getName() + ".fr"),
  706. *FalseValI);
  707. IC.replaceOperand(*FalseValI, FalseValI->getOperand(0) == Y ? 0 : 1, FrY);
  708. return IC.replaceInstUsesWith(SI, FalseValI);
  709. }
  710. /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
  711. /// There are 8 commuted/swapped variants of this pattern.
  712. /// TODO: Also support a - UMIN(a,b) patterns.
  713. static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
  714. const Value *TrueVal,
  715. const Value *FalseVal,
  716. InstCombiner::BuilderTy &Builder) {
  717. ICmpInst::Predicate Pred = ICI->getPredicate();
  718. Value *A = ICI->getOperand(0);
  719. Value *B = ICI->getOperand(1);
  720. // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
  721. // (a == 0) ? 0 : a - 1 -> (a != 0) ? a - 1 : 0
  722. if (match(TrueVal, m_Zero())) {
  723. Pred = ICmpInst::getInversePredicate(Pred);
  724. std::swap(TrueVal, FalseVal);
  725. }
  726. if (!match(FalseVal, m_Zero()))
  727. return nullptr;
  728. // ugt 0 is canonicalized to ne 0 and requires special handling
  729. // (a != 0) ? a + -1 : 0 -> usub.sat(a, 1)
  730. if (Pred == ICmpInst::ICMP_NE) {
  731. if (match(B, m_Zero()) && match(TrueVal, m_Add(m_Specific(A), m_AllOnes())))
  732. return Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A,
  733. ConstantInt::get(A->getType(), 1));
  734. return nullptr;
  735. }
  736. if (!ICmpInst::isUnsigned(Pred))
  737. return nullptr;
  738. if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
  739. // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
  740. std::swap(A, B);
  741. Pred = ICmpInst::getSwappedPredicate(Pred);
  742. }
  743. assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
  744. "Unexpected isUnsigned predicate!");
  745. // Ensure the sub is of the form:
  746. // (a > b) ? a - b : 0 -> usub.sat(a, b)
  747. // (a > b) ? b - a : 0 -> -usub.sat(a, b)
  748. // Checking for both a-b and a+(-b) as a constant.
  749. bool IsNegative = false;
  750. const APInt *C;
  751. if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
  752. (match(A, m_APInt(C)) &&
  753. match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
  754. IsNegative = true;
  755. else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
  756. !(match(B, m_APInt(C)) &&
  757. match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
  758. return nullptr;
  759. // If we are adding a negate and the sub and icmp are used anywhere else, we
  760. // would end up with more instructions.
  761. if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
  762. return nullptr;
  763. // (a > b) ? a - b : 0 -> usub.sat(a, b)
  764. // (a > b) ? b - a : 0 -> -usub.sat(a, b)
  765. Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
  766. if (IsNegative)
  767. Result = Builder.CreateNeg(Result);
  768. return Result;
  769. }
  770. static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
  771. InstCombiner::BuilderTy &Builder) {
  772. if (!Cmp->hasOneUse())
  773. return nullptr;
  774. // Match unsigned saturated add with constant.
  775. Value *Cmp0 = Cmp->getOperand(0);
  776. Value *Cmp1 = Cmp->getOperand(1);
  777. ICmpInst::Predicate Pred = Cmp->getPredicate();
  778. Value *X;
  779. const APInt *C, *CmpC;
  780. if (Pred == ICmpInst::ICMP_ULT &&
  781. match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
  782. match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
  783. // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
  784. return Builder.CreateBinaryIntrinsic(
  785. Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
  786. }
  787. // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
  788. // There are 8 commuted variants.
  789. // Canonicalize -1 (saturated result) to true value of the select.
  790. if (match(FVal, m_AllOnes())) {
  791. std::swap(TVal, FVal);
  792. Pred = CmpInst::getInversePredicate(Pred);
  793. }
  794. if (!match(TVal, m_AllOnes()))
  795. return nullptr;
  796. // Canonicalize predicate to less-than or less-or-equal-than.
  797. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
  798. std::swap(Cmp0, Cmp1);
  799. Pred = CmpInst::getSwappedPredicate(Pred);
  800. }
  801. if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
  802. return nullptr;
  803. // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
  804. // Strictness of the comparison is irrelevant.
  805. Value *Y;
  806. if (match(Cmp0, m_Not(m_Value(X))) &&
  807. match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
  808. // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
  809. // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
  810. return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
  811. }
  812. // The 'not' op may be included in the sum but not the compare.
  813. // Strictness of the comparison is irrelevant.
  814. X = Cmp0;
  815. Y = Cmp1;
  816. if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
  817. // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
  818. // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
  819. BinaryOperator *BO = cast<BinaryOperator>(FVal);
  820. return Builder.CreateBinaryIntrinsic(
  821. Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
  822. }
  823. // The overflow may be detected via the add wrapping round.
  824. // This is only valid for strict comparison!
  825. if (Pred == ICmpInst::ICMP_ULT &&
  826. match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
  827. match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
  828. // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
  829. // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
  830. return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
  831. }
  832. return nullptr;
  833. }
  834. /// Fold the following code sequence:
  835. /// \code
  836. /// int a = ctlz(x & -x);
  837. // x ? 31 - a : a;
  838. /// \code
  839. ///
  840. /// into:
  841. /// cttz(x)
  842. static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
  843. Value *FalseVal,
  844. InstCombiner::BuilderTy &Builder) {
  845. unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
  846. if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
  847. return nullptr;
  848. if (ICI->getPredicate() == ICmpInst::ICMP_NE)
  849. std::swap(TrueVal, FalseVal);
  850. if (!match(FalseVal,
  851. m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
  852. return nullptr;
  853. if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
  854. return nullptr;
  855. Value *X = ICI->getOperand(0);
  856. auto *II = cast<IntrinsicInst>(TrueVal);
  857. if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
  858. return nullptr;
  859. Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
  860. II->getType());
  861. return CallInst::Create(F, {X, II->getArgOperand(1)});
  862. }
  863. /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
  864. /// call to cttz/ctlz with flag 'is_zero_poison' cleared.
  865. ///
  866. /// For example, we can fold the following code sequence:
  867. /// \code
  868. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
  869. /// %1 = icmp ne i32 %x, 0
  870. /// %2 = select i1 %1, i32 %0, i32 32
  871. /// \code
  872. ///
  873. /// into:
  874. /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
  875. static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
  876. InstCombiner::BuilderTy &Builder) {
  877. ICmpInst::Predicate Pred = ICI->getPredicate();
  878. Value *CmpLHS = ICI->getOperand(0);
  879. Value *CmpRHS = ICI->getOperand(1);
  880. // Check if the select condition compares a value for equality.
  881. if (!ICI->isEquality())
  882. return nullptr;
  883. Value *SelectArg = FalseVal;
  884. Value *ValueOnZero = TrueVal;
  885. if (Pred == ICmpInst::ICMP_NE)
  886. std::swap(SelectArg, ValueOnZero);
  887. // Skip zero extend/truncate.
  888. Value *Count = nullptr;
  889. if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
  890. !match(SelectArg, m_Trunc(m_Value(Count))))
  891. Count = SelectArg;
  892. // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
  893. // input to the cttz/ctlz is used as LHS for the compare instruction.
  894. Value *X;
  895. if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Value(X))) &&
  896. !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Value(X))))
  897. return nullptr;
  898. // (X == 0) ? BitWidth : ctz(X)
  899. // (X == -1) ? BitWidth : ctz(~X)
  900. if ((X != CmpLHS || !match(CmpRHS, m_Zero())) &&
  901. (!match(X, m_Not(m_Specific(CmpLHS))) || !match(CmpRHS, m_AllOnes())))
  902. return nullptr;
  903. IntrinsicInst *II = cast<IntrinsicInst>(Count);
  904. // Check if the value propagated on zero is a constant number equal to the
  905. // sizeof in bits of 'Count'.
  906. unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
  907. if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
  908. // Explicitly clear the 'is_zero_poison' flag. It's always valid to go from
  909. // true to false on this flag, so we can replace it for all users.
  910. II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
  911. return SelectArg;
  912. }
  913. // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
  914. // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
  915. // not be used if the input is zero. Relax to 'zero is poison' for that case.
  916. if (II->hasOneUse() && SelectArg->hasOneUse() &&
  917. !match(II->getArgOperand(1), m_One()))
  918. II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
  919. return nullptr;
  920. }
  921. /// Return true if we find and adjust an icmp+select pattern where the compare
  922. /// is with a constant that can be incremented or decremented to match the
  923. /// minimum or maximum idiom.
  924. static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
  925. ICmpInst::Predicate Pred = Cmp.getPredicate();
  926. Value *CmpLHS = Cmp.getOperand(0);
  927. Value *CmpRHS = Cmp.getOperand(1);
  928. Value *TrueVal = Sel.getTrueValue();
  929. Value *FalseVal = Sel.getFalseValue();
  930. // We may move or edit the compare, so make sure the select is the only user.
  931. const APInt *CmpC;
  932. if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
  933. return false;
  934. // These transforms only work for selects of integers or vector selects of
  935. // integer vectors.
  936. Type *SelTy = Sel.getType();
  937. auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
  938. if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
  939. return false;
  940. Constant *AdjustedRHS;
  941. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
  942. AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
  943. else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
  944. AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
  945. else
  946. return false;
  947. // X > C ? X : C+1 --> X < C+1 ? C+1 : X
  948. // X < C ? X : C-1 --> X > C-1 ? C-1 : X
  949. if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
  950. (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
  951. ; // Nothing to do here. Values match without any sign/zero extension.
  952. }
  953. // Types do not match. Instead of calculating this with mixed types, promote
  954. // all to the larger type. This enables scalar evolution to analyze this
  955. // expression.
  956. else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
  957. Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
  958. // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
  959. // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
  960. // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
  961. // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
  962. if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
  963. CmpLHS = TrueVal;
  964. AdjustedRHS = SextRHS;
  965. } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
  966. SextRHS == TrueVal) {
  967. CmpLHS = FalseVal;
  968. AdjustedRHS = SextRHS;
  969. } else if (Cmp.isUnsigned()) {
  970. Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
  971. // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
  972. // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
  973. // zext + signed compare cannot be changed:
  974. // 0xff <s 0x00, but 0x00ff >s 0x0000
  975. if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
  976. CmpLHS = TrueVal;
  977. AdjustedRHS = ZextRHS;
  978. } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
  979. ZextRHS == TrueVal) {
  980. CmpLHS = FalseVal;
  981. AdjustedRHS = ZextRHS;
  982. } else {
  983. return false;
  984. }
  985. } else {
  986. return false;
  987. }
  988. } else {
  989. return false;
  990. }
  991. Pred = ICmpInst::getSwappedPredicate(Pred);
  992. CmpRHS = AdjustedRHS;
  993. std::swap(FalseVal, TrueVal);
  994. Cmp.setPredicate(Pred);
  995. Cmp.setOperand(0, CmpLHS);
  996. Cmp.setOperand(1, CmpRHS);
  997. Sel.setOperand(1, TrueVal);
  998. Sel.setOperand(2, FalseVal);
  999. Sel.swapProfMetadata();
  1000. // Move the compare instruction right before the select instruction. Otherwise
  1001. // the sext/zext value may be defined after the compare instruction uses it.
  1002. Cmp.moveBefore(&Sel);
  1003. return true;
  1004. }
  1005. static Instruction *canonicalizeSPF(SelectInst &Sel, ICmpInst &Cmp,
  1006. InstCombinerImpl &IC) {
  1007. Value *LHS, *RHS;
  1008. // TODO: What to do with pointer min/max patterns?
  1009. if (!Sel.getType()->isIntOrIntVectorTy())
  1010. return nullptr;
  1011. SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
  1012. if (SPF == SelectPatternFlavor::SPF_ABS ||
  1013. SPF == SelectPatternFlavor::SPF_NABS) {
  1014. if (!Cmp.hasOneUse() && !RHS->hasOneUse())
  1015. return nullptr; // TODO: Relax this restriction.
  1016. // Note that NSW flag can only be propagated for normal, non-negated abs!
  1017. bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
  1018. match(RHS, m_NSWNeg(m_Specific(LHS)));
  1019. Constant *IntMinIsPoisonC =
  1020. ConstantInt::get(Type::getInt1Ty(Sel.getContext()), IntMinIsPoison);
  1021. Instruction *Abs =
  1022. IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC);
  1023. if (SPF == SelectPatternFlavor::SPF_NABS)
  1024. return BinaryOperator::CreateNeg(Abs); // Always without NSW flag!
  1025. return IC.replaceInstUsesWith(Sel, Abs);
  1026. }
  1027. if (SelectPatternResult::isMinOrMax(SPF)) {
  1028. Intrinsic::ID IntrinsicID;
  1029. switch (SPF) {
  1030. case SelectPatternFlavor::SPF_UMIN:
  1031. IntrinsicID = Intrinsic::umin;
  1032. break;
  1033. case SelectPatternFlavor::SPF_UMAX:
  1034. IntrinsicID = Intrinsic::umax;
  1035. break;
  1036. case SelectPatternFlavor::SPF_SMIN:
  1037. IntrinsicID = Intrinsic::smin;
  1038. break;
  1039. case SelectPatternFlavor::SPF_SMAX:
  1040. IntrinsicID = Intrinsic::smax;
  1041. break;
  1042. default:
  1043. llvm_unreachable("Unexpected SPF");
  1044. }
  1045. return IC.replaceInstUsesWith(
  1046. Sel, IC.Builder.CreateBinaryIntrinsic(IntrinsicID, LHS, RHS));
  1047. }
  1048. return nullptr;
  1049. }
  1050. static bool replaceInInstruction(Value *V, Value *Old, Value *New,
  1051. InstCombiner &IC, unsigned Depth = 0) {
  1052. // Conservatively limit replacement to two instructions upwards.
  1053. if (Depth == 2)
  1054. return false;
  1055. auto *I = dyn_cast<Instruction>(V);
  1056. if (!I || !I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
  1057. return false;
  1058. bool Changed = false;
  1059. for (Use &U : I->operands()) {
  1060. if (U == Old) {
  1061. IC.replaceUse(U, New);
  1062. Changed = true;
  1063. } else {
  1064. Changed |= replaceInInstruction(U, Old, New, IC, Depth + 1);
  1065. }
  1066. }
  1067. return Changed;
  1068. }
  1069. /// If we have a select with an equality comparison, then we know the value in
  1070. /// one of the arms of the select. See if substituting this value into an arm
  1071. /// and simplifying the result yields the same value as the other arm.
  1072. ///
  1073. /// To make this transform safe, we must drop poison-generating flags
  1074. /// (nsw, etc) if we simplified to a binop because the select may be guarding
  1075. /// that poison from propagating. If the existing binop already had no
  1076. /// poison-generating flags, then this transform can be done by instsimplify.
  1077. ///
  1078. /// Consider:
  1079. /// %cmp = icmp eq i32 %x, 2147483647
  1080. /// %add = add nsw i32 %x, 1
  1081. /// %sel = select i1 %cmp, i32 -2147483648, i32 %add
  1082. ///
  1083. /// We can't replace %sel with %add unless we strip away the flags.
  1084. /// TODO: Wrapping flags could be preserved in some cases with better analysis.
  1085. Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
  1086. ICmpInst &Cmp) {
  1087. if (!Cmp.isEquality())
  1088. return nullptr;
  1089. // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
  1090. Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
  1091. bool Swapped = false;
  1092. if (Cmp.getPredicate() == ICmpInst::ICMP_NE) {
  1093. std::swap(TrueVal, FalseVal);
  1094. Swapped = true;
  1095. }
  1096. // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
  1097. // Make sure Y cannot be undef though, as we might pick different values for
  1098. // undef in the icmp and in f(Y). Additionally, take care to avoid replacing
  1099. // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite
  1100. // replacement cycle.
  1101. Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
  1102. if (TrueVal != CmpLHS &&
  1103. isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT)) {
  1104. if (Value *V = simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ,
  1105. /* AllowRefinement */ true))
  1106. return replaceOperand(Sel, Swapped ? 2 : 1, V);
  1107. // Even if TrueVal does not simplify, we can directly replace a use of
  1108. // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
  1109. // else and is safe to speculatively execute (we may end up executing it
  1110. // with different operands, which should not cause side-effects or trigger
  1111. // undefined behavior). Only do this if CmpRHS is a constant, as
  1112. // profitability is not clear for other cases.
  1113. // FIXME: Support vectors.
  1114. if (match(CmpRHS, m_ImmConstant()) && !match(CmpLHS, m_ImmConstant()) &&
  1115. !Cmp.getType()->isVectorTy())
  1116. if (replaceInInstruction(TrueVal, CmpLHS, CmpRHS, *this))
  1117. return &Sel;
  1118. }
  1119. if (TrueVal != CmpRHS &&
  1120. isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT))
  1121. if (Value *V = simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ,
  1122. /* AllowRefinement */ true))
  1123. return replaceOperand(Sel, Swapped ? 2 : 1, V);
  1124. auto *FalseInst = dyn_cast<Instruction>(FalseVal);
  1125. if (!FalseInst)
  1126. return nullptr;
  1127. // InstSimplify already performed this fold if it was possible subject to
  1128. // current poison-generating flags. Try the transform again with
  1129. // poison-generating flags temporarily dropped.
  1130. bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false;
  1131. if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
  1132. WasNUW = OBO->hasNoUnsignedWrap();
  1133. WasNSW = OBO->hasNoSignedWrap();
  1134. FalseInst->setHasNoUnsignedWrap(false);
  1135. FalseInst->setHasNoSignedWrap(false);
  1136. }
  1137. if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
  1138. WasExact = PEO->isExact();
  1139. FalseInst->setIsExact(false);
  1140. }
  1141. if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) {
  1142. WasInBounds = GEP->isInBounds();
  1143. GEP->setIsInBounds(false);
  1144. }
  1145. // Try each equivalence substitution possibility.
  1146. // We have an 'EQ' comparison, so the select's false value will propagate.
  1147. // Example:
  1148. // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
  1149. if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
  1150. /* AllowRefinement */ false) == TrueVal ||
  1151. simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
  1152. /* AllowRefinement */ false) == TrueVal) {
  1153. return replaceInstUsesWith(Sel, FalseVal);
  1154. }
  1155. // Restore poison-generating flags if the transform did not apply.
  1156. if (WasNUW)
  1157. FalseInst->setHasNoUnsignedWrap();
  1158. if (WasNSW)
  1159. FalseInst->setHasNoSignedWrap();
  1160. if (WasExact)
  1161. FalseInst->setIsExact();
  1162. if (WasInBounds)
  1163. cast<GetElementPtrInst>(FalseInst)->setIsInBounds();
  1164. return nullptr;
  1165. }
  1166. // See if this is a pattern like:
  1167. // %old_cmp1 = icmp slt i32 %x, C2
  1168. // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
  1169. // %old_x_offseted = add i32 %x, C1
  1170. // %old_cmp0 = icmp ult i32 %old_x_offseted, C0
  1171. // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
  1172. // This can be rewritten as more canonical pattern:
  1173. // %new_cmp1 = icmp slt i32 %x, -C1
  1174. // %new_cmp2 = icmp sge i32 %x, C0-C1
  1175. // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
  1176. // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
  1177. // Iff -C1 s<= C2 s<= C0-C1
  1178. // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
  1179. // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
  1180. static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
  1181. InstCombiner::BuilderTy &Builder) {
  1182. Value *X = Sel0.getTrueValue();
  1183. Value *Sel1 = Sel0.getFalseValue();
  1184. // First match the condition of the outermost select.
  1185. // Said condition must be one-use.
  1186. if (!Cmp0.hasOneUse())
  1187. return nullptr;
  1188. ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
  1189. Value *Cmp00 = Cmp0.getOperand(0);
  1190. Constant *C0;
  1191. if (!match(Cmp0.getOperand(1),
  1192. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
  1193. return nullptr;
  1194. if (!isa<SelectInst>(Sel1)) {
  1195. Pred0 = ICmpInst::getInversePredicate(Pred0);
  1196. std::swap(X, Sel1);
  1197. }
  1198. // Canonicalize Cmp0 into ult or uge.
  1199. // FIXME: we shouldn't care about lanes that are 'undef' in the end?
  1200. switch (Pred0) {
  1201. case ICmpInst::Predicate::ICMP_ULT:
  1202. case ICmpInst::Predicate::ICMP_UGE:
  1203. // Although icmp ult %x, 0 is an unusual thing to try and should generally
  1204. // have been simplified, it does not verify with undef inputs so ensure we
  1205. // are not in a strange state.
  1206. if (!match(C0, m_SpecificInt_ICMP(
  1207. ICmpInst::Predicate::ICMP_NE,
  1208. APInt::getZero(C0->getType()->getScalarSizeInBits()))))
  1209. return nullptr;
  1210. break; // Great!
  1211. case ICmpInst::Predicate::ICMP_ULE:
  1212. case ICmpInst::Predicate::ICMP_UGT:
  1213. // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
  1214. // C0, which again means it must not have any all-ones elements.
  1215. if (!match(C0,
  1216. m_SpecificInt_ICMP(
  1217. ICmpInst::Predicate::ICMP_NE,
  1218. APInt::getAllOnes(C0->getType()->getScalarSizeInBits()))))
  1219. return nullptr; // Can't do, have all-ones element[s].
  1220. Pred0 = ICmpInst::getFlippedStrictnessPredicate(Pred0);
  1221. C0 = InstCombiner::AddOne(C0);
  1222. break;
  1223. default:
  1224. return nullptr; // Unknown predicate.
  1225. }
  1226. // Now that we've canonicalized the ICmp, we know the X we expect;
  1227. // the select in other hand should be one-use.
  1228. if (!Sel1->hasOneUse())
  1229. return nullptr;
  1230. // If the types do not match, look through any truncs to the underlying
  1231. // instruction.
  1232. if (Cmp00->getType() != X->getType() && X->hasOneUse())
  1233. match(X, m_TruncOrSelf(m_Value(X)));
  1234. // We now can finish matching the condition of the outermost select:
  1235. // it should either be the X itself, or an addition of some constant to X.
  1236. Constant *C1;
  1237. if (Cmp00 == X)
  1238. C1 = ConstantInt::getNullValue(X->getType());
  1239. else if (!match(Cmp00,
  1240. m_Add(m_Specific(X),
  1241. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
  1242. return nullptr;
  1243. Value *Cmp1;
  1244. ICmpInst::Predicate Pred1;
  1245. Constant *C2;
  1246. Value *ReplacementLow, *ReplacementHigh;
  1247. if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
  1248. m_Value(ReplacementHigh))) ||
  1249. !match(Cmp1,
  1250. m_ICmp(Pred1, m_Specific(X),
  1251. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
  1252. return nullptr;
  1253. if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
  1254. return nullptr; // Not enough one-use instructions for the fold.
  1255. // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
  1256. // two comparisons we'll need to build.
  1257. // Canonicalize Cmp1 into the form we expect.
  1258. // FIXME: we shouldn't care about lanes that are 'undef' in the end?
  1259. switch (Pred1) {
  1260. case ICmpInst::Predicate::ICMP_SLT:
  1261. break;
  1262. case ICmpInst::Predicate::ICMP_SLE:
  1263. // We'd have to increment C2 by one, and for that it must not have signed
  1264. // max element, but then it would have been canonicalized to 'slt' before
  1265. // we get here. So we can't do anything useful with 'sle'.
  1266. return nullptr;
  1267. case ICmpInst::Predicate::ICMP_SGT:
  1268. // We want to canonicalize it to 'slt', so we'll need to increment C2,
  1269. // which again means it must not have any signed max elements.
  1270. if (!match(C2,
  1271. m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
  1272. APInt::getSignedMaxValue(
  1273. C2->getType()->getScalarSizeInBits()))))
  1274. return nullptr; // Can't do, have signed max element[s].
  1275. C2 = InstCombiner::AddOne(C2);
  1276. [[fallthrough]];
  1277. case ICmpInst::Predicate::ICMP_SGE:
  1278. // Also non-canonical, but here we don't need to change C2,
  1279. // so we don't have any restrictions on C2, so we can just handle it.
  1280. Pred1 = ICmpInst::Predicate::ICMP_SLT;
  1281. std::swap(ReplacementLow, ReplacementHigh);
  1282. break;
  1283. default:
  1284. return nullptr; // Unknown predicate.
  1285. }
  1286. assert(Pred1 == ICmpInst::Predicate::ICMP_SLT &&
  1287. "Unexpected predicate type.");
  1288. // The thresholds of this clamp-like pattern.
  1289. auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
  1290. auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
  1291. assert((Pred0 == ICmpInst::Predicate::ICMP_ULT ||
  1292. Pred0 == ICmpInst::Predicate::ICMP_UGE) &&
  1293. "Unexpected predicate type.");
  1294. if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
  1295. std::swap(ThresholdLowIncl, ThresholdHighExcl);
  1296. // The fold has a precondition 1: C2 s>= ThresholdLow
  1297. auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
  1298. ThresholdLowIncl);
  1299. if (!match(Precond1, m_One()))
  1300. return nullptr;
  1301. // The fold has a precondition 2: C2 s<= ThresholdHigh
  1302. auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
  1303. ThresholdHighExcl);
  1304. if (!match(Precond2, m_One()))
  1305. return nullptr;
  1306. // If we are matching from a truncated input, we need to sext the
  1307. // ReplacementLow and ReplacementHigh values. Only do the transform if they
  1308. // are free to extend due to being constants.
  1309. if (X->getType() != Sel0.getType()) {
  1310. Constant *LowC, *HighC;
  1311. if (!match(ReplacementLow, m_ImmConstant(LowC)) ||
  1312. !match(ReplacementHigh, m_ImmConstant(HighC)))
  1313. return nullptr;
  1314. ReplacementLow = ConstantExpr::getSExt(LowC, X->getType());
  1315. ReplacementHigh = ConstantExpr::getSExt(HighC, X->getType());
  1316. }
  1317. // All good, finally emit the new pattern.
  1318. Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
  1319. Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
  1320. Value *MaybeReplacedLow =
  1321. Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
  1322. // Create the final select. If we looked through a truncate above, we will
  1323. // need to retruncate the result.
  1324. Value *MaybeReplacedHigh = Builder.CreateSelect(
  1325. ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
  1326. return Builder.CreateTrunc(MaybeReplacedHigh, Sel0.getType());
  1327. }
  1328. // If we have
  1329. // %cmp = icmp [canonical predicate] i32 %x, C0
  1330. // %r = select i1 %cmp, i32 %y, i32 C1
  1331. // Where C0 != C1 and %x may be different from %y, see if the constant that we
  1332. // will have if we flip the strictness of the predicate (i.e. without changing
  1333. // the result) is identical to the C1 in select. If it matches we can change
  1334. // original comparison to one with swapped predicate, reuse the constant,
  1335. // and swap the hands of select.
  1336. static Instruction *
  1337. tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
  1338. InstCombinerImpl &IC) {
  1339. ICmpInst::Predicate Pred;
  1340. Value *X;
  1341. Constant *C0;
  1342. if (!match(&Cmp, m_OneUse(m_ICmp(
  1343. Pred, m_Value(X),
  1344. m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
  1345. return nullptr;
  1346. // If comparison predicate is non-relational, we won't be able to do anything.
  1347. if (ICmpInst::isEquality(Pred))
  1348. return nullptr;
  1349. // If comparison predicate is non-canonical, then we certainly won't be able
  1350. // to make it canonical; canonicalizeCmpWithConstant() already tried.
  1351. if (!InstCombiner::isCanonicalPredicate(Pred))
  1352. return nullptr;
  1353. // If the [input] type of comparison and select type are different, lets abort
  1354. // for now. We could try to compare constants with trunc/[zs]ext though.
  1355. if (C0->getType() != Sel.getType())
  1356. return nullptr;
  1357. // ULT with 'add' of a constant is canonical. See foldICmpAddConstant().
  1358. // FIXME: Are there more magic icmp predicate+constant pairs we must avoid?
  1359. // Or should we just abandon this transform entirely?
  1360. if (Pred == CmpInst::ICMP_ULT && match(X, m_Add(m_Value(), m_Constant())))
  1361. return nullptr;
  1362. Value *SelVal0, *SelVal1; // We do not care which one is from where.
  1363. match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
  1364. // At least one of these values we are selecting between must be a constant
  1365. // else we'll never succeed.
  1366. if (!match(SelVal0, m_AnyIntegralConstant()) &&
  1367. !match(SelVal1, m_AnyIntegralConstant()))
  1368. return nullptr;
  1369. // Does this constant C match any of the `select` values?
  1370. auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
  1371. return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
  1372. };
  1373. // If C0 *already* matches true/false value of select, we are done.
  1374. if (MatchesSelectValue(C0))
  1375. return nullptr;
  1376. // Check the constant we'd have with flipped-strictness predicate.
  1377. auto FlippedStrictness =
  1378. InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0);
  1379. if (!FlippedStrictness)
  1380. return nullptr;
  1381. // If said constant doesn't match either, then there is no hope,
  1382. if (!MatchesSelectValue(FlippedStrictness->second))
  1383. return nullptr;
  1384. // It matched! Lets insert the new comparison just before select.
  1385. InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
  1386. IC.Builder.SetInsertPoint(&Sel);
  1387. Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
  1388. Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
  1389. Cmp.getName() + ".inv");
  1390. IC.replaceOperand(Sel, 0, NewCmp);
  1391. Sel.swapValues();
  1392. Sel.swapProfMetadata();
  1393. return &Sel;
  1394. }
  1395. static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal,
  1396. Value *FVal,
  1397. InstCombiner::BuilderTy &Builder) {
  1398. if (!Cmp->hasOneUse())
  1399. return nullptr;
  1400. const APInt *CmpC;
  1401. if (!match(Cmp->getOperand(1), m_APIntAllowUndef(CmpC)))
  1402. return nullptr;
  1403. // (X u< 2) ? -X : -1 --> sext (X != 0)
  1404. Value *X = Cmp->getOperand(0);
  1405. if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 &&
  1406. match(TVal, m_Neg(m_Specific(X))) && match(FVal, m_AllOnes()))
  1407. return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
  1408. // (X u> 1) ? -1 : -X --> sext (X != 0)
  1409. if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 &&
  1410. match(FVal, m_Neg(m_Specific(X))) && match(TVal, m_AllOnes()))
  1411. return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
  1412. return nullptr;
  1413. }
  1414. static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI) {
  1415. const APInt *CmpC;
  1416. Value *V;
  1417. CmpInst::Predicate Pred;
  1418. if (!match(ICI, m_ICmp(Pred, m_Value(V), m_APInt(CmpC))))
  1419. return nullptr;
  1420. BinaryOperator *BO;
  1421. const APInt *C;
  1422. CmpInst::Predicate CPred;
  1423. if (match(&SI, m_Select(m_Specific(ICI), m_APInt(C), m_BinOp(BO))))
  1424. CPred = ICI->getPredicate();
  1425. else if (match(&SI, m_Select(m_Specific(ICI), m_BinOp(BO), m_APInt(C))))
  1426. CPred = ICI->getInversePredicate();
  1427. else
  1428. return nullptr;
  1429. const APInt *BinOpC;
  1430. if (!match(BO, m_BinOp(m_Specific(V), m_APInt(BinOpC))))
  1431. return nullptr;
  1432. ConstantRange R = ConstantRange::makeExactICmpRegion(CPred, *CmpC)
  1433. .binaryOp(BO->getOpcode(), *BinOpC);
  1434. if (R == *C) {
  1435. BO->dropPoisonGeneratingFlags();
  1436. return BO;
  1437. }
  1438. return nullptr;
  1439. }
  1440. /// Visit a SelectInst that has an ICmpInst as its first operand.
  1441. Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
  1442. ICmpInst *ICI) {
  1443. if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI))
  1444. return NewSel;
  1445. if (Instruction *NewSPF = canonicalizeSPF(SI, *ICI, *this))
  1446. return NewSPF;
  1447. if (Value *V = foldSelectInstWithICmpConst(SI, ICI))
  1448. return replaceInstUsesWith(SI, V);
  1449. if (Value *V = canonicalizeClampLike(SI, *ICI, Builder))
  1450. return replaceInstUsesWith(SI, V);
  1451. if (Instruction *NewSel =
  1452. tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
  1453. return NewSel;
  1454. bool Changed = adjustMinMax(SI, *ICI);
  1455. if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
  1456. return replaceInstUsesWith(SI, V);
  1457. // NOTE: if we wanted to, this is where to detect integer MIN/MAX
  1458. Value *TrueVal = SI.getTrueValue();
  1459. Value *FalseVal = SI.getFalseValue();
  1460. ICmpInst::Predicate Pred = ICI->getPredicate();
  1461. Value *CmpLHS = ICI->getOperand(0);
  1462. Value *CmpRHS = ICI->getOperand(1);
  1463. if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
  1464. if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
  1465. // Transform (X == C) ? X : Y -> (X == C) ? C : Y
  1466. SI.setOperand(1, CmpRHS);
  1467. Changed = true;
  1468. } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
  1469. // Transform (X != C) ? Y : X -> (X != C) ? Y : C
  1470. SI.setOperand(2, CmpRHS);
  1471. Changed = true;
  1472. }
  1473. }
  1474. // Canonicalize a signbit condition to use zero constant by swapping:
  1475. // (CmpLHS > -1) ? TV : FV --> (CmpLHS < 0) ? FV : TV
  1476. // To avoid conflicts (infinite loops) with other canonicalizations, this is
  1477. // not applied with any constant select arm.
  1478. if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes()) &&
  1479. !match(TrueVal, m_Constant()) && !match(FalseVal, m_Constant()) &&
  1480. ICI->hasOneUse()) {
  1481. InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
  1482. Builder.SetInsertPoint(&SI);
  1483. Value *IsNeg = Builder.CreateIsNeg(CmpLHS, ICI->getName());
  1484. replaceOperand(SI, 0, IsNeg);
  1485. SI.swapValues();
  1486. SI.swapProfMetadata();
  1487. return &SI;
  1488. }
  1489. // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
  1490. // decomposeBitTestICmp() might help.
  1491. {
  1492. unsigned BitWidth =
  1493. DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
  1494. APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
  1495. Value *X;
  1496. const APInt *Y, *C;
  1497. bool TrueWhenUnset;
  1498. bool IsBitTest = false;
  1499. if (ICmpInst::isEquality(Pred) &&
  1500. match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
  1501. match(CmpRHS, m_Zero())) {
  1502. IsBitTest = true;
  1503. TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
  1504. } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
  1505. X = CmpLHS;
  1506. Y = &MinSignedValue;
  1507. IsBitTest = true;
  1508. TrueWhenUnset = false;
  1509. } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
  1510. X = CmpLHS;
  1511. Y = &MinSignedValue;
  1512. IsBitTest = true;
  1513. TrueWhenUnset = true;
  1514. }
  1515. if (IsBitTest) {
  1516. Value *V = nullptr;
  1517. // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
  1518. if (TrueWhenUnset && TrueVal == X &&
  1519. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1520. V = Builder.CreateAnd(X, ~(*Y));
  1521. // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
  1522. else if (!TrueWhenUnset && FalseVal == X &&
  1523. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1524. V = Builder.CreateAnd(X, ~(*Y));
  1525. // (X & Y) == 0 ? X ^ Y : X --> X | Y
  1526. else if (TrueWhenUnset && FalseVal == X &&
  1527. match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1528. V = Builder.CreateOr(X, *Y);
  1529. // (X & Y) != 0 ? X : X ^ Y --> X | Y
  1530. else if (!TrueWhenUnset && TrueVal == X &&
  1531. match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
  1532. V = Builder.CreateOr(X, *Y);
  1533. if (V)
  1534. return replaceInstUsesWith(SI, V);
  1535. }
  1536. }
  1537. if (Instruction *V =
  1538. foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
  1539. return V;
  1540. if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
  1541. return V;
  1542. if (Instruction *V = foldSelectZeroOrOnes(ICI, TrueVal, FalseVal, Builder))
  1543. return V;
  1544. if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
  1545. return replaceInstUsesWith(SI, V);
  1546. if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
  1547. return replaceInstUsesWith(SI, V);
  1548. if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
  1549. return replaceInstUsesWith(SI, V);
  1550. if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
  1551. return replaceInstUsesWith(SI, V);
  1552. if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
  1553. return replaceInstUsesWith(SI, V);
  1554. return Changed ? &SI : nullptr;
  1555. }
  1556. /// SI is a select whose condition is a PHI node (but the two may be in
  1557. /// different blocks). See if the true/false values (V) are live in all of the
  1558. /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
  1559. ///
  1560. /// X = phi [ C1, BB1], [C2, BB2]
  1561. /// Y = add
  1562. /// Z = select X, Y, 0
  1563. ///
  1564. /// because Y is not live in BB1/BB2.
  1565. static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
  1566. const SelectInst &SI) {
  1567. // If the value is a non-instruction value like a constant or argument, it
  1568. // can always be mapped.
  1569. const Instruction *I = dyn_cast<Instruction>(V);
  1570. if (!I) return true;
  1571. // If V is a PHI node defined in the same block as the condition PHI, we can
  1572. // map the arguments.
  1573. const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
  1574. if (const PHINode *VP = dyn_cast<PHINode>(I))
  1575. if (VP->getParent() == CondPHI->getParent())
  1576. return true;
  1577. // Otherwise, if the PHI and select are defined in the same block and if V is
  1578. // defined in a different block, then we can transform it.
  1579. if (SI.getParent() == CondPHI->getParent() &&
  1580. I->getParent() != CondPHI->getParent())
  1581. return true;
  1582. // Otherwise we have a 'hard' case and we can't tell without doing more
  1583. // detailed dominator based analysis, punt.
  1584. return false;
  1585. }
  1586. /// We have an SPF (e.g. a min or max) of an SPF of the form:
  1587. /// SPF2(SPF1(A, B), C)
  1588. Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
  1589. SelectPatternFlavor SPF1, Value *A,
  1590. Value *B, Instruction &Outer,
  1591. SelectPatternFlavor SPF2,
  1592. Value *C) {
  1593. if (Outer.getType() != Inner->getType())
  1594. return nullptr;
  1595. if (C == A || C == B) {
  1596. // MAX(MAX(A, B), B) -> MAX(A, B)
  1597. // MIN(MIN(a, b), a) -> MIN(a, b)
  1598. // TODO: This could be done in instsimplify.
  1599. if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
  1600. return replaceInstUsesWith(Outer, Inner);
  1601. }
  1602. return nullptr;
  1603. }
  1604. /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
  1605. /// This is even legal for FP.
  1606. static Instruction *foldAddSubSelect(SelectInst &SI,
  1607. InstCombiner::BuilderTy &Builder) {
  1608. Value *CondVal = SI.getCondition();
  1609. Value *TrueVal = SI.getTrueValue();
  1610. Value *FalseVal = SI.getFalseValue();
  1611. auto *TI = dyn_cast<Instruction>(TrueVal);
  1612. auto *FI = dyn_cast<Instruction>(FalseVal);
  1613. if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
  1614. return nullptr;
  1615. Instruction *AddOp = nullptr, *SubOp = nullptr;
  1616. if ((TI->getOpcode() == Instruction::Sub &&
  1617. FI->getOpcode() == Instruction::Add) ||
  1618. (TI->getOpcode() == Instruction::FSub &&
  1619. FI->getOpcode() == Instruction::FAdd)) {
  1620. AddOp = FI;
  1621. SubOp = TI;
  1622. } else if ((FI->getOpcode() == Instruction::Sub &&
  1623. TI->getOpcode() == Instruction::Add) ||
  1624. (FI->getOpcode() == Instruction::FSub &&
  1625. TI->getOpcode() == Instruction::FAdd)) {
  1626. AddOp = TI;
  1627. SubOp = FI;
  1628. }
  1629. if (AddOp) {
  1630. Value *OtherAddOp = nullptr;
  1631. if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
  1632. OtherAddOp = AddOp->getOperand(1);
  1633. } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
  1634. OtherAddOp = AddOp->getOperand(0);
  1635. }
  1636. if (OtherAddOp) {
  1637. // So at this point we know we have (Y -> OtherAddOp):
  1638. // select C, (add X, Y), (sub X, Z)
  1639. Value *NegVal; // Compute -Z
  1640. if (SI.getType()->isFPOrFPVectorTy()) {
  1641. NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
  1642. if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
  1643. FastMathFlags Flags = AddOp->getFastMathFlags();
  1644. Flags &= SubOp->getFastMathFlags();
  1645. NegInst->setFastMathFlags(Flags);
  1646. }
  1647. } else {
  1648. NegVal = Builder.CreateNeg(SubOp->getOperand(1));
  1649. }
  1650. Value *NewTrueOp = OtherAddOp;
  1651. Value *NewFalseOp = NegVal;
  1652. if (AddOp != TI)
  1653. std::swap(NewTrueOp, NewFalseOp);
  1654. Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
  1655. SI.getName() + ".p", &SI);
  1656. if (SI.getType()->isFPOrFPVectorTy()) {
  1657. Instruction *RI =
  1658. BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
  1659. FastMathFlags Flags = AddOp->getFastMathFlags();
  1660. Flags &= SubOp->getFastMathFlags();
  1661. RI->setFastMathFlags(Flags);
  1662. return RI;
  1663. } else
  1664. return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
  1665. }
  1666. }
  1667. return nullptr;
  1668. }
  1669. /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
  1670. /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
  1671. /// Along with a number of patterns similar to:
  1672. /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1673. /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1674. static Instruction *
  1675. foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
  1676. Value *CondVal = SI.getCondition();
  1677. Value *TrueVal = SI.getTrueValue();
  1678. Value *FalseVal = SI.getFalseValue();
  1679. WithOverflowInst *II;
  1680. if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
  1681. !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
  1682. return nullptr;
  1683. Value *X = II->getLHS();
  1684. Value *Y = II->getRHS();
  1685. auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
  1686. Type *Ty = Limit->getType();
  1687. ICmpInst::Predicate Pred;
  1688. Value *TrueVal, *FalseVal, *Op;
  1689. const APInt *C;
  1690. if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
  1691. m_Value(TrueVal), m_Value(FalseVal))))
  1692. return false;
  1693. auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
  1694. auto IsMinMax = [&](Value *Min, Value *Max) {
  1695. APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
  1696. APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
  1697. return match(Min, m_SpecificInt(MinVal)) &&
  1698. match(Max, m_SpecificInt(MaxVal));
  1699. };
  1700. if (Op != X && Op != Y)
  1701. return false;
  1702. if (IsAdd) {
  1703. // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1704. // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1705. // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1706. // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1707. if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
  1708. IsMinMax(TrueVal, FalseVal))
  1709. return true;
  1710. // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1711. // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1712. // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1713. // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1714. if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
  1715. IsMinMax(FalseVal, TrueVal))
  1716. return true;
  1717. } else {
  1718. // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1719. // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1720. if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
  1721. IsMinMax(TrueVal, FalseVal))
  1722. return true;
  1723. // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1724. // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1725. if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
  1726. IsMinMax(FalseVal, TrueVal))
  1727. return true;
  1728. // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1729. // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1730. if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
  1731. IsMinMax(FalseVal, TrueVal))
  1732. return true;
  1733. // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1734. // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1735. if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
  1736. IsMinMax(TrueVal, FalseVal))
  1737. return true;
  1738. }
  1739. return false;
  1740. };
  1741. Intrinsic::ID NewIntrinsicID;
  1742. if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
  1743. match(TrueVal, m_AllOnes()))
  1744. // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
  1745. NewIntrinsicID = Intrinsic::uadd_sat;
  1746. else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
  1747. match(TrueVal, m_Zero()))
  1748. // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
  1749. NewIntrinsicID = Intrinsic::usub_sat;
  1750. else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
  1751. IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
  1752. // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1753. // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1754. // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1755. // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1756. // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1757. // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
  1758. // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1759. // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
  1760. NewIntrinsicID = Intrinsic::sadd_sat;
  1761. else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
  1762. IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
  1763. // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1764. // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1765. // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1766. // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1767. // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1768. // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
  1769. // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1770. // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
  1771. NewIntrinsicID = Intrinsic::ssub_sat;
  1772. else
  1773. return nullptr;
  1774. Function *F =
  1775. Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
  1776. return CallInst::Create(F, {X, Y});
  1777. }
  1778. Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
  1779. Constant *C;
  1780. if (!match(Sel.getTrueValue(), m_Constant(C)) &&
  1781. !match(Sel.getFalseValue(), m_Constant(C)))
  1782. return nullptr;
  1783. Instruction *ExtInst;
  1784. if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
  1785. !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
  1786. return nullptr;
  1787. auto ExtOpcode = ExtInst->getOpcode();
  1788. if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
  1789. return nullptr;
  1790. // If we are extending from a boolean type or if we can create a select that
  1791. // has the same size operands as its condition, try to narrow the select.
  1792. Value *X = ExtInst->getOperand(0);
  1793. Type *SmallType = X->getType();
  1794. Value *Cond = Sel.getCondition();
  1795. auto *Cmp = dyn_cast<CmpInst>(Cond);
  1796. if (!SmallType->isIntOrIntVectorTy(1) &&
  1797. (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
  1798. return nullptr;
  1799. // If the constant is the same after truncation to the smaller type and
  1800. // extension to the original type, we can narrow the select.
  1801. Type *SelType = Sel.getType();
  1802. Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
  1803. Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
  1804. if (ExtC == C && ExtInst->hasOneUse()) {
  1805. Value *TruncCVal = cast<Value>(TruncC);
  1806. if (ExtInst == Sel.getFalseValue())
  1807. std::swap(X, TruncCVal);
  1808. // select Cond, (ext X), C --> ext(select Cond, X, C')
  1809. // select Cond, C, (ext X) --> ext(select Cond, C', X)
  1810. Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
  1811. return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
  1812. }
  1813. // If one arm of the select is the extend of the condition, replace that arm
  1814. // with the extension of the appropriate known bool value.
  1815. if (Cond == X) {
  1816. if (ExtInst == Sel.getTrueValue()) {
  1817. // select X, (sext X), C --> select X, -1, C
  1818. // select X, (zext X), C --> select X, 1, C
  1819. Constant *One = ConstantInt::getTrue(SmallType);
  1820. Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
  1821. return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
  1822. } else {
  1823. // select X, C, (sext X) --> select X, C, 0
  1824. // select X, C, (zext X) --> select X, C, 0
  1825. Constant *Zero = ConstantInt::getNullValue(SelType);
  1826. return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
  1827. }
  1828. }
  1829. return nullptr;
  1830. }
  1831. /// Try to transform a vector select with a constant condition vector into a
  1832. /// shuffle for easier combining with other shuffles and insert/extract.
  1833. static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
  1834. Value *CondVal = SI.getCondition();
  1835. Constant *CondC;
  1836. auto *CondValTy = dyn_cast<FixedVectorType>(CondVal->getType());
  1837. if (!CondValTy || !match(CondVal, m_Constant(CondC)))
  1838. return nullptr;
  1839. unsigned NumElts = CondValTy->getNumElements();
  1840. SmallVector<int, 16> Mask;
  1841. Mask.reserve(NumElts);
  1842. for (unsigned i = 0; i != NumElts; ++i) {
  1843. Constant *Elt = CondC->getAggregateElement(i);
  1844. if (!Elt)
  1845. return nullptr;
  1846. if (Elt->isOneValue()) {
  1847. // If the select condition element is true, choose from the 1st vector.
  1848. Mask.push_back(i);
  1849. } else if (Elt->isNullValue()) {
  1850. // If the select condition element is false, choose from the 2nd vector.
  1851. Mask.push_back(i + NumElts);
  1852. } else if (isa<UndefValue>(Elt)) {
  1853. // Undef in a select condition (choose one of the operands) does not mean
  1854. // the same thing as undef in a shuffle mask (any value is acceptable), so
  1855. // give up.
  1856. return nullptr;
  1857. } else {
  1858. // Bail out on a constant expression.
  1859. return nullptr;
  1860. }
  1861. }
  1862. return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
  1863. }
  1864. /// If we have a select of vectors with a scalar condition, try to convert that
  1865. /// to a vector select by splatting the condition. A splat may get folded with
  1866. /// other operations in IR and having all operands of a select be vector types
  1867. /// is likely better for vector codegen.
  1868. static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
  1869. InstCombinerImpl &IC) {
  1870. auto *Ty = dyn_cast<VectorType>(Sel.getType());
  1871. if (!Ty)
  1872. return nullptr;
  1873. // We can replace a single-use extract with constant index.
  1874. Value *Cond = Sel.getCondition();
  1875. if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
  1876. return nullptr;
  1877. // select (extelt V, Index), T, F --> select (splat V, Index), T, F
  1878. // Splatting the extracted condition reduces code (we could directly create a
  1879. // splat shuffle of the source vector to eliminate the intermediate step).
  1880. return IC.replaceOperand(
  1881. Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
  1882. }
  1883. /// Reuse bitcasted operands between a compare and select:
  1884. /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
  1885. /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
  1886. static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
  1887. InstCombiner::BuilderTy &Builder) {
  1888. Value *Cond = Sel.getCondition();
  1889. Value *TVal = Sel.getTrueValue();
  1890. Value *FVal = Sel.getFalseValue();
  1891. CmpInst::Predicate Pred;
  1892. Value *A, *B;
  1893. if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
  1894. return nullptr;
  1895. // The select condition is a compare instruction. If the select's true/false
  1896. // values are already the same as the compare operands, there's nothing to do.
  1897. if (TVal == A || TVal == B || FVal == A || FVal == B)
  1898. return nullptr;
  1899. Value *C, *D;
  1900. if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
  1901. return nullptr;
  1902. // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
  1903. Value *TSrc, *FSrc;
  1904. if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
  1905. !match(FVal, m_BitCast(m_Value(FSrc))))
  1906. return nullptr;
  1907. // If the select true/false values are *different bitcasts* of the same source
  1908. // operands, make the select operands the same as the compare operands and
  1909. // cast the result. This is the canonical select form for min/max.
  1910. Value *NewSel;
  1911. if (TSrc == C && FSrc == D) {
  1912. // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
  1913. // bitcast (select (cmp A, B), A, B)
  1914. NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
  1915. } else if (TSrc == D && FSrc == C) {
  1916. // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
  1917. // bitcast (select (cmp A, B), B, A)
  1918. NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
  1919. } else {
  1920. return nullptr;
  1921. }
  1922. return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
  1923. }
  1924. /// Try to eliminate select instructions that test the returned flag of cmpxchg
  1925. /// instructions.
  1926. ///
  1927. /// If a select instruction tests the returned flag of a cmpxchg instruction and
  1928. /// selects between the returned value of the cmpxchg instruction its compare
  1929. /// operand, the result of the select will always be equal to its false value.
  1930. /// For example:
  1931. ///
  1932. /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
  1933. /// %1 = extractvalue { i64, i1 } %0, 1
  1934. /// %2 = extractvalue { i64, i1 } %0, 0
  1935. /// %3 = select i1 %1, i64 %compare, i64 %2
  1936. /// ret i64 %3
  1937. ///
  1938. /// The returned value of the cmpxchg instruction (%2) is the original value
  1939. /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
  1940. /// must have been equal to %compare. Thus, the result of the select is always
  1941. /// equal to %2, and the code can be simplified to:
  1942. ///
  1943. /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
  1944. /// %1 = extractvalue { i64, i1 } %0, 0
  1945. /// ret i64 %1
  1946. ///
  1947. static Value *foldSelectCmpXchg(SelectInst &SI) {
  1948. // A helper that determines if V is an extractvalue instruction whose
  1949. // aggregate operand is a cmpxchg instruction and whose single index is equal
  1950. // to I. If such conditions are true, the helper returns the cmpxchg
  1951. // instruction; otherwise, a nullptr is returned.
  1952. auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
  1953. auto *Extract = dyn_cast<ExtractValueInst>(V);
  1954. if (!Extract)
  1955. return nullptr;
  1956. if (Extract->getIndices()[0] != I)
  1957. return nullptr;
  1958. return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
  1959. };
  1960. // If the select has a single user, and this user is a select instruction that
  1961. // we can simplify, skip the cmpxchg simplification for now.
  1962. if (SI.hasOneUse())
  1963. if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
  1964. if (Select->getCondition() == SI.getCondition())
  1965. if (Select->getFalseValue() == SI.getTrueValue() ||
  1966. Select->getTrueValue() == SI.getFalseValue())
  1967. return nullptr;
  1968. // Ensure the select condition is the returned flag of a cmpxchg instruction.
  1969. auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
  1970. if (!CmpXchg)
  1971. return nullptr;
  1972. // Check the true value case: The true value of the select is the returned
  1973. // value of the same cmpxchg used by the condition, and the false value is the
  1974. // cmpxchg instruction's compare operand.
  1975. if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
  1976. if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
  1977. return SI.getFalseValue();
  1978. // Check the false value case: The false value of the select is the returned
  1979. // value of the same cmpxchg used by the condition, and the true value is the
  1980. // cmpxchg instruction's compare operand.
  1981. if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
  1982. if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
  1983. return SI.getFalseValue();
  1984. return nullptr;
  1985. }
  1986. /// Try to reduce a funnel/rotate pattern that includes a compare and select
  1987. /// into a funnel shift intrinsic. Example:
  1988. /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
  1989. /// --> call llvm.fshl.i32(a, a, b)
  1990. /// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
  1991. /// --> call llvm.fshl.i32(a, b, c)
  1992. /// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
  1993. /// --> call llvm.fshr.i32(a, b, c)
  1994. static Instruction *foldSelectFunnelShift(SelectInst &Sel,
  1995. InstCombiner::BuilderTy &Builder) {
  1996. // This must be a power-of-2 type for a bitmasking transform to be valid.
  1997. unsigned Width = Sel.getType()->getScalarSizeInBits();
  1998. if (!isPowerOf2_32(Width))
  1999. return nullptr;
  2000. BinaryOperator *Or0, *Or1;
  2001. if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
  2002. return nullptr;
  2003. Value *SV0, *SV1, *SA0, *SA1;
  2004. if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0),
  2005. m_ZExtOrSelf(m_Value(SA0))))) ||
  2006. !match(Or1, m_OneUse(m_LogicalShift(m_Value(SV1),
  2007. m_ZExtOrSelf(m_Value(SA1))))) ||
  2008. Or0->getOpcode() == Or1->getOpcode())
  2009. return nullptr;
  2010. // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
  2011. if (Or0->getOpcode() == BinaryOperator::LShr) {
  2012. std::swap(Or0, Or1);
  2013. std::swap(SV0, SV1);
  2014. std::swap(SA0, SA1);
  2015. }
  2016. assert(Or0->getOpcode() == BinaryOperator::Shl &&
  2017. Or1->getOpcode() == BinaryOperator::LShr &&
  2018. "Illegal or(shift,shift) pair");
  2019. // Check the shift amounts to see if they are an opposite pair.
  2020. Value *ShAmt;
  2021. if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
  2022. ShAmt = SA0;
  2023. else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
  2024. ShAmt = SA1;
  2025. else
  2026. return nullptr;
  2027. // We should now have this pattern:
  2028. // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
  2029. // The false value of the select must be a funnel-shift of the true value:
  2030. // IsFShl -> TVal must be SV0 else TVal must be SV1.
  2031. bool IsFshl = (ShAmt == SA0);
  2032. Value *TVal = Sel.getTrueValue();
  2033. if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
  2034. return nullptr;
  2035. // Finally, see if the select is filtering out a shift-by-zero.
  2036. Value *Cond = Sel.getCondition();
  2037. ICmpInst::Predicate Pred;
  2038. if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
  2039. Pred != ICmpInst::ICMP_EQ)
  2040. return nullptr;
  2041. // If this is not a rotate then the select was blocking poison from the
  2042. // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
  2043. if (SV0 != SV1) {
  2044. if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1))
  2045. SV1 = Builder.CreateFreeze(SV1);
  2046. else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0))
  2047. SV0 = Builder.CreateFreeze(SV0);
  2048. }
  2049. // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
  2050. // Convert to funnel shift intrinsic.
  2051. Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
  2052. Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
  2053. ShAmt = Builder.CreateZExt(ShAmt, Sel.getType());
  2054. return CallInst::Create(F, { SV0, SV1, ShAmt });
  2055. }
  2056. static Instruction *foldSelectToCopysign(SelectInst &Sel,
  2057. InstCombiner::BuilderTy &Builder) {
  2058. Value *Cond = Sel.getCondition();
  2059. Value *TVal = Sel.getTrueValue();
  2060. Value *FVal = Sel.getFalseValue();
  2061. Type *SelType = Sel.getType();
  2062. // Match select ?, TC, FC where the constants are equal but negated.
  2063. // TODO: Generalize to handle a negated variable operand?
  2064. const APFloat *TC, *FC;
  2065. if (!match(TVal, m_APFloatAllowUndef(TC)) ||
  2066. !match(FVal, m_APFloatAllowUndef(FC)) ||
  2067. !abs(*TC).bitwiseIsEqual(abs(*FC)))
  2068. return nullptr;
  2069. assert(TC != FC && "Expected equal select arms to simplify");
  2070. Value *X;
  2071. const APInt *C;
  2072. bool IsTrueIfSignSet;
  2073. ICmpInst::Predicate Pred;
  2074. if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
  2075. !InstCombiner::isSignBitCheck(Pred, *C, IsTrueIfSignSet) ||
  2076. X->getType() != SelType)
  2077. return nullptr;
  2078. // If needed, negate the value that will be the sign argument of the copysign:
  2079. // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
  2080. // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
  2081. // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
  2082. // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
  2083. // Note: FMF from the select can not be propagated to the new instructions.
  2084. if (IsTrueIfSignSet ^ TC->isNegative())
  2085. X = Builder.CreateFNeg(X);
  2086. // Canonicalize the magnitude argument as the positive constant since we do
  2087. // not care about its sign.
  2088. Value *MagArg = ConstantFP::get(SelType, abs(*TC));
  2089. Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
  2090. Sel.getType());
  2091. return CallInst::Create(F, { MagArg, X });
  2092. }
  2093. Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
  2094. if (!isa<VectorType>(Sel.getType()))
  2095. return nullptr;
  2096. Value *Cond = Sel.getCondition();
  2097. Value *TVal = Sel.getTrueValue();
  2098. Value *FVal = Sel.getFalseValue();
  2099. Value *C, *X, *Y;
  2100. if (match(Cond, m_VecReverse(m_Value(C)))) {
  2101. auto createSelReverse = [&](Value *C, Value *X, Value *Y) {
  2102. Value *V = Builder.CreateSelect(C, X, Y, Sel.getName(), &Sel);
  2103. if (auto *I = dyn_cast<Instruction>(V))
  2104. I->copyIRFlags(&Sel);
  2105. Module *M = Sel.getModule();
  2106. Function *F = Intrinsic::getDeclaration(
  2107. M, Intrinsic::experimental_vector_reverse, V->getType());
  2108. return CallInst::Create(F, V);
  2109. };
  2110. if (match(TVal, m_VecReverse(m_Value(X)))) {
  2111. // select rev(C), rev(X), rev(Y) --> rev(select C, X, Y)
  2112. if (match(FVal, m_VecReverse(m_Value(Y))) &&
  2113. (Cond->hasOneUse() || TVal->hasOneUse() || FVal->hasOneUse()))
  2114. return createSelReverse(C, X, Y);
  2115. // select rev(C), rev(X), FValSplat --> rev(select C, X, FValSplat)
  2116. if ((Cond->hasOneUse() || TVal->hasOneUse()) && isSplatValue(FVal))
  2117. return createSelReverse(C, X, FVal);
  2118. }
  2119. // select rev(C), TValSplat, rev(Y) --> rev(select C, TValSplat, Y)
  2120. else if (isSplatValue(TVal) && match(FVal, m_VecReverse(m_Value(Y))) &&
  2121. (Cond->hasOneUse() || FVal->hasOneUse()))
  2122. return createSelReverse(C, TVal, Y);
  2123. }
  2124. auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
  2125. if (!VecTy)
  2126. return nullptr;
  2127. unsigned NumElts = VecTy->getNumElements();
  2128. APInt UndefElts(NumElts, 0);
  2129. APInt AllOnesEltMask(APInt::getAllOnes(NumElts));
  2130. if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
  2131. if (V != &Sel)
  2132. return replaceInstUsesWith(Sel, V);
  2133. return &Sel;
  2134. }
  2135. // A select of a "select shuffle" with a common operand can be rearranged
  2136. // to select followed by "select shuffle". Because of poison, this only works
  2137. // in the case of a shuffle with no undefined mask elements.
  2138. ArrayRef<int> Mask;
  2139. if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
  2140. !is_contained(Mask, UndefMaskElem) &&
  2141. cast<ShuffleVectorInst>(TVal)->isSelect()) {
  2142. if (X == FVal) {
  2143. // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
  2144. Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
  2145. return new ShuffleVectorInst(X, NewSel, Mask);
  2146. }
  2147. if (Y == FVal) {
  2148. // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
  2149. Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
  2150. return new ShuffleVectorInst(NewSel, Y, Mask);
  2151. }
  2152. }
  2153. if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
  2154. !is_contained(Mask, UndefMaskElem) &&
  2155. cast<ShuffleVectorInst>(FVal)->isSelect()) {
  2156. if (X == TVal) {
  2157. // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
  2158. Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
  2159. return new ShuffleVectorInst(X, NewSel, Mask);
  2160. }
  2161. if (Y == TVal) {
  2162. // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
  2163. Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
  2164. return new ShuffleVectorInst(NewSel, Y, Mask);
  2165. }
  2166. }
  2167. return nullptr;
  2168. }
  2169. static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
  2170. const DominatorTree &DT,
  2171. InstCombiner::BuilderTy &Builder) {
  2172. // Find the block's immediate dominator that ends with a conditional branch
  2173. // that matches select's condition (maybe inverted).
  2174. auto *IDomNode = DT[BB]->getIDom();
  2175. if (!IDomNode)
  2176. return nullptr;
  2177. BasicBlock *IDom = IDomNode->getBlock();
  2178. Value *Cond = Sel.getCondition();
  2179. Value *IfTrue, *IfFalse;
  2180. BasicBlock *TrueSucc, *FalseSucc;
  2181. if (match(IDom->getTerminator(),
  2182. m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
  2183. m_BasicBlock(FalseSucc)))) {
  2184. IfTrue = Sel.getTrueValue();
  2185. IfFalse = Sel.getFalseValue();
  2186. } else if (match(IDom->getTerminator(),
  2187. m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
  2188. m_BasicBlock(FalseSucc)))) {
  2189. IfTrue = Sel.getFalseValue();
  2190. IfFalse = Sel.getTrueValue();
  2191. } else
  2192. return nullptr;
  2193. // Make sure the branches are actually different.
  2194. if (TrueSucc == FalseSucc)
  2195. return nullptr;
  2196. // We want to replace select %cond, %a, %b with a phi that takes value %a
  2197. // for all incoming edges that are dominated by condition `%cond == true`,
  2198. // and value %b for edges dominated by condition `%cond == false`. If %a
  2199. // or %b are also phis from the same basic block, we can go further and take
  2200. // their incoming values from the corresponding blocks.
  2201. BasicBlockEdge TrueEdge(IDom, TrueSucc);
  2202. BasicBlockEdge FalseEdge(IDom, FalseSucc);
  2203. DenseMap<BasicBlock *, Value *> Inputs;
  2204. for (auto *Pred : predecessors(BB)) {
  2205. // Check implication.
  2206. BasicBlockEdge Incoming(Pred, BB);
  2207. if (DT.dominates(TrueEdge, Incoming))
  2208. Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
  2209. else if (DT.dominates(FalseEdge, Incoming))
  2210. Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
  2211. else
  2212. return nullptr;
  2213. // Check availability.
  2214. if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
  2215. if (!DT.dominates(Insn, Pred->getTerminator()))
  2216. return nullptr;
  2217. }
  2218. Builder.SetInsertPoint(&*BB->begin());
  2219. auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
  2220. for (auto *Pred : predecessors(BB))
  2221. PN->addIncoming(Inputs[Pred], Pred);
  2222. PN->takeName(&Sel);
  2223. return PN;
  2224. }
  2225. static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
  2226. InstCombiner::BuilderTy &Builder) {
  2227. // Try to replace this select with Phi in one of these blocks.
  2228. SmallSetVector<BasicBlock *, 4> CandidateBlocks;
  2229. CandidateBlocks.insert(Sel.getParent());
  2230. for (Value *V : Sel.operands())
  2231. if (auto *I = dyn_cast<Instruction>(V))
  2232. CandidateBlocks.insert(I->getParent());
  2233. for (BasicBlock *BB : CandidateBlocks)
  2234. if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
  2235. return PN;
  2236. return nullptr;
  2237. }
  2238. static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
  2239. FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition());
  2240. if (!FI)
  2241. return nullptr;
  2242. Value *Cond = FI->getOperand(0);
  2243. Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
  2244. // select (freeze(x == y)), x, y --> y
  2245. // select (freeze(x != y)), x, y --> x
  2246. // The freeze should be only used by this select. Otherwise, remaining uses of
  2247. // the freeze can observe a contradictory value.
  2248. // c = freeze(x == y) ; Let's assume that y = poison & x = 42; c is 0 or 1
  2249. // a = select c, x, y ;
  2250. // f(a, c) ; f(poison, 1) cannot happen, but if a is folded
  2251. // ; to y, this can happen.
  2252. CmpInst::Predicate Pred;
  2253. if (FI->hasOneUse() &&
  2254. match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) &&
  2255. (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) {
  2256. return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal;
  2257. }
  2258. return nullptr;
  2259. }
  2260. Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
  2261. SelectInst &SI,
  2262. bool IsAnd) {
  2263. Value *CondVal = SI.getCondition();
  2264. Value *A = SI.getTrueValue();
  2265. Value *B = SI.getFalseValue();
  2266. assert(Op->getType()->isIntOrIntVectorTy(1) &&
  2267. "Op must be either i1 or vector of i1.");
  2268. std::optional<bool> Res = isImpliedCondition(Op, CondVal, DL, IsAnd);
  2269. if (!Res)
  2270. return nullptr;
  2271. Value *Zero = Constant::getNullValue(A->getType());
  2272. Value *One = Constant::getAllOnesValue(A->getType());
  2273. if (*Res == true) {
  2274. if (IsAnd)
  2275. // select op, (select cond, A, B), false => select op, A, false
  2276. // and op, (select cond, A, B) => select op, A, false
  2277. // if op = true implies condval = true.
  2278. return SelectInst::Create(Op, A, Zero);
  2279. else
  2280. // select op, true, (select cond, A, B) => select op, true, A
  2281. // or op, (select cond, A, B) => select op, true, A
  2282. // if op = false implies condval = true.
  2283. return SelectInst::Create(Op, One, A);
  2284. } else {
  2285. if (IsAnd)
  2286. // select op, (select cond, A, B), false => select op, B, false
  2287. // and op, (select cond, A, B) => select op, B, false
  2288. // if op = true implies condval = false.
  2289. return SelectInst::Create(Op, B, Zero);
  2290. else
  2291. // select op, true, (select cond, A, B) => select op, true, B
  2292. // or op, (select cond, A, B) => select op, true, B
  2293. // if op = false implies condval = false.
  2294. return SelectInst::Create(Op, One, B);
  2295. }
  2296. }
  2297. // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
  2298. // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
  2299. static Instruction *foldSelectWithFCmpToFabs(SelectInst &SI,
  2300. InstCombinerImpl &IC) {
  2301. Value *CondVal = SI.getCondition();
  2302. bool ChangedFMF = false;
  2303. for (bool Swap : {false, true}) {
  2304. Value *TrueVal = SI.getTrueValue();
  2305. Value *X = SI.getFalseValue();
  2306. CmpInst::Predicate Pred;
  2307. if (Swap)
  2308. std::swap(TrueVal, X);
  2309. if (!match(CondVal, m_FCmp(Pred, m_Specific(X), m_AnyZeroFP())))
  2310. continue;
  2311. // fold (X <= +/-0.0) ? (0.0 - X) : X to fabs(X), when 'Swap' is false
  2312. // fold (X > +/-0.0) ? X : (0.0 - X) to fabs(X), when 'Swap' is true
  2313. if (match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) {
  2314. if (!Swap && (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
  2315. Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
  2316. return IC.replaceInstUsesWith(SI, Fabs);
  2317. }
  2318. if (Swap && (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
  2319. Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
  2320. return IC.replaceInstUsesWith(SI, Fabs);
  2321. }
  2322. }
  2323. if (!match(TrueVal, m_FNeg(m_Specific(X))))
  2324. return nullptr;
  2325. // Forward-propagate nnan and ninf from the fneg to the select.
  2326. // If all inputs are not those values, then the select is not either.
  2327. // Note: nsz is defined differently, so it may not be correct to propagate.
  2328. FastMathFlags FMF = cast<FPMathOperator>(TrueVal)->getFastMathFlags();
  2329. if (FMF.noNaNs() && !SI.hasNoNaNs()) {
  2330. SI.setHasNoNaNs(true);
  2331. ChangedFMF = true;
  2332. }
  2333. if (FMF.noInfs() && !SI.hasNoInfs()) {
  2334. SI.setHasNoInfs(true);
  2335. ChangedFMF = true;
  2336. }
  2337. // With nsz, when 'Swap' is false:
  2338. // fold (X < +/-0.0) ? -X : X or (X <= +/-0.0) ? -X : X to fabs(X)
  2339. // fold (X > +/-0.0) ? -X : X or (X >= +/-0.0) ? -X : X to -fabs(x)
  2340. // when 'Swap' is true:
  2341. // fold (X > +/-0.0) ? X : -X or (X >= +/-0.0) ? X : -X to fabs(X)
  2342. // fold (X < +/-0.0) ? X : -X or (X <= +/-0.0) ? X : -X to -fabs(X)
  2343. //
  2344. // Note: We require "nnan" for this fold because fcmp ignores the signbit
  2345. // of NAN, but IEEE-754 specifies the signbit of NAN values with
  2346. // fneg/fabs operations.
  2347. if (!SI.hasNoSignedZeros() || !SI.hasNoNaNs())
  2348. return nullptr;
  2349. if (Swap)
  2350. Pred = FCmpInst::getSwappedPredicate(Pred);
  2351. bool IsLTOrLE = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
  2352. Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE;
  2353. bool IsGTOrGE = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
  2354. Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE;
  2355. if (IsLTOrLE) {
  2356. Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
  2357. return IC.replaceInstUsesWith(SI, Fabs);
  2358. }
  2359. if (IsGTOrGE) {
  2360. Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
  2361. Instruction *NewFNeg = UnaryOperator::CreateFNeg(Fabs);
  2362. NewFNeg->setFastMathFlags(SI.getFastMathFlags());
  2363. return NewFNeg;
  2364. }
  2365. }
  2366. return ChangedFMF ? &SI : nullptr;
  2367. }
  2368. // Match the following IR pattern:
  2369. // %x.lowbits = and i8 %x, %lowbitmask
  2370. // %x.lowbits.are.zero = icmp eq i8 %x.lowbits, 0
  2371. // %x.biased = add i8 %x, %bias
  2372. // %x.biased.highbits = and i8 %x.biased, %highbitmask
  2373. // %x.roundedup = select i1 %x.lowbits.are.zero, i8 %x, i8 %x.biased.highbits
  2374. // Define:
  2375. // %alignment = add i8 %lowbitmask, 1
  2376. // Iff 1. an %alignment is a power-of-two (aka, %lowbitmask is a low bit mask)
  2377. // and 2. %bias is equal to either %lowbitmask or %alignment,
  2378. // and 3. %highbitmask is equal to ~%lowbitmask (aka, to -%alignment)
  2379. // then this pattern can be transformed into:
  2380. // %x.offset = add i8 %x, %lowbitmask
  2381. // %x.roundedup = and i8 %x.offset, %highbitmask
  2382. static Value *
  2383. foldRoundUpIntegerWithPow2Alignment(SelectInst &SI,
  2384. InstCombiner::BuilderTy &Builder) {
  2385. Value *Cond = SI.getCondition();
  2386. Value *X = SI.getTrueValue();
  2387. Value *XBiasedHighBits = SI.getFalseValue();
  2388. ICmpInst::Predicate Pred;
  2389. Value *XLowBits;
  2390. if (!match(Cond, m_ICmp(Pred, m_Value(XLowBits), m_ZeroInt())) ||
  2391. !ICmpInst::isEquality(Pred))
  2392. return nullptr;
  2393. if (Pred == ICmpInst::Predicate::ICMP_NE)
  2394. std::swap(X, XBiasedHighBits);
  2395. // FIXME: we could support non non-splats here.
  2396. const APInt *LowBitMaskCst;
  2397. if (!match(XLowBits, m_And(m_Specific(X), m_APIntAllowUndef(LowBitMaskCst))))
  2398. return nullptr;
  2399. // Match even if the AND and ADD are swapped.
  2400. const APInt *BiasCst, *HighBitMaskCst;
  2401. if (!match(XBiasedHighBits,
  2402. m_And(m_Add(m_Specific(X), m_APIntAllowUndef(BiasCst)),
  2403. m_APIntAllowUndef(HighBitMaskCst))) &&
  2404. !match(XBiasedHighBits,
  2405. m_Add(m_And(m_Specific(X), m_APIntAllowUndef(HighBitMaskCst)),
  2406. m_APIntAllowUndef(BiasCst))))
  2407. return nullptr;
  2408. if (!LowBitMaskCst->isMask())
  2409. return nullptr;
  2410. APInt InvertedLowBitMaskCst = ~*LowBitMaskCst;
  2411. if (InvertedLowBitMaskCst != *HighBitMaskCst)
  2412. return nullptr;
  2413. APInt AlignmentCst = *LowBitMaskCst + 1;
  2414. if (*BiasCst != AlignmentCst && *BiasCst != *LowBitMaskCst)
  2415. return nullptr;
  2416. if (!XBiasedHighBits->hasOneUse()) {
  2417. if (*BiasCst == *LowBitMaskCst)
  2418. return XBiasedHighBits;
  2419. return nullptr;
  2420. }
  2421. // FIXME: could we preserve undef's here?
  2422. Type *Ty = X->getType();
  2423. Value *XOffset = Builder.CreateAdd(X, ConstantInt::get(Ty, *LowBitMaskCst),
  2424. X->getName() + ".biased");
  2425. Value *R = Builder.CreateAnd(XOffset, ConstantInt::get(Ty, *HighBitMaskCst));
  2426. R->takeName(&SI);
  2427. return R;
  2428. }
  2429. namespace {
  2430. struct DecomposedSelect {
  2431. Value *Cond = nullptr;
  2432. Value *TrueVal = nullptr;
  2433. Value *FalseVal = nullptr;
  2434. };
  2435. } // namespace
  2436. /// Look for patterns like
  2437. /// %outer.cond = select i1 %inner.cond, i1 %alt.cond, i1 false
  2438. /// %inner.sel = select i1 %inner.cond, i8 %inner.sel.t, i8 %inner.sel.f
  2439. /// %outer.sel = select i1 %outer.cond, i8 %outer.sel.t, i8 %inner.sel
  2440. /// and rewrite it as
  2441. /// %inner.sel = select i1 %cond.alternative, i8 %sel.outer.t, i8 %sel.inner.t
  2442. /// %sel.outer = select i1 %cond.inner, i8 %inner.sel, i8 %sel.inner.f
  2443. static Instruction *foldNestedSelects(SelectInst &OuterSelVal,
  2444. InstCombiner::BuilderTy &Builder) {
  2445. // We must start with a `select`.
  2446. DecomposedSelect OuterSel;
  2447. match(&OuterSelVal,
  2448. m_Select(m_Value(OuterSel.Cond), m_Value(OuterSel.TrueVal),
  2449. m_Value(OuterSel.FalseVal)));
  2450. // Canonicalize inversion of the outermost `select`'s condition.
  2451. if (match(OuterSel.Cond, m_Not(m_Value(OuterSel.Cond))))
  2452. std::swap(OuterSel.TrueVal, OuterSel.FalseVal);
  2453. // The condition of the outermost select must be an `and`/`or`.
  2454. if (!match(OuterSel.Cond, m_c_LogicalOp(m_Value(), m_Value())))
  2455. return nullptr;
  2456. // Depending on the logical op, inner select might be in different hand.
  2457. bool IsAndVariant = match(OuterSel.Cond, m_LogicalAnd());
  2458. Value *InnerSelVal = IsAndVariant ? OuterSel.FalseVal : OuterSel.TrueVal;
  2459. // Profitability check - avoid increasing instruction count.
  2460. if (none_of(ArrayRef<Value *>({OuterSelVal.getCondition(), InnerSelVal}),
  2461. [](Value *V) { return V->hasOneUse(); }))
  2462. return nullptr;
  2463. // The appropriate hand of the outermost `select` must be a select itself.
  2464. DecomposedSelect InnerSel;
  2465. if (!match(InnerSelVal,
  2466. m_Select(m_Value(InnerSel.Cond), m_Value(InnerSel.TrueVal),
  2467. m_Value(InnerSel.FalseVal))))
  2468. return nullptr;
  2469. // Canonicalize inversion of the innermost `select`'s condition.
  2470. if (match(InnerSel.Cond, m_Not(m_Value(InnerSel.Cond))))
  2471. std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
  2472. Value *AltCond = nullptr;
  2473. auto matchOuterCond = [OuterSel, &AltCond](auto m_InnerCond) {
  2474. return match(OuterSel.Cond, m_c_LogicalOp(m_InnerCond, m_Value(AltCond)));
  2475. };
  2476. // Finally, match the condition that was driving the outermost `select`,
  2477. // it should be a logical operation between the condition that was driving
  2478. // the innermost `select` (after accounting for the possible inversions
  2479. // of the condition), and some other condition.
  2480. if (matchOuterCond(m_Specific(InnerSel.Cond))) {
  2481. // Done!
  2482. } else if (Value * NotInnerCond; matchOuterCond(m_CombineAnd(
  2483. m_Not(m_Specific(InnerSel.Cond)), m_Value(NotInnerCond)))) {
  2484. // Done!
  2485. std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
  2486. InnerSel.Cond = NotInnerCond;
  2487. } else // Not the pattern we were looking for.
  2488. return nullptr;
  2489. Value *SelInner = Builder.CreateSelect(
  2490. AltCond, IsAndVariant ? OuterSel.TrueVal : InnerSel.FalseVal,
  2491. IsAndVariant ? InnerSel.TrueVal : OuterSel.FalseVal);
  2492. SelInner->takeName(InnerSelVal);
  2493. return SelectInst::Create(InnerSel.Cond,
  2494. IsAndVariant ? SelInner : InnerSel.TrueVal,
  2495. !IsAndVariant ? SelInner : InnerSel.FalseVal);
  2496. }
  2497. Instruction *InstCombinerImpl::foldSelectOfBools(SelectInst &SI) {
  2498. Value *CondVal = SI.getCondition();
  2499. Value *TrueVal = SI.getTrueValue();
  2500. Value *FalseVal = SI.getFalseValue();
  2501. Type *SelType = SI.getType();
  2502. // Avoid potential infinite loops by checking for non-constant condition.
  2503. // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
  2504. // Scalar select must have simplified?
  2505. if (!SelType->isIntOrIntVectorTy(1) || isa<Constant>(CondVal) ||
  2506. TrueVal->getType() != CondVal->getType())
  2507. return nullptr;
  2508. auto *One = ConstantInt::getTrue(SelType);
  2509. auto *Zero = ConstantInt::getFalse(SelType);
  2510. Value *A, *B, *C, *D;
  2511. // Folding select to and/or i1 isn't poison safe in general. impliesPoison
  2512. // checks whether folding it does not convert a well-defined value into
  2513. // poison.
  2514. if (match(TrueVal, m_One())) {
  2515. if (impliesPoison(FalseVal, CondVal)) {
  2516. // Change: A = select B, true, C --> A = or B, C
  2517. return BinaryOperator::CreateOr(CondVal, FalseVal);
  2518. }
  2519. if (auto *LHS = dyn_cast<FCmpInst>(CondVal))
  2520. if (auto *RHS = dyn_cast<FCmpInst>(FalseVal))
  2521. if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false,
  2522. /*IsSelectLogical*/ true))
  2523. return replaceInstUsesWith(SI, V);
  2524. // (A && B) || (C && B) --> (A || C) && B
  2525. if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
  2526. match(FalseVal, m_LogicalAnd(m_Value(C), m_Value(D))) &&
  2527. (CondVal->hasOneUse() || FalseVal->hasOneUse())) {
  2528. bool CondLogicAnd = isa<SelectInst>(CondVal);
  2529. bool FalseLogicAnd = isa<SelectInst>(FalseVal);
  2530. auto AndFactorization = [&](Value *Common, Value *InnerCond,
  2531. Value *InnerVal,
  2532. bool SelFirst = false) -> Instruction * {
  2533. Value *InnerSel = Builder.CreateSelect(InnerCond, One, InnerVal);
  2534. if (SelFirst)
  2535. std::swap(Common, InnerSel);
  2536. if (FalseLogicAnd || (CondLogicAnd && Common == A))
  2537. return SelectInst::Create(Common, InnerSel, Zero);
  2538. else
  2539. return BinaryOperator::CreateAnd(Common, InnerSel);
  2540. };
  2541. if (A == C)
  2542. return AndFactorization(A, B, D);
  2543. if (A == D)
  2544. return AndFactorization(A, B, C);
  2545. if (B == C)
  2546. return AndFactorization(B, A, D);
  2547. if (B == D)
  2548. return AndFactorization(B, A, C, CondLogicAnd && FalseLogicAnd);
  2549. }
  2550. }
  2551. if (match(FalseVal, m_Zero())) {
  2552. if (impliesPoison(TrueVal, CondVal)) {
  2553. // Change: A = select B, C, false --> A = and B, C
  2554. return BinaryOperator::CreateAnd(CondVal, TrueVal);
  2555. }
  2556. if (auto *LHS = dyn_cast<FCmpInst>(CondVal))
  2557. if (auto *RHS = dyn_cast<FCmpInst>(TrueVal))
  2558. if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true,
  2559. /*IsSelectLogical*/ true))
  2560. return replaceInstUsesWith(SI, V);
  2561. // (A || B) && (C || B) --> (A && C) || B
  2562. if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
  2563. match(TrueVal, m_LogicalOr(m_Value(C), m_Value(D))) &&
  2564. (CondVal->hasOneUse() || TrueVal->hasOneUse())) {
  2565. bool CondLogicOr = isa<SelectInst>(CondVal);
  2566. bool TrueLogicOr = isa<SelectInst>(TrueVal);
  2567. auto OrFactorization = [&](Value *Common, Value *InnerCond,
  2568. Value *InnerVal,
  2569. bool SelFirst = false) -> Instruction * {
  2570. Value *InnerSel = Builder.CreateSelect(InnerCond, InnerVal, Zero);
  2571. if (SelFirst)
  2572. std::swap(Common, InnerSel);
  2573. if (TrueLogicOr || (CondLogicOr && Common == A))
  2574. return SelectInst::Create(Common, One, InnerSel);
  2575. else
  2576. return BinaryOperator::CreateOr(Common, InnerSel);
  2577. };
  2578. if (A == C)
  2579. return OrFactorization(A, B, D);
  2580. if (A == D)
  2581. return OrFactorization(A, B, C);
  2582. if (B == C)
  2583. return OrFactorization(B, A, D);
  2584. if (B == D)
  2585. return OrFactorization(B, A, C, CondLogicOr && TrueLogicOr);
  2586. }
  2587. }
  2588. // We match the "full" 0 or 1 constant here to avoid a potential infinite
  2589. // loop with vectors that may have undefined/poison elements.
  2590. // select a, false, b -> select !a, b, false
  2591. if (match(TrueVal, m_Specific(Zero))) {
  2592. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  2593. return SelectInst::Create(NotCond, FalseVal, Zero);
  2594. }
  2595. // select a, b, true -> select !a, true, b
  2596. if (match(FalseVal, m_Specific(One))) {
  2597. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  2598. return SelectInst::Create(NotCond, One, TrueVal);
  2599. }
  2600. // DeMorgan in select form: !a && !b --> !(a || b)
  2601. // select !a, !b, false --> not (select a, true, b)
  2602. if (match(&SI, m_LogicalAnd(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
  2603. (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
  2604. !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
  2605. return BinaryOperator::CreateNot(Builder.CreateSelect(A, One, B));
  2606. // DeMorgan in select form: !a || !b --> !(a && b)
  2607. // select !a, true, !b --> not (select a, b, false)
  2608. if (match(&SI, m_LogicalOr(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
  2609. (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
  2610. !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
  2611. return BinaryOperator::CreateNot(Builder.CreateSelect(A, B, Zero));
  2612. // select (select a, true, b), true, b -> select a, true, b
  2613. if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
  2614. match(TrueVal, m_One()) && match(FalseVal, m_Specific(B)))
  2615. return replaceOperand(SI, 0, A);
  2616. // select (select a, b, false), b, false -> select a, b, false
  2617. if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) &&
  2618. match(TrueVal, m_Specific(B)) && match(FalseVal, m_Zero()))
  2619. return replaceOperand(SI, 0, A);
  2620. // ~(A & B) & (A | B) --> A ^ B
  2621. if (match(&SI, m_c_LogicalAnd(m_Not(m_LogicalAnd(m_Value(A), m_Value(B))),
  2622. m_c_LogicalOr(m_Deferred(A), m_Deferred(B)))))
  2623. return BinaryOperator::CreateXor(A, B);
  2624. // select (~a | c), a, b -> and a, (or c, freeze(b))
  2625. if (match(CondVal, m_c_Or(m_Not(m_Specific(TrueVal)), m_Value(C))) &&
  2626. CondVal->hasOneUse()) {
  2627. FalseVal = Builder.CreateFreeze(FalseVal);
  2628. return BinaryOperator::CreateAnd(TrueVal, Builder.CreateOr(C, FalseVal));
  2629. }
  2630. // select (~c & b), a, b -> and b, (or freeze(a), c)
  2631. if (match(CondVal, m_c_And(m_Not(m_Value(C)), m_Specific(FalseVal))) &&
  2632. CondVal->hasOneUse()) {
  2633. TrueVal = Builder.CreateFreeze(TrueVal);
  2634. return BinaryOperator::CreateAnd(FalseVal, Builder.CreateOr(C, TrueVal));
  2635. }
  2636. if (match(FalseVal, m_Zero()) || match(TrueVal, m_One())) {
  2637. Use *Y = nullptr;
  2638. bool IsAnd = match(FalseVal, m_Zero()) ? true : false;
  2639. Value *Op1 = IsAnd ? TrueVal : FalseVal;
  2640. if (isCheckForZeroAndMulWithOverflow(CondVal, Op1, IsAnd, Y)) {
  2641. auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
  2642. InsertNewInstBefore(FI, *cast<Instruction>(Y->getUser()));
  2643. replaceUse(*Y, FI);
  2644. return replaceInstUsesWith(SI, Op1);
  2645. }
  2646. if (auto *Op1SI = dyn_cast<SelectInst>(Op1))
  2647. if (auto *I = foldAndOrOfSelectUsingImpliedCond(CondVal, *Op1SI,
  2648. /* IsAnd */ IsAnd))
  2649. return I;
  2650. if (auto *ICmp0 = dyn_cast<ICmpInst>(CondVal))
  2651. if (auto *ICmp1 = dyn_cast<ICmpInst>(Op1))
  2652. if (auto *V = foldAndOrOfICmps(ICmp0, ICmp1, SI, IsAnd,
  2653. /* IsLogical */ true))
  2654. return replaceInstUsesWith(SI, V);
  2655. }
  2656. // select (a || b), c, false -> select a, c, false
  2657. // select c, (a || b), false -> select c, a, false
  2658. // if c implies that b is false.
  2659. if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
  2660. match(FalseVal, m_Zero())) {
  2661. std::optional<bool> Res = isImpliedCondition(TrueVal, B, DL);
  2662. if (Res && *Res == false)
  2663. return replaceOperand(SI, 0, A);
  2664. }
  2665. if (match(TrueVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
  2666. match(FalseVal, m_Zero())) {
  2667. std::optional<bool> Res = isImpliedCondition(CondVal, B, DL);
  2668. if (Res && *Res == false)
  2669. return replaceOperand(SI, 1, A);
  2670. }
  2671. // select c, true, (a && b) -> select c, true, a
  2672. // select (a && b), true, c -> select a, true, c
  2673. // if c = false implies that b = true
  2674. if (match(TrueVal, m_One()) &&
  2675. match(FalseVal, m_LogicalAnd(m_Value(A), m_Value(B)))) {
  2676. std::optional<bool> Res = isImpliedCondition(CondVal, B, DL, false);
  2677. if (Res && *Res == true)
  2678. return replaceOperand(SI, 2, A);
  2679. }
  2680. if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
  2681. match(TrueVal, m_One())) {
  2682. std::optional<bool> Res = isImpliedCondition(FalseVal, B, DL, false);
  2683. if (Res && *Res == true)
  2684. return replaceOperand(SI, 0, A);
  2685. }
  2686. if (match(TrueVal, m_One())) {
  2687. Value *C;
  2688. // (C && A) || (!C && B) --> sel C, A, B
  2689. // (A && C) || (!C && B) --> sel C, A, B
  2690. // (C && A) || (B && !C) --> sel C, A, B
  2691. // (A && C) || (B && !C) --> sel C, A, B (may require freeze)
  2692. if (match(FalseVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(B))) &&
  2693. match(CondVal, m_c_LogicalAnd(m_Specific(C), m_Value(A)))) {
  2694. auto *SelCond = dyn_cast<SelectInst>(CondVal);
  2695. auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
  2696. bool MayNeedFreeze = SelCond && SelFVal &&
  2697. match(SelFVal->getTrueValue(),
  2698. m_Not(m_Specific(SelCond->getTrueValue())));
  2699. if (MayNeedFreeze)
  2700. C = Builder.CreateFreeze(C);
  2701. return SelectInst::Create(C, A, B);
  2702. }
  2703. // (!C && A) || (C && B) --> sel C, B, A
  2704. // (A && !C) || (C && B) --> sel C, B, A
  2705. // (!C && A) || (B && C) --> sel C, B, A
  2706. // (A && !C) || (B && C) --> sel C, B, A (may require freeze)
  2707. if (match(CondVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(A))) &&
  2708. match(FalseVal, m_c_LogicalAnd(m_Specific(C), m_Value(B)))) {
  2709. auto *SelCond = dyn_cast<SelectInst>(CondVal);
  2710. auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
  2711. bool MayNeedFreeze = SelCond && SelFVal &&
  2712. match(SelCond->getTrueValue(),
  2713. m_Not(m_Specific(SelFVal->getTrueValue())));
  2714. if (MayNeedFreeze)
  2715. C = Builder.CreateFreeze(C);
  2716. return SelectInst::Create(C, B, A);
  2717. }
  2718. }
  2719. return nullptr;
  2720. }
  2721. Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
  2722. Value *CondVal = SI.getCondition();
  2723. Value *TrueVal = SI.getTrueValue();
  2724. Value *FalseVal = SI.getFalseValue();
  2725. Type *SelType = SI.getType();
  2726. if (Value *V = simplifySelectInst(CondVal, TrueVal, FalseVal,
  2727. SQ.getWithInstruction(&SI)))
  2728. return replaceInstUsesWith(SI, V);
  2729. if (Instruction *I = canonicalizeSelectToShuffle(SI))
  2730. return I;
  2731. if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
  2732. return I;
  2733. // If the type of select is not an integer type or if the condition and
  2734. // the selection type are not both scalar nor both vector types, there is no
  2735. // point in attempting to match these patterns.
  2736. Type *CondType = CondVal->getType();
  2737. if (!isa<Constant>(CondVal) && SelType->isIntOrIntVectorTy() &&
  2738. CondType->isVectorTy() == SelType->isVectorTy()) {
  2739. if (Value *S = simplifyWithOpReplaced(TrueVal, CondVal,
  2740. ConstantInt::getTrue(CondType), SQ,
  2741. /* AllowRefinement */ true))
  2742. return replaceOperand(SI, 1, S);
  2743. if (Value *S = simplifyWithOpReplaced(FalseVal, CondVal,
  2744. ConstantInt::getFalse(CondType), SQ,
  2745. /* AllowRefinement */ true))
  2746. return replaceOperand(SI, 2, S);
  2747. // Handle patterns involving sext/zext + not explicitly,
  2748. // as simplifyWithOpReplaced() only looks past one instruction.
  2749. Value *NotCond;
  2750. // select a, sext(!a), b -> select !a, b, 0
  2751. // select a, zext(!a), b -> select !a, b, 0
  2752. if (match(TrueVal, m_ZExtOrSExt(m_CombineAnd(m_Value(NotCond),
  2753. m_Not(m_Specific(CondVal))))))
  2754. return SelectInst::Create(NotCond, FalseVal,
  2755. Constant::getNullValue(SelType));
  2756. // select a, b, zext(!a) -> select !a, 1, b
  2757. if (match(FalseVal, m_ZExt(m_CombineAnd(m_Value(NotCond),
  2758. m_Not(m_Specific(CondVal))))))
  2759. return SelectInst::Create(NotCond, ConstantInt::get(SelType, 1), TrueVal);
  2760. // select a, b, sext(!a) -> select !a, -1, b
  2761. if (match(FalseVal, m_SExt(m_CombineAnd(m_Value(NotCond),
  2762. m_Not(m_Specific(CondVal))))))
  2763. return SelectInst::Create(NotCond, Constant::getAllOnesValue(SelType),
  2764. TrueVal);
  2765. }
  2766. if (Instruction *R = foldSelectOfBools(SI))
  2767. return R;
  2768. // Selecting between two integer or vector splat integer constants?
  2769. //
  2770. // Note that we don't handle a scalar select of vectors:
  2771. // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
  2772. // because that may need 3 instructions to splat the condition value:
  2773. // extend, insertelement, shufflevector.
  2774. //
  2775. // Do not handle i1 TrueVal and FalseVal otherwise would result in
  2776. // zext/sext i1 to i1.
  2777. if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(1) &&
  2778. CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
  2779. // select C, 1, 0 -> zext C to int
  2780. if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
  2781. return new ZExtInst(CondVal, SelType);
  2782. // select C, -1, 0 -> sext C to int
  2783. if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
  2784. return new SExtInst(CondVal, SelType);
  2785. // select C, 0, 1 -> zext !C to int
  2786. if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
  2787. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  2788. return new ZExtInst(NotCond, SelType);
  2789. }
  2790. // select C, 0, -1 -> sext !C to int
  2791. if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
  2792. Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
  2793. return new SExtInst(NotCond, SelType);
  2794. }
  2795. }
  2796. if (auto *FCmp = dyn_cast<FCmpInst>(CondVal)) {
  2797. Value *Cmp0 = FCmp->getOperand(0), *Cmp1 = FCmp->getOperand(1);
  2798. // Are we selecting a value based on a comparison of the two values?
  2799. if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
  2800. (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
  2801. // Canonicalize to use ordered comparisons by swapping the select
  2802. // operands.
  2803. //
  2804. // e.g.
  2805. // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
  2806. if (FCmp->hasOneUse() && FCmpInst::isUnordered(FCmp->getPredicate())) {
  2807. FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
  2808. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  2809. // FIXME: The FMF should propagate from the select, not the fcmp.
  2810. Builder.setFastMathFlags(FCmp->getFastMathFlags());
  2811. Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
  2812. FCmp->getName() + ".inv");
  2813. Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
  2814. return replaceInstUsesWith(SI, NewSel);
  2815. }
  2816. }
  2817. }
  2818. if (isa<FPMathOperator>(SI)) {
  2819. // TODO: Try to forward-propagate FMF from select arms to the select.
  2820. // Canonicalize select of FP values where NaN and -0.0 are not valid as
  2821. // minnum/maxnum intrinsics.
  2822. if (SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
  2823. Value *X, *Y;
  2824. if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
  2825. return replaceInstUsesWith(
  2826. SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
  2827. if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
  2828. return replaceInstUsesWith(
  2829. SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
  2830. }
  2831. }
  2832. // Fold selecting to fabs.
  2833. if (Instruction *Fabs = foldSelectWithFCmpToFabs(SI, *this))
  2834. return Fabs;
  2835. // See if we are selecting two values based on a comparison of the two values.
  2836. if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
  2837. if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
  2838. return Result;
  2839. if (Instruction *Add = foldAddSubSelect(SI, Builder))
  2840. return Add;
  2841. if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
  2842. return Add;
  2843. if (Instruction *Or = foldSetClearBits(SI, Builder))
  2844. return Or;
  2845. if (Instruction *Mul = foldSelectZeroOrMul(SI, *this))
  2846. return Mul;
  2847. // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
  2848. auto *TI = dyn_cast<Instruction>(TrueVal);
  2849. auto *FI = dyn_cast<Instruction>(FalseVal);
  2850. if (TI && FI && TI->getOpcode() == FI->getOpcode())
  2851. if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
  2852. return IV;
  2853. if (Instruction *I = foldSelectExtConst(SI))
  2854. return I;
  2855. // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
  2856. // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
  2857. auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
  2858. bool Swap) -> GetElementPtrInst * {
  2859. Value *Ptr = Gep->getPointerOperand();
  2860. if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
  2861. !Gep->hasOneUse())
  2862. return nullptr;
  2863. Value *Idx = Gep->getOperand(1);
  2864. if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType()))
  2865. return nullptr;
  2866. Type *ElementType = Gep->getResultElementType();
  2867. Value *NewT = Idx;
  2868. Value *NewF = Constant::getNullValue(Idx->getType());
  2869. if (Swap)
  2870. std::swap(NewT, NewF);
  2871. Value *NewSI =
  2872. Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
  2873. return GetElementPtrInst::Create(ElementType, Ptr, {NewSI});
  2874. };
  2875. if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
  2876. if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
  2877. return NewGep;
  2878. if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
  2879. if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
  2880. return NewGep;
  2881. // See if we can fold the select into one of our operands.
  2882. if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
  2883. if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
  2884. return FoldI;
  2885. Value *LHS, *RHS;
  2886. Instruction::CastOps CastOp;
  2887. SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
  2888. auto SPF = SPR.Flavor;
  2889. if (SPF) {
  2890. Value *LHS2, *RHS2;
  2891. if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
  2892. if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
  2893. RHS2, SI, SPF, RHS))
  2894. return R;
  2895. if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
  2896. if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
  2897. RHS2, SI, SPF, LHS))
  2898. return R;
  2899. }
  2900. if (SelectPatternResult::isMinOrMax(SPF)) {
  2901. // Canonicalize so that
  2902. // - type casts are outside select patterns.
  2903. // - float clamp is transformed to min/max pattern
  2904. bool IsCastNeeded = LHS->getType() != SelType;
  2905. Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
  2906. Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
  2907. if (IsCastNeeded ||
  2908. (LHS->getType()->isFPOrFPVectorTy() &&
  2909. ((CmpLHS != LHS && CmpLHS != RHS) ||
  2910. (CmpRHS != LHS && CmpRHS != RHS)))) {
  2911. CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
  2912. Value *Cmp;
  2913. if (CmpInst::isIntPredicate(MinMaxPred)) {
  2914. Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
  2915. } else {
  2916. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  2917. auto FMF =
  2918. cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
  2919. Builder.setFastMathFlags(FMF);
  2920. Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
  2921. }
  2922. Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
  2923. if (!IsCastNeeded)
  2924. return replaceInstUsesWith(SI, NewSI);
  2925. Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
  2926. return replaceInstUsesWith(SI, NewCast);
  2927. }
  2928. }
  2929. }
  2930. // See if we can fold the select into a phi node if the condition is a select.
  2931. if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
  2932. // The true/false values have to be live in the PHI predecessor's blocks.
  2933. if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
  2934. canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
  2935. if (Instruction *NV = foldOpIntoPhi(SI, PN))
  2936. return NV;
  2937. if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
  2938. if (TrueSI->getCondition()->getType() == CondVal->getType()) {
  2939. // select(C, select(C, a, b), c) -> select(C, a, c)
  2940. if (TrueSI->getCondition() == CondVal) {
  2941. if (SI.getTrueValue() == TrueSI->getTrueValue())
  2942. return nullptr;
  2943. return replaceOperand(SI, 1, TrueSI->getTrueValue());
  2944. }
  2945. // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
  2946. // We choose this as normal form to enable folding on the And and
  2947. // shortening paths for the values (this helps getUnderlyingObjects() for
  2948. // example).
  2949. if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
  2950. Value *And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition());
  2951. replaceOperand(SI, 0, And);
  2952. replaceOperand(SI, 1, TrueSI->getTrueValue());
  2953. return &SI;
  2954. }
  2955. }
  2956. }
  2957. if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
  2958. if (FalseSI->getCondition()->getType() == CondVal->getType()) {
  2959. // select(C, a, select(C, b, c)) -> select(C, a, c)
  2960. if (FalseSI->getCondition() == CondVal) {
  2961. if (SI.getFalseValue() == FalseSI->getFalseValue())
  2962. return nullptr;
  2963. return replaceOperand(SI, 2, FalseSI->getFalseValue());
  2964. }
  2965. // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
  2966. if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
  2967. Value *Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition());
  2968. replaceOperand(SI, 0, Or);
  2969. replaceOperand(SI, 2, FalseSI->getFalseValue());
  2970. return &SI;
  2971. }
  2972. }
  2973. }
  2974. auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
  2975. // The select might be preventing a division by 0.
  2976. switch (BO->getOpcode()) {
  2977. default:
  2978. return true;
  2979. case Instruction::SRem:
  2980. case Instruction::URem:
  2981. case Instruction::SDiv:
  2982. case Instruction::UDiv:
  2983. return false;
  2984. }
  2985. };
  2986. // Try to simplify a binop sandwiched between 2 selects with the same
  2987. // condition.
  2988. // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
  2989. BinaryOperator *TrueBO;
  2990. if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
  2991. canMergeSelectThroughBinop(TrueBO)) {
  2992. if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
  2993. if (TrueBOSI->getCondition() == CondVal) {
  2994. replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
  2995. Worklist.push(TrueBO);
  2996. return &SI;
  2997. }
  2998. }
  2999. if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
  3000. if (TrueBOSI->getCondition() == CondVal) {
  3001. replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
  3002. Worklist.push(TrueBO);
  3003. return &SI;
  3004. }
  3005. }
  3006. }
  3007. // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
  3008. BinaryOperator *FalseBO;
  3009. if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
  3010. canMergeSelectThroughBinop(FalseBO)) {
  3011. if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
  3012. if (FalseBOSI->getCondition() == CondVal) {
  3013. replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
  3014. Worklist.push(FalseBO);
  3015. return &SI;
  3016. }
  3017. }
  3018. if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
  3019. if (FalseBOSI->getCondition() == CondVal) {
  3020. replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
  3021. Worklist.push(FalseBO);
  3022. return &SI;
  3023. }
  3024. }
  3025. }
  3026. Value *NotCond;
  3027. if (match(CondVal, m_Not(m_Value(NotCond))) &&
  3028. !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
  3029. replaceOperand(SI, 0, NotCond);
  3030. SI.swapValues();
  3031. SI.swapProfMetadata();
  3032. return &SI;
  3033. }
  3034. if (Instruction *I = foldVectorSelect(SI))
  3035. return I;
  3036. // If we can compute the condition, there's no need for a select.
  3037. // Like the above fold, we are attempting to reduce compile-time cost by
  3038. // putting this fold here with limitations rather than in InstSimplify.
  3039. // The motivation for this call into value tracking is to take advantage of
  3040. // the assumption cache, so make sure that is populated.
  3041. if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
  3042. KnownBits Known(1);
  3043. computeKnownBits(CondVal, Known, 0, &SI);
  3044. if (Known.One.isOne())
  3045. return replaceInstUsesWith(SI, TrueVal);
  3046. if (Known.Zero.isOne())
  3047. return replaceInstUsesWith(SI, FalseVal);
  3048. }
  3049. if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
  3050. return BitCastSel;
  3051. // Simplify selects that test the returned flag of cmpxchg instructions.
  3052. if (Value *V = foldSelectCmpXchg(SI))
  3053. return replaceInstUsesWith(SI, V);
  3054. if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
  3055. return Select;
  3056. if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
  3057. return Funnel;
  3058. if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
  3059. return Copysign;
  3060. if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
  3061. return replaceInstUsesWith(SI, PN);
  3062. if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder))
  3063. return replaceInstUsesWith(SI, Fr);
  3064. if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
  3065. return replaceInstUsesWith(SI, V);
  3066. // select(mask, mload(,,mask,0), 0) -> mload(,,mask,0)
  3067. // Load inst is intentionally not checked for hasOneUse()
  3068. if (match(FalseVal, m_Zero()) &&
  3069. (match(TrueVal, m_MaskedLoad(m_Value(), m_Value(), m_Specific(CondVal),
  3070. m_CombineOr(m_Undef(), m_Zero()))) ||
  3071. match(TrueVal, m_MaskedGather(m_Value(), m_Value(), m_Specific(CondVal),
  3072. m_CombineOr(m_Undef(), m_Zero()))))) {
  3073. auto *MaskedInst = cast<IntrinsicInst>(TrueVal);
  3074. if (isa<UndefValue>(MaskedInst->getArgOperand(3)))
  3075. MaskedInst->setArgOperand(3, FalseVal /* Zero */);
  3076. return replaceInstUsesWith(SI, MaskedInst);
  3077. }
  3078. Value *Mask;
  3079. if (match(TrueVal, m_Zero()) &&
  3080. (match(FalseVal, m_MaskedLoad(m_Value(), m_Value(), m_Value(Mask),
  3081. m_CombineOr(m_Undef(), m_Zero()))) ||
  3082. match(FalseVal, m_MaskedGather(m_Value(), m_Value(), m_Value(Mask),
  3083. m_CombineOr(m_Undef(), m_Zero())))) &&
  3084. (CondVal->getType() == Mask->getType())) {
  3085. // We can remove the select by ensuring the load zeros all lanes the
  3086. // select would have. We determine this by proving there is no overlap
  3087. // between the load and select masks.
  3088. // (i.e (load_mask & select_mask) == 0 == no overlap)
  3089. bool CanMergeSelectIntoLoad = false;
  3090. if (Value *V = simplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI)))
  3091. CanMergeSelectIntoLoad = match(V, m_Zero());
  3092. if (CanMergeSelectIntoLoad) {
  3093. auto *MaskedInst = cast<IntrinsicInst>(FalseVal);
  3094. if (isa<UndefValue>(MaskedInst->getArgOperand(3)))
  3095. MaskedInst->setArgOperand(3, TrueVal /* Zero */);
  3096. return replaceInstUsesWith(SI, MaskedInst);
  3097. }
  3098. }
  3099. if (Instruction *I = foldNestedSelects(SI, Builder))
  3100. return I;
  3101. // Match logical variants of the pattern,
  3102. // and transform them iff that gets rid of inversions.
  3103. // (~x) | y --> ~(x & (~y))
  3104. // (~x) & y --> ~(x | (~y))
  3105. if (sinkNotIntoOtherHandOfLogicalOp(SI))
  3106. return &SI;
  3107. return nullptr;
  3108. }