blob: 24a82ba9ae40049de5fe15b691ddaa2e9494ac7c [file] [log] [blame]
Chris Lattner0a8191e2010-01-05 07:50:36 +00001//===- InstCombineAndOrXor.cpp --------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitAnd, visitOr, and visitXor functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Craig Topper0aa3a192017-08-14 21:39:51 +000015#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000016#include "llvm/Analysis/InstructionSimplify.h"
David Blaikie31b98d22018-06-04 21:23:21 +000017#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000018#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000020#include "llvm/IR/PatternMatch.h"
Chris Lattner0a8191e2010-01-05 07:50:36 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjay Patel18549272015-09-08 18:24:36 +000026/// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
Tim Shenaec68b22016-06-29 20:10:17 +000027/// a four bit mask.
28static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
32 // U L G E
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
49 return CC;
Chris Lattner0a8191e2010-01-05 07:50:36 +000050}
51
Sanjay Patel18549272015-09-08 18:24:36 +000052/// This is the complement of getICmpCode, which turns an opcode and two
53/// operands into either a constant true or false, or a brand new ICmp
54/// instruction. The sign is passed in to determine which kind of predicate to
55/// use in the new icmp instruction.
Sanjay Patel3d5bb152018-12-04 18:53:27 +000056static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000057 InstCombiner::BuilderTy &Builder) {
Pete Cooperebf98c12011-12-17 01:20:32 +000058 ICmpInst::Predicate NewPred;
Sanjay Patel3d5bb152018-12-04 18:53:27 +000059 if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
60 return TorF;
Craig Topperbb4069e2017-07-07 23:16:26 +000061 return Builder.CreateICmp(NewPred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000062}
63
Sanjay Patel18549272015-09-08 18:24:36 +000064/// This is the complement of getFCmpCode, which turns an opcode and two
Tim Shenaec68b22016-06-29 20:10:17 +000065/// operands into either a FCmp instruction, or a true/false constant.
66static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
Craig Topperbb4069e2017-07-07 23:16:26 +000067 InstCombiner::BuilderTy &Builder) {
Tim Shenaec68b22016-06-29 20:10:17 +000068 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
Craig Topperbb4069e2017-07-07 23:16:26 +000075 return Builder.CreateFCmp(Pred, LHS, RHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +000076}
77
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000078/// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
Craig Topperfc42ace2017-07-06 16:24:22 +000079/// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000080/// \param I Binary operator to transform.
81/// \return Pointer to node that must replace the original binary operator, or
82/// null pointer if no transformation was made.
Craig Topper95e41422017-07-06 16:24:23 +000083static Value *SimplifyBSwap(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +000084 InstCombiner::BuilderTy &Builder) {
Craig Topperc6948c22017-07-03 05:54:11 +000085 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
86
Craig Topper22795de2017-07-06 16:24:21 +000087 Value *OldLHS = I.getOperand(0);
88 Value *OldRHS = I.getOperand(1);
Craig Topper80369702017-07-03 05:54:16 +000089
Craig Topper766ce6e2017-07-03 05:54:15 +000090 Value *NewLHS;
Craig Topper22795de2017-07-06 16:24:21 +000091 if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +000092 return nullptr;
93
Craig Topper766ce6e2017-07-03 05:54:15 +000094 Value *NewRHS;
95 const APInt *C;
96
Craig Topper22795de2017-07-06 16:24:21 +000097 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
Craig Topper766ce6e2017-07-03 05:54:15 +000098 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
Craig Topper22795de2017-07-06 16:24:21 +000099 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
100 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000101 // NewRHS initialized by the matcher.
Craig Topper22795de2017-07-06 16:24:21 +0000102 } else if (match(OldRHS, m_APInt(C))) {
Craig Topper766ce6e2017-07-03 05:54:15 +0000103 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
Craig Topper22795de2017-07-06 16:24:21 +0000104 if (!OldLHS->hasOneUse())
105 return nullptr;
Craig Topper766ce6e2017-07-03 05:54:15 +0000106 NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
107 } else
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000108 return nullptr;
109
Craig Topperbb4069e2017-07-07 23:16:26 +0000110 Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Craig Topper1e4643a2017-07-03 05:54:13 +0000111 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
112 I.getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000113 return Builder.CreateCall(F, BinOp);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000114}
115
Sanjay Patel18549272015-09-08 18:24:36 +0000116/// This handles expressions of the form ((val OP C1) & C2). Where
Craig Topper70e4f432017-04-02 17:57:30 +0000117/// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
118Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
Chris Lattner0a8191e2010-01-05 07:50:36 +0000119 ConstantInt *OpRHS,
120 ConstantInt *AndRHS,
121 BinaryOperator &TheAnd) {
122 Value *X = Op->getOperand(0);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000123
124 switch (Op->getOpcode()) {
Craig Topper70e4f432017-04-02 17:57:30 +0000125 default: break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000126 case Instruction::Add:
127 if (Op->hasOneUse()) {
128 // Adding a one to a single bit bit-field should be turned into an XOR
129 // of the bit. First thing to check is to see if this AND is with a
130 // single bit constant.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000131 const APInt &AndRHSV = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000132
133 // If there is only one bit set.
134 if (AndRHSV.isPowerOf2()) {
135 // Ok, at this point, we know that we are masking the result of the
136 // ADD down to exactly one bit. If the constant we are adding has
137 // no bits set below this bit, then we can eliminate the ADD.
Jakub Staszak9de494e2013-06-06 00:49:57 +0000138 const APInt& AddRHS = OpRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000139
140 // Check to see if any bits below the one bit set in AndRHSV are set.
Craig Topper73ba1c82017-06-07 07:40:37 +0000141 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000142 // If not, the only thing that can effect the output of the AND is
143 // the bit specified by AndRHSV. If that bit is set, the effect of
144 // the XOR is to toggle the bit. If it is clear, then the ADD has
145 // no effect.
Craig Topper73ba1c82017-06-07 07:40:37 +0000146 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
Chris Lattner0a8191e2010-01-05 07:50:36 +0000147 TheAnd.setOperand(0, X);
148 return &TheAnd;
149 } else {
150 // Pull the XOR out of the AND.
Craig Topperbb4069e2017-07-07 23:16:26 +0000151 Value *NewAnd = Builder.CreateAnd(X, AndRHS);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000152 NewAnd->takeName(Op);
153 return BinaryOperator::CreateXor(NewAnd, AndRHS);
154 }
155 }
156 }
157 }
158 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000159 }
Craig Topperf40110f2014-04-25 05:29:35 +0000160 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000161}
162
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000163/// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000164/// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
165/// whether to treat V, Lo, and Hi as signed or not.
Sanjay Patel85d79742016-08-31 19:49:56 +0000166Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
Chris Lattner067459c2010-03-05 08:46:26 +0000167 bool isSigned, bool Inside) {
Sanjay Patel85d79742016-08-31 19:49:56 +0000168 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
Chris Lattner0a8191e2010-01-05 07:50:36 +0000169 "Lo is not <= Hi in range emission code!");
Craig Topper9d4171a2012-12-20 07:09:41 +0000170
Sanjay Patel85d79742016-08-31 19:49:56 +0000171 Type *Ty = V->getType();
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000172 if (Lo == Hi)
Sanjay Patel85d79742016-08-31 19:49:56 +0000173 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000174
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000175 // V >= Min && V < Hi --> V < Hi
176 // V < Min || V >= Hi --> V >= Hi
177 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Sanjay Patel85d79742016-08-31 19:49:56 +0000178 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000179 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
Craig Topperbb4069e2017-07-07 23:16:26 +0000180 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000181 }
182
Sanjay Patel7d9ebaf2016-08-31 00:19:35 +0000183 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
184 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
Sanjay Patel85d79742016-08-31 19:49:56 +0000185 Value *VMinusLo =
Craig Topperbb4069e2017-07-07 23:16:26 +0000186 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
Sanjay Patel85d79742016-08-31 19:49:56 +0000187 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
Craig Topperbb4069e2017-07-07 23:16:26 +0000188 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000189}
190
Sanjay Patel77bf6222017-04-03 16:53:12 +0000191/// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
192/// that can be simplified.
193/// One of A and B is considered the mask. The other is the value. This is
194/// described as the "AMask" or "BMask" part of the enum. If the enum contains
195/// only "Mask", then both A and B can be considered masks. If A is the mask,
196/// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
197/// If both A and C are constants, this proof is also easy.
198/// For the following explanations, we assume that A is the mask.
199///
200/// "AllOnes" declares that the comparison is true only if (A & B) == A or all
201/// bits of A are set in B.
202/// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
203///
204/// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
205/// bits of A are cleared in B.
206/// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
207///
208/// "Mixed" declares that (A & B) == C and C might or might not contain any
209/// number of one bits and zero bits.
210/// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
211///
212/// "Not" means that in above descriptions "==" should be replaced by "!=".
213/// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
214///
Owen Anderson3fe002d2010-09-08 22:16:17 +0000215/// If the mask A contains a single bit, then the following is equivalent:
216/// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
217/// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
218enum MaskedICmpType {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000219 AMask_AllOnes = 1,
220 AMask_NotAllOnes = 2,
221 BMask_AllOnes = 4,
222 BMask_NotAllOnes = 8,
223 Mask_AllZeros = 16,
224 Mask_NotAllZeros = 32,
225 AMask_Mixed = 64,
226 AMask_NotMixed = 128,
227 BMask_Mixed = 256,
228 BMask_NotMixed = 512
Owen Anderson3fe002d2010-09-08 22:16:17 +0000229};
230
Sanjay Patel77bf6222017-04-03 16:53:12 +0000231/// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
232/// satisfies.
233static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
234 ICmpInst::Predicate Pred) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000235 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
236 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
237 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000238 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
239 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
240 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
241 unsigned MaskVal = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000242 if (CCst && CCst->isZero()) {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000243 // if C is zero, then both A and B qualify as mask
Sanjay Patel77bf6222017-04-03 16:53:12 +0000244 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
245 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
246 if (IsAPow2)
247 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
248 : (AMask_AllOnes | AMask_Mixed));
249 if (IsBPow2)
250 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
251 : (BMask_AllOnes | BMask_Mixed));
252 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000253 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000254
Owen Anderson3fe002d2010-09-08 22:16:17 +0000255 if (A == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000256 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
257 : (AMask_NotAllOnes | AMask_NotMixed));
258 if (IsAPow2)
259 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
260 : (Mask_AllZeros | AMask_Mixed));
261 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
262 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000263 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000264
Craig Topperae48cb22012-12-20 07:15:54 +0000265 if (B == C) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000266 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
267 : (BMask_NotAllOnes | BMask_NotMixed));
268 if (IsBPow2)
269 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
270 : (Mask_AllZeros | BMask_Mixed));
271 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
272 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000273 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000274
275 return MaskVal;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000276}
277
Tim Northoverc0756c42013-09-04 11:57:13 +0000278/// Convert an analysis of a masked ICmp into its equivalent if all boolean
279/// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
280/// is adjacent to the corresponding normal flag (recording ==), this just
281/// involves swapping those bits over.
282static unsigned conjugateICmpMask(unsigned Mask) {
283 unsigned NewMask;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000284 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
285 AMask_Mixed | BMask_Mixed))
Tim Northoverc0756c42013-09-04 11:57:13 +0000286 << 1;
287
Sanjay Patel77bf6222017-04-03 16:53:12 +0000288 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
289 AMask_NotMixed | BMask_NotMixed))
290 >> 1;
Tim Northoverc0756c42013-09-04 11:57:13 +0000291
292 return NewMask;
293}
294
Craig Topper0aa3a192017-08-14 21:39:51 +0000295// Adapts the external decomposeBitTestICmp for local use.
296static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
297 Value *&X, Value *&Y, Value *&Z) {
298 APInt Mask;
299 if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
300 return false;
301
Craig Topper085c1f42017-09-01 21:27:29 +0000302 Y = ConstantInt::get(X->getType(), Mask);
303 Z = ConstantInt::get(X->getType(), 0);
Craig Topper0aa3a192017-08-14 21:39:51 +0000304 return true;
305}
306
Sanjay Patel77bf6222017-04-03 16:53:12 +0000307/// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000308/// Return the pattern classes (from MaskedICmpType) for the left hand side and
309/// the right hand side as a pair.
310/// LHS and RHS are the left hand side and the right hand side ICmps and PredL
311/// and PredR are their predicates, respectively.
312static
313Optional<std::pair<unsigned, unsigned>>
314getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
315 Value *&D, Value *&E, ICmpInst *LHS,
316 ICmpInst *RHS,
317 ICmpInst::Predicate &PredL,
318 ICmpInst::Predicate &PredR) {
Craig Topper775ffcc2017-08-21 21:00:45 +0000319 // vectors are not (yet?) supported. Don't support pointers either.
Craig Topperd3b46562017-09-01 21:27:31 +0000320 if (!LHS->getOperand(0)->getType()->isIntegerTy() ||
321 !RHS->getOperand(0)->getType()->isIntegerTy())
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000322 return None;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000323
324 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000325 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000326 // and L11 & L12 == L21 & L22. The same goes for RHS.
327 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000328 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000329 // above.
330 Value *L1 = LHS->getOperand(0);
331 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000332 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000333 // Check whether the icmp can be decomposed into a bit test.
Craig Topper0aa3a192017-08-14 21:39:51 +0000334 if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000335 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000336 } else {
337 // Look for ANDs in the LHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000338 if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000339 // Any icmp can be viewed as being trivially masked; if it allows us to
340 // remove one, it's worth it.
341 L11 = L1;
342 L12 = Constant::getAllOnesValue(L1->getType());
343 }
344
Craig Topper775ffcc2017-08-21 21:00:45 +0000345 if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000346 L21 = L2;
347 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000348 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000349 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000350
351 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000352 if (!ICmpInst::isEquality(PredL))
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000353 return None;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000354
355 Value *R1 = RHS->getOperand(0);
356 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000357 Value *R11, *R12;
358 bool Ok = false;
Craig Topper0aa3a192017-08-14 21:39:51 +0000359 if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000360 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000361 A = R11;
362 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000363 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000364 A = R12;
365 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000366 } else {
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000367 return None;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000368 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000369 E = R2;
370 R1 = nullptr;
371 Ok = true;
Craig Topper775ffcc2017-08-21 21:00:45 +0000372 } else {
Tim Northoverdc647a22013-09-04 11:57:17 +0000373 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
374 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000375 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000376 R11 = R1;
377 R12 = Constant::getAllOnesValue(R1->getType());
378 }
379
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000380 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000381 A = R11;
382 D = R12;
383 E = R2;
384 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000385 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000386 A = R12;
387 D = R11;
388 E = R2;
389 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000390 }
391 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000392
393 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000394 if (!ICmpInst::isEquality(PredR))
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000395 return None;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000396
Chad Rosier58919cc2016-05-09 21:37:43 +0000397 // Look for ANDs on the right side of the RHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000398 if (!Ok) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000399 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
400 R11 = R2;
401 R12 = Constant::getAllOnesValue(R2->getType());
402 }
403
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000404 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000405 A = R11;
406 D = R12;
407 E = R1;
408 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000409 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000410 A = R12;
411 D = R11;
412 E = R1;
413 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000414 } else {
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000415 return None;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000416 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000417 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000418 if (!Ok)
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000419 return None;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000420
421 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000422 B = L12;
423 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000424 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000425 B = L11;
426 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000427 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000428 B = L22;
429 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000430 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 B = L21;
432 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000433 }
434
Sanjay Patel77bf6222017-04-03 16:53:12 +0000435 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
436 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000437 return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
438}
439
440/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
441/// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
442/// and the right hand side is of type BMask_Mixed. For example,
443/// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
444static Value * foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
445 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
446 Value *A, Value *B, Value *C, Value *D, Value *E,
447 ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
448 llvm::InstCombiner::BuilderTy &Builder) {
449 // We are given the canonical form:
450 // (icmp ne (A & B), 0) & (icmp eq (A & D), E).
451 // where D & E == E.
452 //
453 // If IsAnd is false, we get it in negated form:
454 // (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
455 // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
456 //
457 // We currently handle the case of B, C, D, E are constant.
458 //
459 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
460 if (!BCst)
461 return nullptr;
462 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
463 if (!CCst)
464 return nullptr;
465 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
466 if (!DCst)
467 return nullptr;
468 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
469 if (!ECst)
470 return nullptr;
471
472 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
473
474 // Update E to the canonical form when D is a power of two and RHS is
475 // canonicalized as,
476 // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
477 // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
478 if (PredR != NewCC)
479 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
480
481 // If B or D is zero, skip because if LHS or RHS can be trivially folded by
482 // other folding rules and this pattern won't apply any more.
483 if (BCst->getValue() == 0 || DCst->getValue() == 0)
484 return nullptr;
485
486 // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
487 // deduce anything from it.
488 // For example,
489 // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
490 if ((BCst->getValue() & DCst->getValue()) == 0)
491 return nullptr;
492
493 // If the following two conditions are met:
494 //
495 // 1. mask B covers only a single bit that's not covered by mask D, that is,
496 // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
497 // B and D has only one bit set) and,
498 //
499 // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
500 // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
501 //
502 // then that single bit in B must be one and thus the whole expression can be
503 // folded to
504 // (A & (B | D)) == (B & (B ^ D)) | E.
505 //
506 // For example,
507 // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
508 // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
509 if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) &&
510 (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) {
511 APInt BorD = BCst->getValue() | DCst->getValue();
512 APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) |
513 ECst->getValue();
514 Value *NewMask = ConstantInt::get(BCst->getType(), BorD);
515 Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE);
516 Value *NewAnd = Builder.CreateAnd(A, NewMask);
517 return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
518 }
519
520 auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
521 return (C1->getValue() & C2->getValue()) == C1->getValue();
522 };
523 auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
524 return (C1->getValue() & C2->getValue()) == C2->getValue();
525 };
526
527 // In the following, we consider only the cases where B is a superset of D, B
528 // is a subset of D, or B == D because otherwise there's at least one bit
529 // covered by B but not D, in which case we can't deduce much from it, so
530 // no folding (aside from the single must-be-one bit case right above.)
531 // For example,
532 // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
533 if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
534 return nullptr;
535
536 // At this point, either B is a superset of D, B is a subset of D or B == D.
537
538 // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
539 // and the whole expression becomes false (or true if negated), otherwise, no
540 // folding.
541 // For example,
542 // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
543 // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
544 if (ECst->isZero()) {
545 if (IsSubSetOrEqual(BCst, DCst))
546 return ConstantInt::get(LHS->getType(), !IsAnd);
547 return nullptr;
548 }
549
550 // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
551 // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
552 // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
553 // RHS. For example,
554 // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
555 // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
556 if (IsSuperSetOrEqual(BCst, DCst))
557 return RHS;
558 // Otherwise, B is a subset of D. If B and E have a common bit set,
559 // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
560 // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
561 assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
562 if ((BCst->getValue() & ECst->getValue()) != 0)
563 return RHS;
564 // Otherwise, LHS and RHS contradict and the whole expression becomes false
565 // (or true if negated.) For example,
566 // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
567 // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
568 return ConstantInt::get(LHS->getType(), !IsAnd);
569}
570
571/// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
572/// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
573/// aren't of the common mask pattern type.
574static Value *foldLogOpOfMaskedICmpsAsymmetric(
575 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
576 Value *A, Value *B, Value *C, Value *D, Value *E,
577 ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
578 unsigned LHSMask, unsigned RHSMask,
579 llvm::InstCombiner::BuilderTy &Builder) {
580 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
581 "Expected equality predicates for masked type of icmps.");
582 // Handle Mask_NotAllZeros-BMask_Mixed cases.
583 // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
584 // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
585 // which gets swapped to
586 // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
587 if (!IsAnd) {
588 LHSMask = conjugateICmpMask(LHSMask);
589 RHSMask = conjugateICmpMask(RHSMask);
590 }
591 if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
592 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
593 LHS, RHS, IsAnd, A, B, C, D, E,
594 PredL, PredR, Builder)) {
595 return V;
596 }
597 } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
598 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
599 RHS, LHS, IsAnd, A, D, E, B, C,
600 PredR, PredL, Builder)) {
601 return V;
602 }
603 }
604 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000605}
Sanjay Patel18549272015-09-08 18:24:36 +0000606
607/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
608/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000609static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000610 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000611 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000612 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000613 Optional<std::pair<unsigned, unsigned>> MaskPair =
Sanjay Patel77bf6222017-04-03 16:53:12 +0000614 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000615 if (!MaskPair)
Sanjay Patel77bf6222017-04-03 16:53:12 +0000616 return nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000617 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
618 "Expected equality predicates for masked type of icmps.");
Hiroshi Yamauchie6a3dc72018-03-13 21:13:18 +0000619 unsigned LHSMask = MaskPair->first;
620 unsigned RHSMask = MaskPair->second;
621 unsigned Mask = LHSMask & RHSMask;
622 if (Mask == 0) {
623 // Even if the two sides don't share a common pattern, check if folding can
624 // still happen.
625 if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
626 LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
627 Builder))
628 return V;
629 return nullptr;
630 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000631
Tim Northoverc0756c42013-09-04 11:57:13 +0000632 // In full generality:
633 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
634 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
635 //
636 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
637 // equivalent to (icmp (A & X) !Op Y).
638 //
639 // Therefore, we can pretend for the rest of this function that we're dealing
640 // with the conjunction, provided we flip the sense of any comparisons (both
641 // input and output).
642
643 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000644 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000645 if (!IsAnd) {
646 // Convert the masking analysis into its equivalent with negated
647 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000648 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000649 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000650
Sanjay Patel77bf6222017-04-03 16:53:12 +0000651 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000652 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000653 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000654 Value *NewOr = Builder.CreateOr(B, D);
655 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000656 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000657 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000658 // with B and D, having a single bit set.
659 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000660 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000661 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000662 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000663 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000664 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000665 Value *NewOr = Builder.CreateOr(B, D);
666 Value *NewAnd = Builder.CreateAnd(A, NewOr);
667 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000668 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000669 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000670 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000671 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000672 Value *NewAnd1 = Builder.CreateAnd(B, D);
673 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
674 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000675 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000676
677 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000678 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000679 // easy cases for now" decision.
680 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000681 if (!BCst)
682 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000683 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000684 if (!DCst)
685 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000686
Sanjay Patel77bf6222017-04-03 16:53:12 +0000687 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000688 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
689 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
690 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
691 // Only valid if one of the masks is a superset of the other (check "B&D" is
692 // the same as either B or D).
693 APInt NewMask = BCst->getValue() & DCst->getValue();
694
695 if (NewMask == BCst->getValue())
696 return LHS;
697 else if (NewMask == DCst->getValue())
698 return RHS;
699 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000700
701 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000702 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
703 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
704 // Only valid if one of the masks is a superset of the other (check "B|D" is
705 // the same as either B or D).
706 APInt NewMask = BCst->getValue() | DCst->getValue();
707
708 if (NewMask == BCst->getValue())
709 return LHS;
710 else if (NewMask == DCst->getValue())
711 return RHS;
712 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000713
714 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000715 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000716 // We already know that B & C == C && D & E == E.
717 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
718 // C and E, which are shared by both the mask B and the mask D, don't
719 // contradict, then we can transform to
720 // -> (icmp eq (A & (B|D)), (C|E))
721 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000722 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000723 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000724 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000725 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000726 if (!CCst)
727 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000728 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000729 if (!ECst)
730 return nullptr;
731 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000732 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000733 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000734 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000735
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000736 // If there is a conflict, we should actually return a false for the
737 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000738 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000739 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000740 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000741
Craig Topperbb4069e2017-07-07 23:16:26 +0000742 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000743 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000744 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
745 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000746 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000747
Craig Topperf40110f2014-04-25 05:29:35 +0000748 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000749}
750
Erik Ecksteind1817522014-12-03 10:39:15 +0000751/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
752/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
753/// If \p Inverted is true then the check is for the inverted range, e.g.
754/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
755Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
756 bool Inverted) {
757 // Check the lower range comparison, e.g. x >= 0
758 // InstCombine already ensured that if there is a constant it's on the RHS.
759 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
760 if (!RangeStart)
761 return nullptr;
762
763 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
764 Cmp0->getPredicate());
765
766 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
767 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
768 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
769 return nullptr;
770
771 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
772 Cmp1->getPredicate());
773
774 Value *Input = Cmp0->getOperand(0);
775 Value *RangeEnd;
776 if (Cmp1->getOperand(0) == Input) {
777 // For the upper range compare we have: icmp x, n
778 RangeEnd = Cmp1->getOperand(1);
779 } else if (Cmp1->getOperand(1) == Input) {
780 // For the upper range compare we have: icmp n, x
781 RangeEnd = Cmp1->getOperand(0);
782 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
783 } else {
784 return nullptr;
785 }
786
787 // Check the upper range comparison, e.g. x < n
788 ICmpInst::Predicate NewPred;
789 switch (Pred1) {
790 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
791 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
792 default: return nullptr;
793 }
794
795 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000796 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
797 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000798 return nullptr;
799
800 if (Inverted)
801 NewPred = ICmpInst::getInversePredicate(NewPred);
802
Craig Topperbb4069e2017-07-07 23:16:26 +0000803 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000804}
805
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000806static Value *
807foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
808 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000809 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000810 Value *X = LHS->getOperand(0);
811 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000812 return nullptr;
813
Sanjay Patelef9f5862017-04-15 17:55:06 +0000814 const APInt *C1, *C2;
815 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
816 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000817 return nullptr;
818
819 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
820 ICmpInst::Predicate Pred = LHS->getPredicate();
821 if (Pred != RHS->getPredicate())
822 return nullptr;
823 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
824 return nullptr;
825 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
826 return nullptr;
827
828 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000829 if (C1->ugt(*C2))
830 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000831
Sanjay Patelef9f5862017-04-15 17:55:06 +0000832 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000833 if (Xor.isPowerOf2()) {
834 // If LHSC and RHSC differ by only one bit, then set that bit in X and
835 // compare against the larger constant:
836 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
837 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
838 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
839 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000840 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
841 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000842 }
843
844 // Special case: get the ordering right when the values wrap around zero.
845 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000846 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000847 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000848
Sanjay Patelef9f5862017-04-15 17:55:06 +0000849 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000850 // (X == 13 || X == 14) --> X - 13 <=u 1
851 // (X != 13 && X != 14) --> X - 13 >u 1
852 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000853 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000854 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000855 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000856 }
857
858 return nullptr;
859}
860
Craig Topperda6ea0d2017-06-16 05:10:37 +0000861// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
862// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
863Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
864 bool JoinedByAnd,
865 Instruction &CxtI) {
866 ICmpInst::Predicate Pred = LHS->getPredicate();
867 if (Pred != RHS->getPredicate())
868 return nullptr;
869 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
870 return nullptr;
871 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
872 return nullptr;
873
874 // TODO support vector splats
875 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
876 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
877 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
878 return nullptr;
879
880 Value *A, *B, *C, *D;
881 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
882 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
883 if (A == D || B == D)
884 std::swap(C, D);
885 if (B == C)
886 std::swap(A, B);
887
888 if (A == C &&
889 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
890 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000891 Value *Mask = Builder.CreateOr(B, D);
892 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000893 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000894 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000895 }
896 }
897
898 return nullptr;
899}
900
Roman Lebedev35348742018-08-13 21:54:37 +0000901/// General pattern:
902/// X & Y
903///
904/// Where Y is checking that all the high bits (covered by a mask 4294967168)
905/// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0
906/// Pattern can be one of:
907/// %t = add i32 %arg, 128
908/// %r = icmp ult i32 %t, 256
909/// Or
910/// %t0 = shl i32 %arg, 24
911/// %t1 = ashr i32 %t0, 24
912/// %r = icmp eq i32 %t1, %arg
913/// Or
914/// %t0 = trunc i32 %arg to i8
915/// %t1 = sext i8 %t0 to i32
916/// %r = icmp eq i32 %t1, %arg
917/// This pattern is a signed truncation check.
918///
919/// And X is checking that some bit in that same mask is zero.
920/// I.e. can be one of:
921/// %r = icmp sgt i32 %arg, -1
922/// Or
923/// %t = and i32 %arg, 2147483648
924/// %r = icmp eq i32 %t, 0
925///
926/// Since we are checking that all the bits in that mask are the same,
927/// and a particular bit is zero, what we are really checking is that all the
928/// masked bits are zero.
929/// So this should be transformed to:
930/// %r = icmp ult i32 %arg, 128
931static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
932 Instruction &CxtI,
933 InstCombiner::BuilderTy &Builder) {
934 assert(CxtI.getOpcode() == Instruction::And);
935
936 // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two)
937 auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
938 APInt &SignBitMask) -> bool {
939 CmpInst::Predicate Pred;
940 const APInt *I01, *I1; // powers of two; I1 == I01 << 1
941 if (!(match(ICmp,
942 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
943 Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
944 return false;
945 // Which bit is the new sign bit as per the 'signed truncation' pattern?
946 SignBitMask = *I01;
947 return true;
948 };
949
950 // One icmp needs to be 'signed truncation check'.
951 // We need to match this first, else we will mismatch commutative cases.
952 Value *X1;
953 APInt HighestBit;
954 ICmpInst *OtherICmp;
955 if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
956 OtherICmp = ICmp0;
957 else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
958 OtherICmp = ICmp1;
959 else
960 return nullptr;
961
962 assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
963
964 // Try to match/decompose into: icmp eq (X & Mask), 0
965 auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
966 APInt &UnsetBitsMask) -> bool {
967 CmpInst::Predicate Pred = ICmp->getPredicate();
968 // Can it be decomposed into icmp eq (X & Mask), 0 ?
969 if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
970 Pred, X, UnsetBitsMask,
971 /*LookThruTrunc=*/false) &&
972 Pred == ICmpInst::ICMP_EQ)
973 return true;
974 // Is it icmp eq (X & Mask), 0 already?
975 const APInt *Mask;
976 if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
977 Pred == ICmpInst::ICMP_EQ) {
978 UnsetBitsMask = *Mask;
979 return true;
980 }
981 return false;
982 };
983
984 // And the other icmp needs to be decomposable into a bit test.
985 Value *X0;
986 APInt UnsetBitsMask;
987 if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
988 return nullptr;
989
990 assert(!UnsetBitsMask.isNullValue() && "empty mask makes no sense.");
991
992 // Are they working on the same value?
993 Value *X;
994 if (X1 == X0) {
995 // Ok as is.
996 X = X1;
997 } else if (match(X0, m_Trunc(m_Specific(X1)))) {
998 UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
999 X = X1;
1000 } else
1001 return nullptr;
1002
1003 // So which bits should be uniform as per the 'signed truncation check'?
1004 // (all the bits starting with (i.e. including) HighestBit)
1005 APInt SignBitsMask = ~(HighestBit - 1U);
1006
1007 // UnsetBitsMask must have some common bits with SignBitsMask,
1008 if (!UnsetBitsMask.intersects(SignBitsMask))
1009 return nullptr;
1010
1011 // Does UnsetBitsMask contain any bits outside of SignBitsMask?
1012 if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
1013 APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
1014 if (!OtherHighestBit.isPowerOf2())
1015 return nullptr;
1016 HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
1017 }
1018 // Else, if it does not, then all is ok as-is.
1019
1020 // %r = icmp ult %X, SignBit
1021 return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
1022 CxtI.getName() + ".simplified");
1023}
1024
Sanjay Patel18549272015-09-08 18:24:36 +00001025/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001026Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1027 Instruction &CxtI) {
1028 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
1029 // if K1 and K2 are a one-bit mask.
1030 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
1031 return V;
1032
Sanjay Patel519a87a2017-04-05 17:38:34 +00001033 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001034
1035 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel472652e2018-12-03 15:48:30 +00001036 if (predicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001037 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1038 LHS->getOperand(1) == RHS->getOperand(0))
1039 LHS->swapOperands();
1040 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1041 LHS->getOperand(1) == RHS->getOperand(1)) {
1042 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1043 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
Sanjay Patel3d5bb152018-12-04 18:53:27 +00001044 bool IsSigned = LHS->isSigned() || RHS->isSigned();
1045 return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001046 }
1047 }
Owen Anderson3fe002d2010-09-08 22:16:17 +00001048
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001049 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001050 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001051 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +00001052
Erik Ecksteind1817522014-12-03 10:39:15 +00001053 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
1054 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
1055 return V;
1056
1057 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
1058 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
1059 return V;
1060
Sanjay Patelef9f5862017-04-15 17:55:06 +00001061 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
1062 return V;
1063
Roman Lebedev35348742018-08-13 21:54:37 +00001064 if (Value *V = foldSignedTruncationCheck(LHS, RHS, CxtI, Builder))
1065 return V;
1066
Chris Lattner0a8191e2010-01-05 07:50:36 +00001067 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +00001068 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001069 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1070 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
1071 if (!LHSC || !RHSC)
1072 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001073
Sanjay Patel519a87a2017-04-05 17:38:34 +00001074 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001075 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +00001076 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +00001077 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001078 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
1079 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001080 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1081 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001082 }
1083 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001084
Benjamin Kramer101720f2011-04-28 20:09:57 +00001085 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001086 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001087 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001088 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
1089 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001090 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001091 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001092
1093 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +00001094 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +00001095 if (match(RHS0, m_Trunc(m_Value(V))) &&
1096 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001097 SmallC = RHSC;
1098 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001099 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
1100 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +00001101 SmallC = LHSC;
1102 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001103 }
1104
Sanjay Patel519a87a2017-04-05 17:38:34 +00001105 if (SmallC && BigC) {
1106 unsigned BigBitSize = BigC->getType()->getBitWidth();
1107 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001108
1109 // Check that the low bits are zero.
1110 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +00001111 if ((Low & AndC->getValue()).isNullValue() &&
1112 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001113 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +00001114 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
1115 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +00001116 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +00001117 }
1118 }
1119 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001120
Chris Lattner0a8191e2010-01-05 07:50:36 +00001121 // From here on, we only handle:
1122 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001123 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001124 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001125
Sanjay Patel519a87a2017-04-05 17:38:34 +00001126 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1127 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1128 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1129 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1130 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001131 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +00001132
Chris Lattner0a8191e2010-01-05 07:50:36 +00001133 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel472652e2018-12-03 15:48:30 +00001134 if (!predicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001135 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001136
Chris Lattner0a8191e2010-01-05 07:50:36 +00001137 // Ensure that the larger constant is on the RHS.
1138 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001139 if (CmpInst::isSigned(PredL) ||
1140 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001141 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001142 else
1143 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001144
Chris Lattner0a8191e2010-01-05 07:50:36 +00001145 if (ShouldSwap) {
1146 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001147 std::swap(LHSC, RHSC);
1148 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001149 }
1150
Dan Gohman4a618822010-02-10 16:03:48 +00001151 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001152 // comparing a value against two constants and and'ing the result
1153 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +00001154 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1155 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +00001156 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +00001157 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001158
Sanjay Patel519a87a2017-04-05 17:38:34 +00001159 switch (PredL) {
1160 default:
1161 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001162 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001163 switch (PredR) {
1164 default:
1165 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001166 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001167 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +00001168 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +00001169 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +00001170 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +00001171 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001172 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001173 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001174 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +00001175 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001176 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001177 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001178 // Potential folds for this case should already be handled.
1179 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001180 }
1181 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001182 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001183 switch (PredR) {
1184 default:
1185 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001186 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001187 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +00001188 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001189 break; // (X u> 13 & X != 15) -> no change
1190 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +00001191 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1192 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001193 }
1194 break;
1195 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001196 switch (PredR) {
1197 default:
1198 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001199 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001200 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +00001201 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001202 break; // (X s> 13 & X != 15) -> no change
1203 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +00001204 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001205 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001206 }
1207 break;
1208 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001209
Craig Topperf40110f2014-04-25 05:29:35 +00001210 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001211}
1212
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001213Value *InstCombiner::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
Sanjay Patel275bb5a2017-09-02 17:17:17 +00001214 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1215 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1216 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Tim Shenaec68b22016-06-29 20:10:17 +00001217
Sanjay Patel275bb5a2017-09-02 17:17:17 +00001218 if (LHS0 == RHS1 && RHS0 == LHS1) {
Tim Shenaec68b22016-06-29 20:10:17 +00001219 // Swap RHS operands to match LHS.
Sanjay Patel275bb5a2017-09-02 17:17:17 +00001220 PredR = FCmpInst::getSwappedPredicate(PredR);
1221 std::swap(RHS0, RHS1);
Tim Shenaec68b22016-06-29 20:10:17 +00001222 }
1223
1224 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1225 // Suppose the relation between x and y is R, where R is one of
1226 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1227 // testing the desired relations.
1228 //
1229 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1230 // bool(R & CC0) && bool(R & CC1)
1231 // = bool((R & CC0) & (R & CC1))
1232 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
Sanjay Patel4c52f762017-09-02 16:30:27 +00001233 //
1234 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1235 // bool(R & CC0) || bool(R & CC1)
1236 // = bool((R & CC0) | (R & CC1))
1237 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001238 if (LHS0 == RHS0 && LHS1 == RHS1) {
1239 unsigned FCmpCodeL = getFCmpCode(PredL);
1240 unsigned FCmpCodeR = getFCmpCode(PredR);
1241 unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1242 return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1243 }
Sanjay Patel4c52f762017-09-02 16:30:27 +00001244
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001245 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1246 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
Sanjay Patel275bb5a2017-09-02 17:17:17 +00001247 if (LHS0->getType() != RHS0->getType())
1248 return nullptr;
1249
Sanjay Patel6840c5f2017-09-05 23:13:13 +00001250 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
Sanjay Patel93e64dd2018-03-25 21:16:33 +00001251 // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1252 if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
Sanjay Patel6840c5f2017-09-05 23:13:13 +00001253 // Ignore the constants because they are obviously not NANs:
1254 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y)
1255 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y)
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001256 return Builder.CreateFCmp(PredL, LHS0, RHS0);
Sanjay Patel4c52f762017-09-02 16:30:27 +00001257 }
1258
1259 return nullptr;
1260}
1261
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001262/// Match De Morgan's Laws:
1263/// (~A & ~B) == (~(A | B))
1264/// (~A | ~B) == (~(A & B))
1265static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001266 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001267 auto Opcode = I.getOpcode();
1268 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1269 "Trying to match De Morgan's Laws with something other than and/or");
1270
Sanjay Patel7caaa792017-05-09 20:05:05 +00001271 // Flip the logic operation.
1272 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1273
1274 Value *A, *B;
1275 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1276 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1277 !IsFreeToInvert(A, A->hasOneUse()) &&
1278 !IsFreeToInvert(B, B->hasOneUse())) {
1279 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1280 return BinaryOperator::CreateNot(AndOr);
1281 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001282
1283 return nullptr;
1284}
1285
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001286bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1287 Value *CastSrc = CI->getOperand(0);
1288
1289 // Noop casts and casts of constants should be eliminated trivially.
1290 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1291 return false;
1292
1293 // If this cast is paired with another cast that can be eliminated, we prefer
1294 // to have it eliminated.
1295 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1296 if (isEliminableCastPair(PrecedingCI, CI))
1297 return false;
1298
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001299 return true;
1300}
1301
Sanjay Patel60312bc42016-09-12 00:16:23 +00001302/// Fold {and,or,xor} (cast X), C.
1303static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +00001304 InstCombiner::BuilderTy &Builder) {
Craig Topper5706c012017-08-09 06:17:48 +00001305 Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1306 if (!C)
Sanjay Patel60312bc42016-09-12 00:16:23 +00001307 return nullptr;
1308
1309 auto LogicOpc = Logic.getOpcode();
1310 Type *DestTy = Logic.getType();
1311 Type *SrcTy = Cast->getSrcTy();
1312
Craig Topperae9b87d2017-08-02 20:25:56 +00001313 // Move the logic operation ahead of a zext or sext if the constant is
1314 // unchanged in the smaller source type. Performing the logic in a smaller
1315 // type may provide more information to later folds, and the smaller logic
1316 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001317 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001318 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1319 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1320 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1321 if (ZextTruncC == C) {
1322 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001323 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001324 return new ZExtInst(NewOp, DestTy);
1325 }
1326 }
1327
Craig Topperae9b87d2017-08-02 20:25:56 +00001328 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1329 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1330 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1331 if (SextTruncC == C) {
1332 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1333 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1334 return new SExtInst(NewOp, DestTy);
1335 }
1336 }
1337
Sanjay Patel60312bc42016-09-12 00:16:23 +00001338 return nullptr;
1339}
1340
1341/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001342Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001343 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001344 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001345
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001346 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001347 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001348 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001349 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001350
Sanjay Patel9bba7502016-03-03 19:19:04 +00001351 // This must be a cast from an integer or integer vector source type to allow
1352 // transformation of the logic operation to the source type.
1353 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001354 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001355 if (!SrcTy->isIntOrIntVectorTy())
1356 return nullptr;
1357
Sanjay Patel60312bc42016-09-12 00:16:23 +00001358 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1359 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001360
Sanjay Patel9bba7502016-03-03 19:19:04 +00001361 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1362 if (!Cast1)
1363 return nullptr;
1364
1365 // Both operands of the logic operation are casts. The casts must be of the
1366 // same type for reduction.
1367 auto CastOpcode = Cast0->getOpcode();
1368 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001369 return nullptr;
1370
1371 Value *Cast0Src = Cast0->getOperand(0);
1372 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001373
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001374 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001375 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001376 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001377 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001378 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001379 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001380
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001381 // For now, only 'and'/'or' have optimizations after this.
1382 if (LogicOpc == Instruction::Xor)
1383 return nullptr;
1384
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001385 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001386 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001387 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1388 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1389 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001390 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001391 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001392 if (Res)
1393 return CastInst::Create(CastOpcode, Res, DestTy);
1394 return nullptr;
1395 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001396
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001397 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001398 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001399 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1400 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001401 if (FCmp0 && FCmp1)
1402 if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1403 return CastInst::Create(CastOpcode, R, DestTy);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001404
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001405 return nullptr;
1406}
1407
Sanjay Patele0c26e02017-04-23 22:00:02 +00001408static Instruction *foldAndToXor(BinaryOperator &I,
1409 InstCombiner::BuilderTy &Builder) {
1410 assert(I.getOpcode() == Instruction::And);
1411 Value *Op0 = I.getOperand(0);
1412 Value *Op1 = I.getOperand(1);
1413 Value *A, *B;
1414
1415 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1416 // (A | B) & ~(A & B) --> A ^ B
1417 // (A | B) & ~(B & A) --> A ^ B
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001418 if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1419 m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001420 return BinaryOperator::CreateXor(A, B);
1421
1422 // (A | ~B) & (~A | B) --> ~(A ^ B)
1423 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1424 // (~B | A) & (~A | B) --> ~(A ^ B)
1425 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001426 if (Op0->hasOneUse() || Op1->hasOneUse())
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001427 if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
1428 m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
Craig Topper0de5e6a2017-06-22 16:12:02 +00001429 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001430
1431 return nullptr;
1432}
1433
1434static Instruction *foldOrToXor(BinaryOperator &I,
1435 InstCombiner::BuilderTy &Builder) {
1436 assert(I.getOpcode() == Instruction::Or);
1437 Value *Op0 = I.getOperand(0);
1438 Value *Op1 = I.getOperand(1);
1439 Value *A, *B;
1440
1441 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1442 // (A & B) | ~(A | B) --> ~(A ^ B)
1443 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001444 if (Op0->hasOneUse() || Op1->hasOneUse())
1445 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1446 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1447 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001448
1449 // (A & ~B) | (~A & B) --> A ^ B
1450 // (A & ~B) | (B & ~A) --> A ^ B
1451 // (~B & A) | (~A & B) --> A ^ B
1452 // (~B & A) | (B & ~A) --> A ^ B
1453 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1454 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1455 return BinaryOperator::CreateXor(A, B);
1456
1457 return nullptr;
1458}
1459
Sanjay Patel1d681122018-01-25 16:34:36 +00001460/// Return true if a constant shift amount is always less than the specified
1461/// bit-width. If not, the shift could create poison in the narrower type.
1462static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1463 if (auto *ScalarC = dyn_cast<ConstantInt>(C))
1464 return ScalarC->getZExtValue() < BitWidth;
1465
1466 if (C->getType()->isVectorTy()) {
1467 // Check each element of a constant vector.
1468 unsigned NumElts = C->getType()->getVectorNumElements();
1469 for (unsigned i = 0; i != NumElts; ++i) {
1470 Constant *Elt = C->getAggregateElement(i);
1471 if (!Elt)
1472 return false;
1473 if (isa<UndefValue>(Elt))
1474 continue;
1475 auto *CI = dyn_cast<ConstantInt>(Elt);
1476 if (!CI || CI->getZExtValue() >= BitWidth)
1477 return false;
1478 }
1479 return true;
1480 }
1481
1482 // The constant is a constant expression or unknown.
1483 return false;
1484}
1485
1486/// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1487/// a common zext operand: and (binop (zext X), C), (zext X).
1488Instruction *InstCombiner::narrowMaskedBinOp(BinaryOperator &And) {
1489 // This transform could also apply to {or, and, xor}, but there are better
1490 // folds for those cases, so we don't expect those patterns here. AShr is not
1491 // handled because it should always be transformed to LShr in this sequence.
1492 // The subtract transform is different because it has a constant on the left.
1493 // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1494 Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1495 Constant *C;
1496 if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1497 !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1498 !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1499 !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1500 !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1501 return nullptr;
1502
1503 Value *X;
Craig Topperee99aa42018-03-12 18:46:05 +00001504 if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
Sanjay Patel1d681122018-01-25 16:34:36 +00001505 return nullptr;
1506
1507 Type *Ty = And.getType();
1508 if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1509 return nullptr;
1510
1511 // If we're narrowing a shift, the shift amount must be safe (less than the
1512 // width) in the narrower type. If the shift amount is greater, instsimplify
1513 // usually handles that case, but we can't guarantee/assert it.
1514 Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1515 if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1516 if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1517 return nullptr;
1518
1519 // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1520 // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1521 Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1522 Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1523 : Builder.CreateBinOp(Opc, X, NewC);
1524 return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1525}
1526
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001527// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1528// here. We should standardize that construct where it is needed or choose some
1529// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001530Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001531 if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1),
1532 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001533 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001534
Sanjay Patel70043b72018-07-13 01:18:07 +00001535 if (SimplifyAssociativeOrCommutative(I))
1536 return &I;
1537
Sanjay Patel79dceb22018-10-03 15:20:58 +00001538 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001539 return X;
1540
Craig Topper9d4171a2012-12-20 07:09:41 +00001541 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001542 // purpose is to compute bits we don't care about.
1543 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001544 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001545
Sanjay Patele0c26e02017-04-23 22:00:02 +00001546 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001547 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001548 return Xor;
1549
1550 // (A|B)&(A|C) -> A|(B&C) etc
1551 if (Value *V = SimplifyUsingDistributiveLaws(I))
1552 return replaceInstUsesWith(I, V);
1553
Craig Topper95e41422017-07-06 16:24:23 +00001554 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001555 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001556
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001558 const APInt *C;
1559 if (match(Op1, m_APInt(C))) {
1560 Value *X, *Y;
1561 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1562 C->isOneValue()) {
1563 // (1 << X) & 1 --> zext(X == 0)
1564 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001565 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1566 return new ZExtInst(IsZero, I.getType());
1567 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001568
Craig Toppera1693a22017-08-06 23:11:49 +00001569 const APInt *XorC;
1570 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1571 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1572 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1573 Value *And = Builder.CreateAnd(X, Op1);
1574 And->takeName(Op0);
1575 return BinaryOperator::CreateXor(And, NewC);
1576 }
1577
Craig Topper7091a742017-08-07 18:10:39 +00001578 const APInt *OrC;
1579 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1580 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1581 // NOTE: This reduces the number of bits set in the & mask, which
1582 // can expose opportunities for store narrowing for scalars.
1583 // NOTE: SimplifyDemandedBits should have already removed bits from C1
1584 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1585 // above, but this feels safer.
1586 APInt Together = *C & *OrC;
1587 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(),
1588 Together ^ *C));
1589 And->takeName(Op0);
1590 return BinaryOperator::CreateOr(And, ConstantInt::get(I.getType(),
1591 Together));
1592 }
1593
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001594 // If the mask is only needed on one incoming arm, push the 'and' op up.
1595 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1596 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1597 APInt NotAndMask(~(*C));
1598 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1599 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1600 // Not masking anything out for the LHS, move mask to RHS.
1601 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1602 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1603 return BinaryOperator::Create(BinOp, X, NewRHS);
1604 }
1605 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1606 // Not masking anything out for the RHS, move mask to LHS.
1607 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1608 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1609 return BinaryOperator::Create(BinOp, NewLHS, Y);
1610 }
1611 }
Craig Toppera1693a22017-08-06 23:11:49 +00001612
Sanjay Patel3437ee22017-07-15 17:26:01 +00001613 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001614
Chris Lattner0a8191e2010-01-05 07:50:36 +00001615 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1616 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001617
1618 // Optimize a variety of ((val OP C1) & C2) combinations...
1619 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001620 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1621 // of X and OP behaves well when given trunc(C1) and X.
1622 switch (Op0I->getOpcode()) {
1623 default:
1624 break;
1625 case Instruction::Xor:
1626 case Instruction::Or:
1627 case Instruction::Mul:
1628 case Instruction::Add:
1629 case Instruction::Sub:
1630 Value *X;
1631 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001632 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001633 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1634 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1635 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001636 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001637 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001638 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001639 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001640 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001641 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001642 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001643 return new ZExtInst(And, I.getType());
1644 }
1645 }
1646 }
1647
Chris Lattner0a8191e2010-01-05 07:50:36 +00001648 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1649 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1650 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001651 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001652
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001653 // If this is an integer truncation, and if the source is an 'and' with
1654 // immediate, transform it. This frequently occurs for bitfield accesses.
1655 {
Craig Topperf40110f2014-04-25 05:29:35 +00001656 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001657 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1658 // Change: and (trunc (and X, YC) to T), C2
1659 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001660 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001661 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001662 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001663 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1664 C3 = ConstantExpr::getAnd(C3, AndRHS);
1665 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001666 }
1667 }
Craig Topper86173602017-04-04 20:26:25 +00001668 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001669
Sanjay Patel1d681122018-01-25 16:34:36 +00001670 if (Instruction *Z = narrowMaskedBinOp(I))
1671 return Z;
1672
Sanjay Patel8fdd87f2018-02-28 16:36:24 +00001673 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
1674 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001675
Craig Topperbb4069e2017-07-07 23:16:26 +00001676 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001677 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001678
Chris Lattner0a8191e2010-01-05 07:50:36 +00001679 {
Sanjay Patel9a801cb2018-07-31 13:00:03 +00001680 Value *A, *B, *C;
1681 // A & (A ^ B) --> A & ~B
1682 if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
1683 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
1684 // (A ^ B) & A --> A & ~B
1685 if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
1686 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001687
David Majnemer42af3602014-07-30 21:26:37 +00001688 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1689 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1690 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001691 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001692 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001693
1694 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1695 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1696 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001697 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001698 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001699
1700 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001701 // (A | B) & (B ^ (~A)) -> (A & B)
1702 // (B | A) & ((~A) ^ B) -> (A & B)
1703 // (B | A) & (B ^ (~A)) -> (A & B)
1704 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1705 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001706 return BinaryOperator::CreateAnd(A, B);
1707
1708 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001709 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001710 // (B ^ (~A)) & (A | B) -> (A & B)
1711 // (B ^ (~A)) & (B | A) -> (A & B)
1712 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001713 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001714 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001715 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001716
David Majnemer5e96f1b2014-08-30 06:18:20 +00001717 {
1718 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1719 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1720 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001721 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001722 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001723
David Majnemer5e96f1b2014-08-30 06:18:20 +00001724 // TODO: Make this recursive; it's a little tricky because an arbitrary
1725 // number of 'and' instructions might have to be created.
1726 Value *X, *Y;
1727 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1728 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001729 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001730 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001731 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001732 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001733 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001734 }
1735 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1736 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001737 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001738 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001739 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001740 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001741 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001742 }
1743 }
1744
Chris Lattner4e8137d2010-02-11 06:26:33 +00001745 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1746 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel64fc5da2017-09-02 17:53:33 +00001747 if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00001748 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001749
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001750 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1751 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001752
Craig Topper760ff6e2017-08-04 16:07:20 +00001753 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1754 Value *A;
1755 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1756 A->getType()->isIntOrIntVectorTy(1))
1757 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1758 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1759 A->getType()->isIntOrIntVectorTy(1))
1760 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001761
Sanjay Patel70043b72018-07-13 01:18:07 +00001762 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001763}
1764
Sanjay Patel60728422018-11-14 16:03:36 +00001765Instruction *InstCombiner::matchBSwap(BinaryOperator &Or) {
1766 assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
1767 Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
Chad Rosiere5819e22016-05-26 14:58:51 +00001768
1769 // Look through zero extends.
1770 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1771 Op0 = Ext->getOperand(0);
1772
1773 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1774 Op1 = Ext->getOperand(0);
1775
1776 // (A | B) | C and A | (B | C) -> bswap if possible.
1777 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1778 match(Op1, m_Or(m_Value(), m_Value()));
1779
1780 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1781 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1782 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1783
1784 // (A & B) | (C & D) -> bswap if possible.
1785 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1786 match(Op1, m_And(m_Value(), m_Value()));
1787
Omer Paparo Bivas82ef8e12018-05-01 12:25:46 +00001788 // (A << B) | (C & D) -> bswap if possible.
1789 // The bigger pattern here is ((A & C1) << C2) | ((B >> C2) & C1), which is a
1790 // part of the bswap idiom for specific values of C1, C2 (e.g. C1 = 16711935,
1791 // C2 = 8 for i32).
1792 // This pattern can occur when the operands of the 'or' are not canonicalized
1793 // for some reason (not having only one use, for example).
1794 bool OrOfAndAndSh = (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1795 match(Op1, m_And(m_Value(), m_Value()))) ||
1796 (match(Op0, m_And(m_Value(), m_Value())) &&
1797 match(Op1, m_LogicalShift(m_Value(), m_Value())));
1798
1799 if (!OrOfOrs && !OrOfShifts && !OrOfAnds && !OrOfAndAndSh)
Chad Rosiere5819e22016-05-26 14:58:51 +00001800 return nullptr;
1801
James Molloyf01488e2016-01-15 09:20:19 +00001802 SmallVector<Instruction*, 4> Insts;
Sanjay Patel60728422018-11-14 16:03:36 +00001803 if (!recognizeBSwapOrBitReverseIdiom(&Or, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001804 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001805 Instruction *LastInst = Insts.pop_back_val();
1806 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001807
James Molloyf01488e2016-01-15 09:20:19 +00001808 for (auto *Inst : Insts)
1809 Worklist.Add(Inst);
1810 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001811}
1812
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001813/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1814static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1815 unsigned NumElts = C1->getType()->getVectorNumElements();
1816 for (unsigned i = 0; i != NumElts; ++i) {
1817 Constant *EltC1 = C1->getAggregateElement(i);
1818 Constant *EltC2 = C2->getAggregateElement(i);
1819 if (!EltC1 || !EltC2)
1820 return false;
1821
1822 // One element must be all ones, and the other must be all zeros.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001823 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1824 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1825 return false;
1826 }
1827 return true;
1828}
1829
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001830/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1831/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1832/// B, it can be used as the condition operand of a select instruction.
Sanjay Patel3b206302018-10-24 15:17:56 +00001833Value *InstCombiner::getSelectCondition(Value *A, Value *B) {
1834 // Step 1: We may have peeked through bitcasts in the caller.
1835 // Exit immediately if we don't have (vector) integer types.
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001836 Type *Ty = A->getType();
Sanjay Patel3b206302018-10-24 15:17:56 +00001837 if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
1838 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001839
Sanjay Patel3b206302018-10-24 15:17:56 +00001840 // Step 2: We need 0 or all-1's bitmasks.
1841 if (ComputeNumSignBits(A) != Ty->getScalarSizeInBits())
1842 return nullptr;
1843
1844 // Step 3: If B is the 'not' value of A, we have our answer.
1845 if (match(A, m_Not(m_Specific(B)))) {
1846 // If these are scalars or vectors of i1, A can be used directly.
1847 if (Ty->isIntOrIntVectorTy(1))
1848 return A;
1849 return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(Ty));
1850 }
1851
1852 // If both operands are constants, see if the constants are inverse bitmasks.
1853 Constant *AConst, *BConst;
1854 if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
1855 if (AConst == ConstantExpr::getNot(BConst))
1856 return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
1857
1858 // Look for more complex patterns. The 'not' op may be hidden behind various
1859 // casts. Look through sexts and bitcasts to find the booleans.
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001860 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001861 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001862 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001863 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001864 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1865 NotB = peekThroughBitcast(NotB, true);
1866 if (match(NotB, m_SExt(m_Specific(Cond))))
1867 return Cond;
1868 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001869
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001870 // All scalar (and most vector) possibilities should be handled now.
1871 // Try more matches that only apply to non-splat constant vectors.
1872 if (!Ty->isVectorTy())
1873 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001874
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001875 // If both operands are xor'd with constants using the same sexted boolean
1876 // operand, see if the constants are inverse bitmasks.
Sanjay Patel3b206302018-10-24 15:17:56 +00001877 // TODO: Use ConstantExpr::getNot()?
1878 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
1879 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001880 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patel3b206302018-10-24 15:17:56 +00001881 areInverseVectorBitmasks(AConst, BConst)) {
1882 AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
1883 return Builder.CreateXor(Cond, AConst);
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001884 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001885 return nullptr;
1886}
1887
1888/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1889/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel3b206302018-10-24 15:17:56 +00001890Value *InstCombiner::matchSelectFromAndOr(Value *A, Value *C, Value *B,
1891 Value *D) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001892 // The potential condition of the select may be bitcasted. In that case, look
1893 // through its bitcast and the corresponding bitcast of the 'not' condition.
1894 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001895 A = peekThroughBitcast(A, true);
1896 B = peekThroughBitcast(B, true);
Sanjay Patel3b206302018-10-24 15:17:56 +00001897 if (Value *Cond = getSelectCondition(A, B)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001898 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001899 // The bitcasts will either all exist or all not exist. The builder will
1900 // not create unnecessary casts if the types already match.
1901 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1902 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1903 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1904 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001905 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001906
Craig Topperf40110f2014-04-25 05:29:35 +00001907 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001908}
1909
Sanjay Patel18549272015-09-08 18:24:36 +00001910/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001911Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001912 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001913 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1914 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001915 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1916 return V;
1917
1918 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1919
Sanjay Patel519a87a2017-04-05 17:38:34 +00001920 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1921 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001922
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001923 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1924 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1925 // The original condition actually refers to the following two ranges:
1926 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1927 // We can fold these two ranges if:
1928 // 1) C1 and C2 is unsigned greater than C3.
1929 // 2) The two ranges are separated.
1930 // 3) C1 ^ C2 is one-bit mask.
1931 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1932 // This implies all values in the two ranges differ by exactly one bit.
1933
Sanjay Patel519a87a2017-04-05 17:38:34 +00001934 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1935 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1936 LHSC->getType() == RHSC->getType() &&
1937 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001938
1939 Value *LAdd = LHS->getOperand(0);
1940 Value *RAdd = RHS->getOperand(0);
1941
1942 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001943 ConstantInt *LAddC, *RAddC;
1944 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1945 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1946 LAddC->getValue().ugt(LHSC->getValue()) &&
1947 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001948
Sanjay Patel519a87a2017-04-05 17:38:34 +00001949 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1950 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1951 ConstantInt *MaxAddC = nullptr;
1952 if (LAddC->getValue().ult(RAddC->getValue()))
1953 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001954 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001955 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001956
Sanjay Patel519a87a2017-04-05 17:38:34 +00001957 APInt RRangeLow = -RAddC->getValue();
1958 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1959 APInt LRangeLow = -LAddC->getValue();
1960 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001961 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1962 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1963 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1964 : RRangeLow - LRangeLow;
1965
1966 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001967 RangeDiff.ugt(LHSC->getValue())) {
1968 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001969
Craig Topperbb4069e2017-07-07 23:16:26 +00001970 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1971 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1972 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001973 }
1974 }
1975 }
1976 }
1977
Chris Lattner0a8191e2010-01-05 07:50:36 +00001978 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel472652e2018-12-03 15:48:30 +00001979 if (predicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001980 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1981 LHS->getOperand(1) == RHS->getOperand(0))
1982 LHS->swapOperands();
1983 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1984 LHS->getOperand(1) == RHS->getOperand(1)) {
1985 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1986 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
Sanjay Patel3d5bb152018-12-04 18:53:27 +00001987 bool IsSigned = LHS->isSigned() || RHS->isSigned();
1988 return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001989 }
1990 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001991
1992 // handle (roughly):
1993 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001994 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001995 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001996
Sanjay Patele4159d22017-04-10 19:38:36 +00001997 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001998 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1999 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2000 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00002001 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00002002 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00002003 B = LHS0;
2004 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
2005 A = RHS0;
2006 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00002007 A = RHS->getOperand(1);
2008 }
2009 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2010 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00002011 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00002012 B = RHS0;
2013 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
2014 A = LHS0;
2015 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00002016 A = LHS->getOperand(1);
2017 }
2018 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00002019 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00002020 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00002021 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00002022 }
2023
Erik Ecksteind1817522014-12-03 10:39:15 +00002024 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2025 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
2026 return V;
2027
2028 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2029 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
2030 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00002031
Sanjay Patelef9f5862017-04-15 17:55:06 +00002032 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
2033 return V;
2034
David Majnemerc2a990b2013-07-05 00:31:17 +00002035 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00002036 if (!LHSC || !RHSC)
2037 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002038
Sanjay Patel519a87a2017-04-05 17:38:34 +00002039 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00002040 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00002041 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002042 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
2043 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00002044 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00002045 }
2046
Benjamin Kramerf7957d02010-12-20 20:00:31 +00002047 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002048 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00002049 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
2050 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00002051 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00002052 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00002053 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00002054 }
2055
Chris Lattner0a8191e2010-01-05 07:50:36 +00002056 // From here on, we only handle:
2057 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00002058 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00002059 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00002060
Sanjay Patel519a87a2017-04-05 17:38:34 +00002061 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
2062 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
2063 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
2064 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
2065 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00002066 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00002067
Chris Lattner0a8191e2010-01-05 07:50:36 +00002068 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel472652e2018-12-03 15:48:30 +00002069 if (!predicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00002070 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00002071
Chris Lattner0a8191e2010-01-05 07:50:36 +00002072 // Ensure that the larger constant is on the RHS.
2073 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00002074 if (CmpInst::isSigned(PredL) ||
2075 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00002076 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00002077 else
2078 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00002079
Chris Lattner0a8191e2010-01-05 07:50:36 +00002080 if (ShouldSwap) {
2081 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00002082 std::swap(LHSC, RHSC);
2083 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002084 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002085
Dan Gohman4a618822010-02-10 16:03:48 +00002086 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00002087 // comparing a value against two constants and or'ing the result
2088 // together. Because of the above check, we know that we only have
2089 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2090 // icmp folding check above), that the two constants are not
2091 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00002092 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00002093
Sanjay Patel519a87a2017-04-05 17:38:34 +00002094 switch (PredL) {
2095 default:
2096 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00002097 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00002098 switch (PredR) {
2099 default:
2100 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00002101 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00002102 // Potential folds for this case should already be handled.
2103 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00002104 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
2105 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00002106 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002107 }
2108 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002109 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00002110 switch (PredR) {
2111 default:
2112 llvm_unreachable("Unknown integer condition code!");
2113 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00002114 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00002115 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00002116 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00002117 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
2118 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002119 }
2120 break;
2121 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00002122 switch (PredR) {
2123 default:
2124 llvm_unreachable("Unknown integer condition code!");
2125 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00002126 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00002127 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00002128 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00002129 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00002130 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002131 }
2132 break;
2133 }
Craig Topperf40110f2014-04-25 05:29:35 +00002134 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002135}
2136
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002137// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2138// here. We should standardize that construct where it is needed or choose some
2139// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002140Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00002141 if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
2142 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002143 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00002144
Sanjay Patel70043b72018-07-13 01:18:07 +00002145 if (SimplifyAssociativeOrCommutative(I))
2146 return &I;
2147
Sanjay Patel79dceb22018-10-03 15:20:58 +00002148 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00002149 return X;
2150
Craig Topper9d4171a2012-12-20 07:09:41 +00002151 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002152 // purpose is to compute bits we don't care about.
2153 if (SimplifyDemandedInstructionBits(I))
2154 return &I;
2155
Sanjay Patele0c26e02017-04-23 22:00:02 +00002156 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00002157 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00002158 return Xor;
2159
2160 // (A&B)|(A&C) -> A&(B|C) etc
2161 if (Value *V = SimplifyUsingDistributiveLaws(I))
2162 return replaceInstUsesWith(I, V);
2163
Craig Topper95e41422017-07-06 16:24:23 +00002164 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002165 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002166
Sanjay Patel8fdd87f2018-02-28 16:36:24 +00002167 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2168 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002169
Sanjay Patel60728422018-11-14 16:03:36 +00002170 if (Instruction *BSwap = matchBSwap(I))
Chad Rosiere5819e22016-05-26 14:58:51 +00002171 return BSwap;
2172
Sanjay Patel099b1a42018-09-01 15:08:59 +00002173 Value *X, *Y;
2174 const APInt *CV;
2175 if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
2176 !CV->isAllOnesValue() && MaskedValueIsZero(Y, *CV, 0, &I)) {
2177 // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2178 // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2179 Value *Or = Builder.CreateOr(X, Y);
2180 return BinaryOperator::CreateXor(Or, ConstantInt::get(I.getType(), *CV));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002181 }
2182
Chris Lattner0a8191e2010-01-05 07:50:36 +00002183 // (A & C)|(B & D)
Sanjay Patel099b1a42018-09-01 15:08:59 +00002184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2185 Value *A, *B, *C, *D;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002186 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2187 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperafa07c52017-04-09 06:12:41 +00002188 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2189 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002190 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topperf7200992017-08-14 00:04:21 +00002191 Value *V1 = nullptr, *V2 = nullptr;
Craig Topper73ba1c82017-06-07 07:40:37 +00002192 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00002193 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002194 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00002195 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002196 ((V1 == B &&
2197 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2198 (V2 == B &&
2199 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002200 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00002201 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00002202 // Or commutes, try both ways.
2203 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00002204 ((V1 == A &&
2205 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2206 (V2 == A &&
2207 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00002208 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00002209 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00002210
Chris Lattner95188692010-01-11 06:55:24 +00002211 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002212 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00002213 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00002214 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002215 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00002216 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00002217 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002218 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00002219 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00002220 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00002221 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002222 }
Craig Topperf7200992017-08-14 00:04:21 +00002223
2224 if (C1->getValue() == ~C2->getValue()) {
2225 Value *X;
2226
2227 // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
2228 if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
2229 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
2230 // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
2231 if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
2232 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
2233
2234 // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
2235 if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
2236 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
2237 // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
2238 if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
2239 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
2240 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002241 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002242
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002243 // Don't try to form a select if it's unlikely that we'll get rid of at
2244 // least one of the operands. A select is generally more expensive than the
2245 // 'or' that it is replacing.
2246 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2247 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Sanjay Patel3b206302018-10-24 15:17:56 +00002248 if (Value *V = matchSelectFromAndOr(A, C, B, D))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002249 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002250 if (Value *V = matchSelectFromAndOr(A, C, D, B))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002251 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002252 if (Value *V = matchSelectFromAndOr(C, A, B, D))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002253 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002254 if (Value *V = matchSelectFromAndOr(C, A, D, B))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002255 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002256 if (Value *V = matchSelectFromAndOr(B, D, A, C))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002257 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002258 if (Value *V = matchSelectFromAndOr(B, D, C, A))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002259 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002260 if (Value *V = matchSelectFromAndOr(D, B, A, C))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002261 return replaceInstUsesWith(I, V);
Sanjay Patel3b206302018-10-24 15:17:56 +00002262 if (Value *V = matchSelectFromAndOr(D, B, C, A))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00002263 return replaceInstUsesWith(I, V);
2264 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002265 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002266
David Majnemer42af3602014-07-30 21:26:37 +00002267 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2268 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2269 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002270 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00002271
2272 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2273 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2274 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00002275 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00002276
David Majnemerf1eda232014-08-14 06:41:38 +00002277 // ((B | C) & A) | B -> B | (A & C)
2278 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002279 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00002280
Craig Topperbb4069e2017-07-07 23:16:26 +00002281 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00002282 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002283
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002284 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00002285 bool SwappedForXor = false;
2286 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002287 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00002288 SwappedForXor = true;
2289 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002290
2291 // A | ( A ^ B) -> A | B
2292 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00002293 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002294 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2295 if (Op0 == A || Op0 == B)
2296 return BinaryOperator::CreateOr(A, B);
2297
Chad Rosier7813dce2012-04-26 23:29:14 +00002298 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2299 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2300 return BinaryOperator::CreateOr(A, B);
2301
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002302 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002303 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002304 return BinaryOperator::CreateOr(Not, Op0);
2305 }
2306 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002307 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002308 return BinaryOperator::CreateOr(Not, Op0);
2309 }
2310 }
2311
2312 // A | ~(A | B) -> A | ~B
2313 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002314 if (match(Op1, m_Not(m_Value(A))))
2315 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002316 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2317 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2318 B->getOpcode() == Instruction::Xor)) {
2319 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2320 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002321 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002322 return BinaryOperator::CreateOr(Not, Op0);
2323 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002324
Eli Friedmane06535b2012-03-16 00:52:42 +00002325 if (SwappedForXor)
2326 std::swap(Op0, Op1);
2327
David Majnemer3d6f80b2014-11-28 19:58:29 +00002328 {
2329 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2330 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2331 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002332 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002333 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002334
David Majnemer3d6f80b2014-11-28 19:58:29 +00002335 // TODO: Make this recursive; it's a little tricky because an arbitrary
2336 // number of 'or' instructions might have to be created.
2337 Value *X, *Y;
2338 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2339 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002340 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002341 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002342 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002343 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002344 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002345 }
2346 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2347 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002348 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002349 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002350 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002351 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002352 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002353 }
2354 }
2355
Chris Lattner4e8137d2010-02-11 06:26:33 +00002356 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2357 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel64fc5da2017-09-02 17:53:33 +00002358 if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002359 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002360
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002361 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2362 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002363
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002364 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002365 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002366 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002367 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002368 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002369 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002370 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2371
Owen Andersonc237a842010-09-13 17:59:27 +00002372 // Note: If we've gotten to the point of visiting the outer OR, then the
2373 // inner one couldn't be simplified. If it was a constant, then it won't
2374 // be simplified by a later pass either, so we try swapping the inner/outer
2375 // ORs in the hopes that we'll be able to simplify it this way.
2376 // (X|C) | V --> (X|V) | C
Sanjay Patel099b1a42018-09-01 15:08:59 +00002377 ConstantInt *CI;
Owen Andersonc237a842010-09-13 17:59:27 +00002378 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
Sanjay Patel099b1a42018-09-01 15:08:59 +00002379 match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002380 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002381 Inner->takeName(Op0);
Sanjay Patel099b1a42018-09-01 15:08:59 +00002382 return BinaryOperator::CreateOr(Inner, CI);
Owen Andersonc237a842010-09-13 17:59:27 +00002383 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002384
Bill Wendling23242092013-02-16 23:41:36 +00002385 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2386 // Since this OR statement hasn't been optimized further yet, we hope
2387 // that this transformation will allow the new ORs to be optimized.
2388 {
Craig Topperf40110f2014-04-25 05:29:35 +00002389 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002390 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2391 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2392 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002393 Value *orTrue = Builder.CreateOr(A, C);
2394 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002395 return SelectInst::Create(X, orTrue, orFalse);
2396 }
2397 }
2398
Sanjay Patel70043b72018-07-13 01:18:07 +00002399 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002400}
2401
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002402/// A ^ B can be specified using other logic ops in a variety of patterns. We
2403/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002404static Instruction *foldXorToXor(BinaryOperator &I,
2405 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002406 assert(I.getOpcode() == Instruction::Xor);
2407 Value *Op0 = I.getOperand(0);
2408 Value *Op1 = I.getOperand(1);
2409 Value *A, *B;
2410
2411 // There are 4 commuted variants for each of the basic patterns.
2412
2413 // (A & B) ^ (A | B) -> A ^ B
2414 // (A & B) ^ (B | A) -> A ^ B
2415 // (A | B) ^ (A & B) -> A ^ B
2416 // (A | B) ^ (B & A) -> A ^ B
Roman Lebedev6959b8e2018-04-27 21:23:20 +00002417 if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
2418 m_c_Or(m_Deferred(A), m_Deferred(B))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002419 I.setOperand(0, A);
2420 I.setOperand(1, B);
2421 return &I;
2422 }
2423
2424 // (A | ~B) ^ (~A | B) -> A ^ B
2425 // (~B | A) ^ (~A | B) -> A ^ B
2426 // (~A | B) ^ (A | ~B) -> A ^ B
2427 // (B | ~A) ^ (A | ~B) -> A ^ B
Roman Lebedev6959b8e2018-04-27 21:23:20 +00002428 if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
2429 m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002430 I.setOperand(0, A);
2431 I.setOperand(1, B);
2432 return &I;
2433 }
2434
2435 // (A & ~B) ^ (~A & B) -> A ^ B
2436 // (~B & A) ^ (~A & B) -> A ^ B
2437 // (~A & B) ^ (A & ~B) -> A ^ B
2438 // (B & ~A) ^ (A & ~B) -> A ^ B
Roman Lebedev6959b8e2018-04-27 21:23:20 +00002439 if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
2440 m_c_And(m_Not(m_Deferred(A)), m_Deferred(B))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002441 I.setOperand(0, A);
2442 I.setOperand(1, B);
2443 return &I;
2444 }
2445
Craig Topperf60ab472017-07-02 01:15:51 +00002446 // For the remaining cases we need to get rid of one of the operands.
2447 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2448 return nullptr;
2449
2450 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2451 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2452 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2453 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2454 // Complexity sorting ensures the not will be on the right side.
2455 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2456 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2457 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2458 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2459 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2460
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002461 return nullptr;
2462}
2463
Sanjay Patel5e456b92017-05-18 20:53:16 +00002464Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
Sanjay Patel472652e2018-12-03 15:48:30 +00002465 if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00002466 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2467 LHS->getOperand(1) == RHS->getOperand(0))
2468 LHS->swapOperands();
2469 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2470 LHS->getOperand(1) == RHS->getOperand(1)) {
2471 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2472 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2473 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
Sanjay Patel3d5bb152018-12-04 18:53:27 +00002474 bool IsSigned = LHS->isSigned() || RHS->isSigned();
2475 return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
Sanjay Patel5e456b92017-05-18 20:53:16 +00002476 }
2477 }
2478
Sanjay Patel94c91b72018-03-22 14:08:16 +00002479 // TODO: This can be generalized to compares of non-signbits using
2480 // decomposeBitTestICmp(). It could be enhanced more by using (something like)
2481 // foldLogOpOfMaskedICmps().
2482 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2483 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
2484 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
2485 if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
Amara Emerson070ac762018-08-15 17:46:22 +00002486 LHS0->getType() == RHS0->getType() &&
2487 LHS0->getType()->isIntOrIntVectorTy()) {
Sanjay Patel94c91b72018-03-22 14:08:16 +00002488 // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
2489 // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0
2490 if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2491 PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
2492 (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2493 PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
2494 Value *Zero = ConstantInt::getNullValue(LHS0->getType());
2495 return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
2496 }
2497 // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1
2498 // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1
2499 if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
2500 PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
2501 (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
2502 PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
2503 Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
2504 return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
2505 }
2506 }
2507
Sanjay Pateladca8252017-06-20 12:40:55 +00002508 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2509 // into those logic ops. That is, try to turn this into an and-of-icmps
2510 // because we have many folds for that pattern.
2511 //
2512 // This is based on a truth table definition of xor:
2513 // X ^ Y --> (X | Y) & !(X & Y)
2514 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2515 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2516 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2517 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2518 // TODO: Independently handle cases where the 'and' side is a constant.
2519 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2520 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2521 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002522 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002523 }
2524 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002525 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002526 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002527 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002528 }
2529 }
2530 }
2531
Sanjay Patel5e456b92017-05-18 20:53:16 +00002532 return nullptr;
2533}
2534
Roman Lebedev13686792018-04-28 15:45:07 +00002535/// If we have a masked merge, in the canonical form of:
Roman Lebedevaa4faec2018-04-30 17:59:33 +00002536/// (assuming that A only has one use.)
Roman Lebedev13686792018-04-28 15:45:07 +00002537/// | A | |B|
2538/// ((x ^ y) & M) ^ y
2539/// | D |
2540/// * If M is inverted:
2541/// | D |
2542/// ((x ^ y) & ~M) ^ y
Roman Lebedevaa4faec2018-04-30 17:59:33 +00002543/// We can canonicalize by swapping the final xor operand
2544/// to eliminate the 'not' of the mask.
Roman Lebedev13686792018-04-28 15:45:07 +00002545/// ((x ^ y) & M) ^ x
Roman Lebedevaa4faec2018-04-30 17:59:33 +00002546/// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
2547/// because that shortens the dependency chain and improves analysis:
2548/// (x & M) | (y & ~M)
Roman Lebedev13686792018-04-28 15:45:07 +00002549static Instruction *visitMaskedMerge(BinaryOperator &I,
2550 InstCombiner::BuilderTy &Builder) {
2551 Value *B, *X, *D;
2552 Value *M;
2553 if (!match(&I, m_c_Xor(m_Value(B),
2554 m_OneUse(m_c_And(
2555 m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
2556 m_Value(D)),
2557 m_Value(M))))))
2558 return nullptr;
2559
2560 Value *NotM;
2561 if (match(M, m_Not(m_Value(NotM)))) {
2562 // De-invert the mask and swap the value in B part.
2563 Value *NewA = Builder.CreateAnd(D, NotM);
2564 return BinaryOperator::CreateXor(NewA, X);
2565 }
2566
Roman Lebedevaa4faec2018-04-30 17:59:33 +00002567 Constant *C;
2568 if (D->hasOneUse() && match(M, m_Constant(C))) {
2569 // Unfold.
2570 Value *LHS = Builder.CreateAnd(X, C);
2571 Value *NotC = Builder.CreateNot(C);
2572 Value *RHS = Builder.CreateAnd(B, NotC);
2573 return BinaryOperator::CreateOr(LHS, RHS);
2574 }
2575
Roman Lebedev13686792018-04-28 15:45:07 +00002576 return nullptr;
2577}
2578
Roman Lebedeva6776512018-08-08 13:31:19 +00002579// Transform
2580// ~(x ^ y)
2581// into:
2582// (~x) ^ y
2583// or into
2584// x ^ (~y)
2585static Instruction *sinkNotIntoXor(BinaryOperator &I,
2586 InstCombiner::BuilderTy &Builder) {
2587 Value *X, *Y;
2588 // FIXME: one-use check is not needed in general, but currently we are unable
2589 // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
2590 if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
2591 return nullptr;
2592
2593 // We only want to do the transform if it is free to do.
2594 if (IsFreeToInvert(X, X->hasOneUse())) {
2595 // Ok, good.
2596 } else if (IsFreeToInvert(Y, Y->hasOneUse())) {
2597 std::swap(X, Y);
2598 } else
2599 return nullptr;
2600
2601 Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
2602 return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
2603}
2604
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002605// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2606// here. We should standardize that construct where it is needed or choose some
2607// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002608Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00002609 if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
2610 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002611 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002612
Sanjay Patel70043b72018-07-13 01:18:07 +00002613 if (SimplifyAssociativeOrCommutative(I))
2614 return &I;
2615
Sanjay Patel79dceb22018-10-03 15:20:58 +00002616 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00002617 return X;
2618
Craig Topperbb4069e2017-07-07 23:16:26 +00002619 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002620 return NewXor;
2621
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002622 // (A&B)^(A&C) -> A&(B^C) etc
2623 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002624 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002625
Craig Topper9d4171a2012-12-20 07:09:41 +00002626 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002627 // purpose is to compute bits we don't care about.
2628 if (SimplifyDemandedInstructionBits(I))
2629 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002630
Craig Topper95e41422017-07-06 16:24:23 +00002631 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002632 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002633
Sanjay Patel7b0fc752018-06-21 17:06:36 +00002634 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Craig Topper8bb49212018-08-13 00:38:27 +00002635
2636 // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
Craig Topper8caccc32018-08-13 00:54:23 +00002637 // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
Craig Topper8bb49212018-08-13 00:38:27 +00002638 // calls in there are unnecessary as SimplifyDemandedInstructionBits should
2639 // have already taken care of those cases.
2640 Value *M;
2641 if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
2642 m_c_And(m_Deferred(M), m_Value()))))
Roman Lebedevf84bfb22018-04-15 18:59:44 +00002643 return BinaryOperator::CreateOr(Op0, Op1);
2644
Sanjay Patel6381db12017-05-02 15:31:40 +00002645 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2646 Value *X, *Y;
2647
2648 // We must eliminate the and/or (one-use) for these transforms to not increase
2649 // the instruction count.
2650 // ~(~X & Y) --> (X | ~Y)
2651 // ~(Y & ~X) --> (X | ~Y)
2652 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002653 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002654 return BinaryOperator::CreateOr(X, NotY);
2655 }
2656 // ~(~X | Y) --> (X & ~Y)
2657 // ~(Y | ~X) --> (X & ~Y)
2658 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002659 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002660 return BinaryOperator::CreateAnd(X, NotY);
2661 }
2662
Roman Lebedev13686792018-04-28 15:45:07 +00002663 if (Instruction *Xor = visitMaskedMerge(I, Builder))
2664 return Xor;
2665
Sanjay Patel3b863f82017-04-22 18:05:35 +00002666 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002667 BinaryOperator *NotVal;
2668 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2669 if (NotVal->getOpcode() == Instruction::And ||
2670 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002671 // Apply DeMorgan's Law when inverts are free:
2672 // ~(X & Y) --> (~X | ~Y)
2673 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002674 if (IsFreeToInvert(NotVal->getOperand(0),
2675 NotVal->getOperand(0)->hasOneUse()) &&
2676 IsFreeToInvert(NotVal->getOperand(1),
2677 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002678 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2679 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002680 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002681 return BinaryOperator::CreateOr(NotX, NotY);
2682 return BinaryOperator::CreateAnd(NotX, NotY);
2683 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002684 }
2685
Sanjay Patel78e4b4d2018-07-27 10:54:48 +00002686 // ~(X - Y) --> ~X + Y
Sanjay Patel17e709b2018-09-02 19:31:45 +00002687 if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
2688 if (isa<Constant>(X) || NotVal->hasOneUse())
2689 return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
Sanjay Patel78e4b4d2018-07-27 10:54:48 +00002690
Sanjay Patela1c88142017-05-08 20:49:59 +00002691 // ~(~X >>s Y) --> (X >>s Y)
2692 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2693 return BinaryOperator::CreateAShr(X, Y);
2694
2695 // If we are inverting a right-shifted constant, we may be able to eliminate
2696 // the 'not' by inverting the constant and using the opposite shift type.
2697 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2698 // but we must check that in case that transform has not fired yet.
Sanjay Patel2fe1f622018-09-03 18:40:56 +00002699
2700 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
Simon Pilgrim19495192018-02-10 21:46:09 +00002701 Constant *C;
2702 if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
Sanjay Patel2fe1f622018-09-03 18:40:56 +00002703 match(C, m_Negative()))
2704 return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
Sanjay Patela1c88142017-05-08 20:49:59 +00002705
Sanjay Patel2fe1f622018-09-03 18:40:56 +00002706 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
Simon Pilgrim19495192018-02-10 21:46:09 +00002707 if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
Sanjay Patel2fe1f622018-09-03 18:40:56 +00002708 match(C, m_NonNegative()))
2709 return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
Sanjay Pateld75064e2018-09-03 18:21:59 +00002710
2711 // ~(X + C) --> -(C + 1) - X
2712 if (match(Op0, m_Add(m_Value(X), m_Constant(C))))
2713 return BinaryOperator::CreateSub(ConstantExpr::getNeg(AddOne(C)), X);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002714 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002715
Sanjay Patel93bd15a2018-09-06 16:23:40 +00002716 // Use DeMorgan and reassociation to eliminate a 'not' op.
2717 Constant *C1;
2718 if (match(Op1, m_Constant(C1))) {
2719 Constant *C2;
2720 if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
2721 // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
2722 Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
2723 return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
2724 }
2725 if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
2726 // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
2727 Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
2728 return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
2729 }
2730 }
2731
Craig Topper798a19a2017-06-29 00:07:08 +00002732 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002733 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002734 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002735 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2736 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002737 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002738
Craig Topperb5bf0162017-08-06 06:28:41 +00002739 {
2740 const APInt *RHSC;
2741 if (match(Op1, m_APInt(RHSC))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002742 Value *X;
Craig Topperb5bf0162017-08-06 06:28:41 +00002743 const APInt *C;
Sanjay Patel2fe1f622018-09-03 18:40:56 +00002744 if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X)))) {
2745 // (C - X) ^ signmask -> (C + signmask - X)
2746 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2747 return BinaryOperator::CreateSub(NewC, X);
2748 }
2749 if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C)))) {
2750 // (X + C) ^ signmask -> (X + C + signmask)
2751 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
2752 return BinaryOperator::CreateAdd(X, NewC);
Craig Topperb5bf0162017-08-06 06:28:41 +00002753 }
Craig Topper9a6110b2017-08-10 20:35:34 +00002754
2755 // (X|C1)^C2 -> X^(C1^C2) iff X&~C1 == 0
2756 if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
2757 MaskedValueIsZero(X, *C, 0, &I)) {
2758 Constant *NewC = ConstantInt::get(I.getType(), *C ^ *RHSC);
2759 Worklist.Add(cast<Instruction>(Op0));
2760 I.setOperand(0, X);
2761 I.setOperand(1, NewC);
2762 return &I;
2763 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002764 }
2765 }
2766
Craig Topper9d1821b2017-04-09 06:12:31 +00002767 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002768 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002769 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002770 if (Op0I->getOpcode() == Instruction::LShr) {
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002771 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2772 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002773 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002774 ConstantInt *C1;
2775 if (Op0I->hasOneUse() &&
2776 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2777 E1->getOpcode() == Instruction::Xor &&
2778 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2779 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002780 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002781 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2782 FoldConst ^= C3->getValue();
2783 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002784 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002785 Opnd0->takeName(Op0I);
2786 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2787 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2788
2789 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2790 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002791 }
2792 }
2793 }
Craig Topper86173602017-04-04 20:26:25 +00002794 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002795
Sanjay Patel8fdd87f2018-02-28 16:36:24 +00002796 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2797 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002798
Sanjay Patela89f1832018-09-04 21:00:13 +00002799 // Y ^ (X | Y) --> X & ~Y
2800 // Y ^ (Y | X) --> X & ~Y
2801 if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
2802 return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
2803 // (X | Y) ^ Y --> X & ~Y
2804 // (Y | X) ^ Y --> X & ~Y
2805 if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
2806 return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
Craig Topper9d4171a2012-12-20 07:09:41 +00002807
Sanjay Patela89f1832018-09-04 21:00:13 +00002808 // Y ^ (X & Y) --> ~X & Y
2809 // Y ^ (Y & X) --> ~X & Y
2810 if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
2811 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
2812 // (X & Y) ^ Y --> ~X & Y
2813 // (Y & X) ^ Y --> ~X & Y
Sanjay Patel0f70f862018-09-04 21:17:14 +00002814 // Canonical form is (X & C) ^ C; don't touch that.
Sanjay Patela89f1832018-09-04 21:00:13 +00002815 // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
2816 // be fixed to prefer that (otherwise we get infinite looping).
Sanjay Patel0f70f862018-09-04 21:17:14 +00002817 if (!match(Op1, m_Constant()) &&
Sanjay Patela89f1832018-09-04 21:00:13 +00002818 match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
2819 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
Craig Topper9d4171a2012-12-20 07:09:41 +00002820
Sanjay Patel63cf26c2018-09-04 23:22:13 +00002821 Value *A, *B, *C;
2822 // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
2823 if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
2824 m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
2825 return BinaryOperator::CreateXor(
2826 Builder.CreateAnd(Builder.CreateNot(A), C), B);
2827
2828 // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
2829 if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
2830 m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
2831 return BinaryOperator::CreateXor(
2832 Builder.CreateAnd(Builder.CreateNot(B), C), A);
2833
2834 // (A & B) ^ (A ^ B) -> (A | B)
2835 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2836 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2837 return BinaryOperator::CreateOr(A, B);
2838 // (A ^ B) ^ (A & B) -> (A | B)
2839 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2840 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
2841 return BinaryOperator::CreateOr(A, B);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002842
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002843 // (A & ~B) ^ ~A -> ~(A & B)
2844 // (~B & A) ^ ~A -> ~(A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002845 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002846 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002847 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002848
Sanjay Patel5e456b92017-05-18 20:53:16 +00002849 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2850 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2851 if (Value *V = foldXorOfICmps(LHS, RHS))
2852 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002853
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002854 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2855 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002856
Sanjay Patel3cd1aa82018-06-06 21:58:12 +00002857 // Canonicalize a shifty way to code absolute value to the common pattern.
Sanjay Patel5a0cdac2017-12-16 16:41:17 +00002858 // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
2859 // We're relying on the fact that we only do this transform when the shift has
2860 // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
2861 // instructions).
Craig Topperee99aa42018-03-12 18:46:05 +00002862 if (Op0->hasNUses(2))
Sanjay Patel5a0cdac2017-12-16 16:41:17 +00002863 std::swap(Op0, Op1);
2864
2865 const APInt *ShAmt;
2866 Type *Ty = I.getType();
2867 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
Craig Topperee99aa42018-03-12 18:46:05 +00002868 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
Sanjay Patel5a0cdac2017-12-16 16:41:17 +00002869 match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
2870 // B = ashr i32 A, 31 ; smear the sign bit
2871 // xor (add A, B), B ; add -1 and flip bits if negative
2872 // --> (A < 0) ? -A : A
2873 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
Craig Topperbd332582018-05-17 16:29:52 +00002874 // Copy the nuw/nsw flags from the add to the negate.
2875 auto *Add = cast<BinaryOperator>(Op0);
2876 Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
2877 Add->hasNoSignedWrap());
2878 return SelectInst::Create(Cmp, Neg, A);
Sanjay Patel5a0cdac2017-12-16 16:41:17 +00002879 }
2880
Artur Gainullind9282012018-04-11 10:29:37 +00002881 // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
2882 //
2883 // %notx = xor i32 %x, -1
2884 // %cmp1 = icmp sgt i32 %notx, %y
2885 // %smax = select i1 %cmp1, i32 %notx, i32 %y
2886 // %res = xor i32 %smax, -1
2887 // =>
2888 // %noty = xor i32 %y, -1
2889 // %cmp2 = icmp slt %x, %noty
2890 // %res = select i1 %cmp2, i32 %x, i32 %noty
2891 //
2892 // Same is applicable for smin/umax/umin.
Craig Topper3d8fe392018-08-21 19:17:00 +00002893 if (match(Op1, m_AllOnes()) && Op0->hasOneUse()) {
Artur Gainullind9282012018-04-11 10:29:37 +00002894 Value *LHS, *RHS;
2895 SelectPatternFlavor SPF = matchSelectPattern(Op0, LHS, RHS).Flavor;
Craig Topper3d8fe392018-08-21 19:17:00 +00002896 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topper040c2b02018-09-07 16:19:50 +00002897 // It's possible we get here before the not has been simplified, so make
2898 // sure the input to the not isn't freely invertible.
2899 if (match(LHS, m_Not(m_Value(X))) && !IsFreeToInvert(X, X->hasOneUse())) {
Artur Gainullind9282012018-04-11 10:29:37 +00002900 Value *NotY = Builder.CreateNot(RHS);
2901 return SelectInst::Create(
2902 Builder.CreateICmp(getInverseMinMaxPred(SPF), X, NotY), X, NotY);
2903 }
Craig Topper040c2b02018-09-07 16:19:50 +00002904
2905 // It's possible we get here before the not has been simplified, so make
2906 // sure the input to the not isn't freely invertible.
2907 if (match(RHS, m_Not(m_Value(Y))) && !IsFreeToInvert(Y, Y->hasOneUse())) {
2908 Value *NotX = Builder.CreateNot(LHS);
2909 return SelectInst::Create(
2910 Builder.CreateICmp(getInverseMinMaxPred(SPF), NotX, Y), NotX, Y);
2911 }
Craig Topper8fc05ce2018-09-13 18:52:58 +00002912
2913 // If both sides are freely invertible, then we can get rid of the xor
2914 // completely.
2915 if (IsFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
2916 IsFreeToInvert(RHS, !RHS->hasNUsesOrMore(3))) {
2917 Value *NotLHS = Builder.CreateNot(LHS);
2918 Value *NotRHS = Builder.CreateNot(RHS);
2919 return SelectInst::Create(
2920 Builder.CreateICmp(getInverseMinMaxPred(SPF), NotLHS, NotRHS),
2921 NotLHS, NotRHS);
2922 }
Artur Gainullind9282012018-04-11 10:29:37 +00002923 }
2924 }
2925
Roman Lebedeva6776512018-08-08 13:31:19 +00002926 if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
2927 return NewXor;
2928
Sanjay Patel70043b72018-07-13 01:18:07 +00002929 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002930}