blob: efc508096d261f9bc5f322ddba1daf98b2b223cd [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"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000017#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Intrinsics.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
James Molloyf01488e2016-01-15 09:20:19 +000020#include "llvm/Transforms/Utils/Local.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.
Benjamin Kramerbaba1aa2012-02-06 11:28:19 +000056static Value *getNewICmpValue(bool Sign, unsigned Code, 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;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
60 return NewConstant;
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
Craig Topperfc42ace2017-07-06 16:24:22 +000078/// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
79/// 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).
308/// Return the set of pattern classes (from MaskedICmpType) that both LHS and
309/// RHS satisfy.
310static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
311 Value *&D, Value *&E, ICmpInst *LHS,
312 ICmpInst *RHS,
313 ICmpInst::Predicate &PredL,
314 ICmpInst::Predicate &PredR) {
Craig Topper775ffcc2017-08-21 21:00:45 +0000315 // vectors are not (yet?) supported. Don't support pointers either.
Craig Topperd3b46562017-09-01 21:27:31 +0000316 if (!LHS->getOperand(0)->getType()->isIntegerTy() ||
317 !RHS->getOperand(0)->getType()->isIntegerTy())
Sanjay Patel77bf6222017-04-03 16:53:12 +0000318 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000319
320 // Here comes the tricky part:
Craig Topper9d4171a2012-12-20 07:09:41 +0000321 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
Owen Anderson3fe002d2010-09-08 22:16:17 +0000322 // and L11 & L12 == L21 & L22. The same goes for RHS.
323 // Now we must find those components L** and R**, that are equal, so
Craig Topper9d4171a2012-12-20 07:09:41 +0000324 // that we can extract the parameters A, B, C, D, and E for the canonical
Owen Anderson3fe002d2010-09-08 22:16:17 +0000325 // above.
326 Value *L1 = LHS->getOperand(0);
327 Value *L2 = LHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000328 Value *L11, *L12, *L21, *L22;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000329 // Check whether the icmp can be decomposed into a bit test.
Craig Topper0aa3a192017-08-14 21:39:51 +0000330 if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000331 L21 = L22 = L1 = nullptr;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000332 } else {
333 // Look for ANDs in the LHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000334 if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000335 // Any icmp can be viewed as being trivially masked; if it allows us to
336 // remove one, it's worth it.
337 L11 = L1;
338 L12 = Constant::getAllOnesValue(L1->getType());
339 }
340
Craig Topper775ffcc2017-08-21 21:00:45 +0000341 if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000342 L21 = L2;
343 L22 = Constant::getAllOnesValue(L2->getType());
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000344 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000345 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000346
347 // Bail if LHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000348 if (!ICmpInst::isEquality(PredL))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000349 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000350
351 Value *R1 = RHS->getOperand(0);
352 Value *R2 = RHS->getOperand(1);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000353 Value *R11, *R12;
354 bool Ok = false;
Craig Topper0aa3a192017-08-14 21:39:51 +0000355 if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000356 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000357 A = R11;
358 D = R12;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000359 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000360 A = R12;
361 D = R11;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000362 } else {
363 return 0;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000364 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000365 E = R2;
366 R1 = nullptr;
367 Ok = true;
Craig Topper775ffcc2017-08-21 21:00:45 +0000368 } else {
Tim Northoverdc647a22013-09-04 11:57:17 +0000369 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
370 // As before, model no mask as a trivial mask if it'll let us do an
Mayur Pandey75b76c62014-08-19 06:41:55 +0000371 // optimization.
Tim Northoverdc647a22013-09-04 11:57:17 +0000372 R11 = R1;
373 R12 = Constant::getAllOnesValue(R1->getType());
374 }
375
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000376 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000377 A = R11;
378 D = R12;
379 E = R2;
380 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000381 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000382 A = R12;
383 D = R11;
384 E = R2;
385 Ok = true;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000386 }
387 }
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000388
389 // Bail if RHS was a icmp that can't be decomposed into an equality.
Sanjay Patel77bf6222017-04-03 16:53:12 +0000390 if (!ICmpInst::isEquality(PredR))
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000391 return 0;
392
Chad Rosier58919cc2016-05-09 21:37:43 +0000393 // Look for ANDs on the right side of the RHS icmp.
Craig Topper775ffcc2017-08-21 21:00:45 +0000394 if (!Ok) {
Tim Northoverdc647a22013-09-04 11:57:17 +0000395 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
396 R11 = R2;
397 R12 = Constant::getAllOnesValue(R2->getType());
398 }
399
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000400 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000401 A = R11;
402 D = R12;
403 E = R1;
404 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000405 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000406 A = R12;
407 D = R11;
408 E = R1;
409 Ok = true;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000410 } else {
Owen Anderson3fe002d2010-09-08 22:16:17 +0000411 return 0;
Benjamin Kramerf9d0cc02012-01-09 17:23:27 +0000412 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000413 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000414 if (!Ok)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000415 return 0;
416
417 if (L11 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000418 B = L12;
419 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000420 } else if (L12 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000421 B = L11;
422 C = L2;
Craig Topperae48cb22012-12-20 07:15:54 +0000423 } else if (L21 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000424 B = L22;
425 C = L1;
Craig Topperae48cb22012-12-20 07:15:54 +0000426 } else if (L22 == A) {
Sanjay Patel77bf6222017-04-03 16:53:12 +0000427 B = L21;
428 C = L1;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000429 }
430
Sanjay Patel77bf6222017-04-03 16:53:12 +0000431 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
432 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000433 return LeftType & RightType;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000434}
Sanjay Patel18549272015-09-08 18:24:36 +0000435
436/// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
437/// into a single (icmp(A & X) ==/!= Y).
David Majnemer1a3327b2014-11-18 09:31:36 +0000438static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000439 llvm::InstCombiner::BuilderTy &Builder) {
Craig Topperf40110f2014-04-25 05:29:35 +0000440 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
Sanjay Patel77bf6222017-04-03 16:53:12 +0000441 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
442 unsigned Mask =
443 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
444 if (Mask == 0)
445 return nullptr;
446
447 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
448 "Expected equality predicates for masked type of icmps.");
Owen Anderson3fe002d2010-09-08 22:16:17 +0000449
Tim Northoverc0756c42013-09-04 11:57:13 +0000450 // In full generality:
451 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
452 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
453 //
454 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
455 // equivalent to (icmp (A & X) !Op Y).
456 //
457 // Therefore, we can pretend for the rest of this function that we're dealing
458 // with the conjunction, provided we flip the sense of any comparisons (both
459 // input and output).
460
461 // In most cases we're going to produce an EQ for the "&&" case.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000462 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Tim Northoverc0756c42013-09-04 11:57:13 +0000463 if (!IsAnd) {
464 // Convert the masking analysis into its equivalent with negated
465 // comparisons.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000466 Mask = conjugateICmpMask(Mask);
Tim Northoverc0756c42013-09-04 11:57:13 +0000467 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000468
Sanjay Patel77bf6222017-04-03 16:53:12 +0000469 if (Mask & Mask_AllZeros) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000470 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000471 // -> (icmp eq (A & (B|D)), 0)
Craig Topperbb4069e2017-07-07 23:16:26 +0000472 Value *NewOr = Builder.CreateOr(B, D);
473 Value *NewAnd = Builder.CreateAnd(A, NewOr);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000474 // We can't use C as zero because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000475 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000476 // with B and D, having a single bit set.
477 Value *Zero = Constant::getNullValue(A->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +0000478 return Builder.CreateICmp(NewCC, NewAnd, Zero);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000479 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000480 if (Mask & BMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000481 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000482 // -> (icmp eq (A & (B|D)), (B|D))
Craig Topperbb4069e2017-07-07 23:16:26 +0000483 Value *NewOr = Builder.CreateOr(B, D);
484 Value *NewAnd = Builder.CreateAnd(A, NewOr);
485 return Builder.CreateICmp(NewCC, NewAnd, NewOr);
Craig Topper9d4171a2012-12-20 07:09:41 +0000486 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000487 if (Mask & AMask_AllOnes) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000488 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000489 // -> (icmp eq (A & (B&D)), A)
Craig Topperbb4069e2017-07-07 23:16:26 +0000490 Value *NewAnd1 = Builder.CreateAnd(B, D);
491 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
492 return Builder.CreateICmp(NewCC, NewAnd2, A);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000493 }
Tim Northoverc0756c42013-09-04 11:57:13 +0000494
495 // Remaining cases assume at least that B and D are constant, and depend on
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000496 // their actual values. This isn't strictly necessary, just a "handle the
Tim Northoverc0756c42013-09-04 11:57:13 +0000497 // easy cases for now" decision.
498 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000499 if (!BCst)
500 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000501 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000502 if (!DCst)
503 return nullptr;
Tim Northoverc0756c42013-09-04 11:57:13 +0000504
Sanjay Patel77bf6222017-04-03 16:53:12 +0000505 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000506 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
507 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
508 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
509 // Only valid if one of the masks is a superset of the other (check "B&D" is
510 // the same as either B or D).
511 APInt NewMask = BCst->getValue() & DCst->getValue();
512
513 if (NewMask == BCst->getValue())
514 return LHS;
515 else if (NewMask == DCst->getValue())
516 return RHS;
517 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000518
519 if (Mask & AMask_NotAllOnes) {
Tim Northoverc0756c42013-09-04 11:57:13 +0000520 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
521 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
522 // Only valid if one of the masks is a superset of the other (check "B|D" is
523 // the same as either B or D).
524 APInt NewMask = BCst->getValue() | DCst->getValue();
525
526 if (NewMask == BCst->getValue())
527 return LHS;
528 else if (NewMask == DCst->getValue())
529 return RHS;
530 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000531
532 if (Mask & BMask_Mixed) {
Craig Topper9d4171a2012-12-20 07:09:41 +0000533 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
Owen Anderson3fe002d2010-09-08 22:16:17 +0000534 // We already know that B & C == C && D & E == E.
535 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
536 // C and E, which are shared by both the mask B and the mask D, don't
537 // contradict, then we can transform to
538 // -> (icmp eq (A & (B|D)), (C|E))
539 // Currently, we only handle the case of B, C, D, and E being constant.
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000540 // We can't simply use C and E because we might actually handle
Craig Topper9d4171a2012-12-20 07:09:41 +0000541 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000542 // with B and D, having a single bit set.
Owen Anderson3fe002d2010-09-08 22:16:17 +0000543 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000544 if (!CCst)
545 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000546 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000547 if (!ECst)
548 return nullptr;
549 if (PredL != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000550 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000551 if (PredR != NewCC)
David Majnemer1a3327b2014-11-18 09:31:36 +0000552 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
Sanjay Patel77bf6222017-04-03 16:53:12 +0000553
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000554 // If there is a conflict, we should actually return a false for the
555 // whole construct.
David Majnemer1a3327b2014-11-18 09:31:36 +0000556 if (((BCst->getValue() & DCst->getValue()) &
Craig Topper73ba1c82017-06-07 07:40:37 +0000557 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
David Majnemer6fdb6b82014-11-18 09:31:41 +0000558 return ConstantInt::get(LHS->getType(), !IsAnd);
Sanjay Patel77bf6222017-04-03 16:53:12 +0000559
Craig Topperbb4069e2017-07-07 23:16:26 +0000560 Value *NewOr1 = Builder.CreateOr(B, D);
Sanjay Patel3b8dcc72016-01-18 18:28:09 +0000561 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
Craig Topperbb4069e2017-07-07 23:16:26 +0000562 Value *NewAnd = Builder.CreateAnd(A, NewOr1);
563 return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
Owen Anderson3fe002d2010-09-08 22:16:17 +0000564 }
Sanjay Patel77bf6222017-04-03 16:53:12 +0000565
Craig Topperf40110f2014-04-25 05:29:35 +0000566 return nullptr;
Owen Anderson3fe002d2010-09-08 22:16:17 +0000567}
568
Erik Ecksteind1817522014-12-03 10:39:15 +0000569/// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
570/// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
571/// If \p Inverted is true then the check is for the inverted range, e.g.
572/// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
573Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
574 bool Inverted) {
575 // Check the lower range comparison, e.g. x >= 0
576 // InstCombine already ensured that if there is a constant it's on the RHS.
577 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
578 if (!RangeStart)
579 return nullptr;
580
581 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
582 Cmp0->getPredicate());
583
584 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
585 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
586 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
587 return nullptr;
588
589 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
590 Cmp1->getPredicate());
591
592 Value *Input = Cmp0->getOperand(0);
593 Value *RangeEnd;
594 if (Cmp1->getOperand(0) == Input) {
595 // For the upper range compare we have: icmp x, n
596 RangeEnd = Cmp1->getOperand(1);
597 } else if (Cmp1->getOperand(1) == Input) {
598 // For the upper range compare we have: icmp n, x
599 RangeEnd = Cmp1->getOperand(0);
600 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
601 } else {
602 return nullptr;
603 }
604
605 // Check the upper range comparison, e.g. x < n
606 ICmpInst::Predicate NewPred;
607 switch (Pred1) {
608 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
609 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
610 default: return nullptr;
611 }
612
613 // This simplification is only valid if the upper range is not negative.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000614 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
615 if (!Known.isNonNegative())
Erik Ecksteind1817522014-12-03 10:39:15 +0000616 return nullptr;
617
618 if (Inverted)
619 NewPred = ICmpInst::getInversePredicate(NewPred);
620
Craig Topperbb4069e2017-07-07 23:16:26 +0000621 return Builder.CreateICmp(NewPred, Input, RangeEnd);
Erik Ecksteind1817522014-12-03 10:39:15 +0000622}
623
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000624static Value *
625foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
626 bool JoinedByAnd,
Craig Topperbb4069e2017-07-07 23:16:26 +0000627 InstCombiner::BuilderTy &Builder) {
Sanjay Patelef9f5862017-04-15 17:55:06 +0000628 Value *X = LHS->getOperand(0);
629 if (X != RHS->getOperand(0))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000630 return nullptr;
631
Sanjay Patelef9f5862017-04-15 17:55:06 +0000632 const APInt *C1, *C2;
633 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
634 !match(RHS->getOperand(1), m_APInt(C2)))
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000635 return nullptr;
636
637 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
638 ICmpInst::Predicate Pred = LHS->getPredicate();
639 if (Pred != RHS->getPredicate())
640 return nullptr;
641 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
642 return nullptr;
643 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
644 return nullptr;
645
646 // The larger unsigned constant goes on the right.
Sanjay Patelef9f5862017-04-15 17:55:06 +0000647 if (C1->ugt(*C2))
648 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000649
Sanjay Patelef9f5862017-04-15 17:55:06 +0000650 APInt Xor = *C1 ^ *C2;
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000651 if (Xor.isPowerOf2()) {
652 // If LHSC and RHSC differ by only one bit, then set that bit in X and
653 // compare against the larger constant:
654 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
655 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
656 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
657 // 'and' because that may lead to smaller codegen from a smaller constant.
Craig Topperbb4069e2017-07-07 23:16:26 +0000658 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
659 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000660 }
661
662 // Special case: get the ordering right when the values wrap around zero.
663 // Ie, we assumed the constants were unsigned when swapping earlier.
Craig Topper73ba1c82017-06-07 07:40:37 +0000664 if (C1->isNullValue() && C2->isAllOnesValue())
Sanjay Patelef9f5862017-04-15 17:55:06 +0000665 std::swap(C1, C2);
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000666
Sanjay Patelef9f5862017-04-15 17:55:06 +0000667 if (*C1 == *C2 - 1) {
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000668 // (X == 13 || X == 14) --> X - 13 <=u 1
669 // (X != 13 && X != 14) --> X - 13 >u 1
670 // An 'add' is the canonical IR form, so favor that over a 'sub'.
Craig Topperbb4069e2017-07-07 23:16:26 +0000671 Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000672 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000673 return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000674 }
675
676 return nullptr;
677}
678
Craig Topperda6ea0d2017-06-16 05:10:37 +0000679// Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
680// Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
681Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
682 bool JoinedByAnd,
683 Instruction &CxtI) {
684 ICmpInst::Predicate Pred = LHS->getPredicate();
685 if (Pred != RHS->getPredicate())
686 return nullptr;
687 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
688 return nullptr;
689 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
690 return nullptr;
691
692 // TODO support vector splats
693 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
694 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
695 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
696 return nullptr;
697
698 Value *A, *B, *C, *D;
699 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
700 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
701 if (A == D || B == D)
702 std::swap(C, D);
703 if (B == C)
704 std::swap(A, B);
705
706 if (A == C &&
707 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
708 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000709 Value *Mask = Builder.CreateOr(B, D);
710 Value *Masked = Builder.CreateAnd(A, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000711 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
Craig Topperbb4069e2017-07-07 23:16:26 +0000712 return Builder.CreateICmp(NewPred, Masked, Mask);
Craig Topperda6ea0d2017-06-16 05:10:37 +0000713 }
714 }
715
716 return nullptr;
717}
718
Sanjay Patel18549272015-09-08 18:24:36 +0000719/// Fold (icmp)&(icmp) if possible.
Craig Topperda6ea0d2017-06-16 05:10:37 +0000720Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
721 Instruction &CxtI) {
722 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
723 // if K1 and K2 are a one-bit mask.
724 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
725 return V;
726
Sanjay Patel519a87a2017-04-05 17:38:34 +0000727 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Chris Lattner0a8191e2010-01-05 07:50:36 +0000728
729 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000730 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000731 if (LHS->getOperand(0) == RHS->getOperand(1) &&
732 LHS->getOperand(1) == RHS->getOperand(0))
733 LHS->swapOperands();
734 if (LHS->getOperand(0) == RHS->getOperand(0) &&
735 LHS->getOperand(1) == RHS->getOperand(1)) {
736 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
737 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
738 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +0000739 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000740 }
741 }
Owen Anderson3fe002d2010-09-08 22:16:17 +0000742
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000743 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +0000744 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
Chris Lattnerdcef03f2011-02-10 05:17:27 +0000745 return V;
Craig Topper9d4171a2012-12-20 07:09:41 +0000746
Erik Ecksteind1817522014-12-03 10:39:15 +0000747 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
748 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
749 return V;
750
751 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
752 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
753 return V;
754
Sanjay Patelef9f5862017-04-15 17:55:06 +0000755 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
756 return V;
757
Chris Lattner0a8191e2010-01-05 07:50:36 +0000758 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Sanjay Patele4159d22017-04-10 19:38:36 +0000759 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000760 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
761 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
762 if (!LHSC || !RHSC)
763 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000764
Sanjay Patel519a87a2017-04-05 17:38:34 +0000765 if (LHSC == RHSC && PredL == PredR) {
Chris Lattner0a8191e2010-01-05 07:50:36 +0000766 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
Sanjay Patelc2ceb8b2016-01-18 19:17:58 +0000767 // where C is a power of 2 or
Chris Lattner0a8191e2010-01-05 07:50:36 +0000768 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000769 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
770 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000771 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
772 return Builder.CreateICmp(PredL, NewOr, LHSC);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000773 }
774 }
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000775
Benjamin Kramer101720f2011-04-28 20:09:57 +0000776 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000777 // where CMAX is the all ones value for the truncated type,
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000778 // iff the lower bits of C2 and CA are zero.
Sanjay Patel519a87a2017-04-05 17:38:34 +0000779 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
780 RHS->hasOneUse()) {
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000781 Value *V;
Sanjay Patel519a87a2017-04-05 17:38:34 +0000782 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000783
784 // (trunc x) == C1 & (and x, CA) == C2
Craig Topperae48cb22012-12-20 07:15:54 +0000785 // (and x, CA) == C2 & (trunc x) == C1
Sanjay Patele4159d22017-04-10 19:38:36 +0000786 if (match(RHS0, m_Trunc(m_Value(V))) &&
787 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000788 SmallC = RHSC;
789 BigC = LHSC;
Sanjay Patele4159d22017-04-10 19:38:36 +0000790 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
791 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
Sanjay Patel519a87a2017-04-05 17:38:34 +0000792 SmallC = LHSC;
793 BigC = RHSC;
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000794 }
795
Sanjay Patel519a87a2017-04-05 17:38:34 +0000796 if (SmallC && BigC) {
797 unsigned BigBitSize = BigC->getType()->getBitWidth();
798 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000799
800 // Check that the low bits are zero.
801 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
Craig Topper73ba1c82017-06-07 07:40:37 +0000802 if ((Low & AndC->getValue()).isNullValue() &&
803 (Low & BigC->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000804 Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
Sanjay Patel519a87a2017-04-05 17:38:34 +0000805 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
806 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
Craig Topperbb4069e2017-07-07 23:16:26 +0000807 return Builder.CreateICmp(PredL, NewAnd, NewVal);
Benjamin Kramer4145c0d2011-04-28 16:58:40 +0000808 }
809 }
810 }
Benjamin Kramerda37e152012-01-08 18:32:24 +0000811
Chris Lattner0a8191e2010-01-05 07:50:36 +0000812 // From here on, we only handle:
813 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +0000814 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +0000815 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000816
Sanjay Patel519a87a2017-04-05 17:38:34 +0000817 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
818 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
819 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
820 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
821 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Anders Carlssonda80afe2011-03-01 15:05:01 +0000823
Chris Lattner0a8191e2010-01-05 07:50:36 +0000824 // We can't fold (ugt x, C) & (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +0000825 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +0000826 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +0000827
Chris Lattner0a8191e2010-01-05 07:50:36 +0000828 // Ensure that the larger constant is on the RHS.
829 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +0000830 if (CmpInst::isSigned(PredL) ||
831 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +0000832 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +0000833 else
834 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +0000835
Chris Lattner0a8191e2010-01-05 07:50:36 +0000836 if (ShouldSwap) {
837 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000838 std::swap(LHSC, RHSC);
839 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000840 }
841
Dan Gohman4a618822010-02-10 16:03:48 +0000842 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +0000843 // comparing a value against two constants and and'ing the result
844 // together. Because of the above check, we know that we only have
Craig Topper9d4171a2012-12-20 07:09:41 +0000845 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
846 // (from the icmp folding check above), that the two constants
Chris Lattner0a8191e2010-01-05 07:50:36 +0000847 // are not equal and that the larger constant is on the RHS
Sanjay Patel519a87a2017-04-05 17:38:34 +0000848 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000849
Sanjay Patel519a87a2017-04-05 17:38:34 +0000850 switch (PredL) {
851 default:
852 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000853 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000854 switch (PredR) {
855 default:
856 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000857 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000858 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000859 return Builder.CreateICmpULT(LHS0, LHSC);
Craig Topper79ab6432017-07-06 18:39:47 +0000860 if (LHSC->isZero()) // (X != 0 & X u< 14) -> X-1 u< 13
Sanjay Patele4159d22017-04-10 19:38:36 +0000861 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
Sanjay Patel85d79742016-08-31 19:49:56 +0000862 false, true);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000863 break; // (X != 13 & X u< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000864 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000865 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
Craig Topperbb4069e2017-07-07 23:16:26 +0000866 return Builder.CreateICmpSLT(LHS0, LHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000867 break; // (X != 13 & X s< 15) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +0000868 case ICmpInst::ICMP_NE:
Sanjay Patel7cfe4162017-04-14 19:23:50 +0000869 // Potential folds for this case should already be handled.
870 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000871 }
872 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000873 case ICmpInst::ICMP_UGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000874 switch (PredR) {
875 default:
876 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000877 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000878 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000879 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000880 break; // (X u> 13 & X != 15) -> no change
881 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000882 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
883 false, true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000884 }
885 break;
886 case ICmpInst::ICMP_SGT:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000887 switch (PredR) {
888 default:
889 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +0000890 case ICmpInst::ICMP_NE:
Sanjay Patel519a87a2017-04-05 17:38:34 +0000891 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
Craig Topperbb4069e2017-07-07 23:16:26 +0000892 return Builder.CreateICmp(PredL, LHS0, RHSC);
Sanjay Patel519a87a2017-04-05 17:38:34 +0000893 break; // (X s> 13 & X != 15) -> no change
894 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Sanjay Patele4159d22017-04-10 19:38:36 +0000895 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
Sanjay Patel519a87a2017-04-05 17:38:34 +0000896 true);
Chris Lattner0a8191e2010-01-05 07:50:36 +0000897 }
898 break;
899 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000900
Craig Topperf40110f2014-04-25 05:29:35 +0000901 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000902}
903
Sanjay Patel18549272015-09-08 18:24:36 +0000904/// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
905/// a Value which should already be inserted into the function.
Sanjay Patel5e456b92017-05-18 20:53:16 +0000906Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
Tim Shenaec68b22016-06-29 20:10:17 +0000907 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
908 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
909 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
910
911 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
912 // Swap RHS operands to match LHS.
913 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
914 std::swap(Op1LHS, Op1RHS);
915 }
916
917 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
918 // Suppose the relation between x and y is R, where R is one of
919 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
920 // testing the desired relations.
921 //
922 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
923 // bool(R & CC0) && bool(R & CC1)
924 // = bool((R & CC0) & (R & CC1))
925 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
926 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
927 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
928 Builder);
929
Chris Lattner0a8191e2010-01-05 07:50:36 +0000930 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
931 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
Benjamin Kramere89c7052013-04-12 21:56:23 +0000932 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
Craig Topperf40110f2014-04-25 05:29:35 +0000933 return nullptr;
Benjamin Kramere89c7052013-04-12 21:56:23 +0000934
Chris Lattner0a8191e2010-01-05 07:50:36 +0000935 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
936 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
937 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
938 // If either of the constants are nans, then the whole thing returns
939 // false.
940 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Craig Topperbb4069e2017-07-07 23:16:26 +0000941 return Builder.getFalse();
942 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000943 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000944
Chris Lattner0a8191e2010-01-05 07:50:36 +0000945 // Handle vector zeros. This occurs because the canonical form of
946 // "fcmp ord x,x" is "fcmp ord x, 0".
947 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
948 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Craig Topperbb4069e2017-07-07 23:16:26 +0000949 return Builder.CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner0a8191e2010-01-05 07:50:36 +0000950 }
Craig Topper9d4171a2012-12-20 07:09:41 +0000951
Craig Topperf40110f2014-04-25 05:29:35 +0000952 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +0000953}
954
Sanjay Patel4c52f762017-09-02 16:30:27 +0000955/// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
956/// a Value which should already be inserted into the function.
957Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
958 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
959 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
960 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
961
962 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
963 // Swap RHS operands to match LHS.
964 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
965 std::swap(Op1LHS, Op1RHS);
966 }
967
968 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
969 // This is a similar transformation to the one in FoldAndOfFCmps.
970 //
971 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
972 // bool(R & CC0) || bool(R & CC1)
973 // = bool((R & CC0) | (R & CC1))
974 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
975 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
976 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
977 Builder);
978
979 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
980 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
981 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
982 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
983 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
984 // If either of the constants are nans, then the whole thing returns
985 // true.
986 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
987 return Builder.getTrue();
988
989 // Otherwise, no need to compare the two constants, compare the
990 // rest.
991 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
992 }
993
994 // Handle vector zeros. This occurs because the canonical form of
995 // "fcmp uno x,x" is "fcmp uno x, 0".
996 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
997 isa<ConstantAggregateZero>(RHS->getOperand(1)))
998 return Builder.CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
Sanjay Patel4c52f762017-09-02 16:30:27 +0000999 }
1000
1001 return nullptr;
1002}
1003
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001004/// Match De Morgan's Laws:
1005/// (~A & ~B) == (~(A | B))
1006/// (~A | ~B) == (~(A & B))
1007static Instruction *matchDeMorgansLaws(BinaryOperator &I,
Sanjay Patel7caaa792017-05-09 20:05:05 +00001008 InstCombiner::BuilderTy &Builder) {
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001009 auto Opcode = I.getOpcode();
1010 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1011 "Trying to match De Morgan's Laws with something other than and/or");
1012
Sanjay Patel7caaa792017-05-09 20:05:05 +00001013 // Flip the logic operation.
1014 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1015
1016 Value *A, *B;
1017 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1018 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1019 !IsFreeToInvert(A, A->hasOneUse()) &&
1020 !IsFreeToInvert(B, B->hasOneUse())) {
1021 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1022 return BinaryOperator::CreateNot(AndOr);
1023 }
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001024
1025 return nullptr;
1026}
1027
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001028bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1029 Value *CastSrc = CI->getOperand(0);
1030
1031 // Noop casts and casts of constants should be eliminated trivially.
1032 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1033 return false;
1034
1035 // If this cast is paired with another cast that can be eliminated, we prefer
1036 // to have it eliminated.
1037 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1038 if (isEliminableCastPair(PrecedingCI, CI))
1039 return false;
1040
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001041 return true;
1042}
1043
Sanjay Patel60312bc42016-09-12 00:16:23 +00001044/// Fold {and,or,xor} (cast X), C.
1045static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
Craig Topperbb4069e2017-07-07 23:16:26 +00001046 InstCombiner::BuilderTy &Builder) {
Craig Topper5706c012017-08-09 06:17:48 +00001047 Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1048 if (!C)
Sanjay Patel60312bc42016-09-12 00:16:23 +00001049 return nullptr;
1050
1051 auto LogicOpc = Logic.getOpcode();
1052 Type *DestTy = Logic.getType();
1053 Type *SrcTy = Cast->getSrcTy();
1054
Craig Topperae9b87d2017-08-02 20:25:56 +00001055 // Move the logic operation ahead of a zext or sext if the constant is
1056 // unchanged in the smaller source type. Performing the logic in a smaller
1057 // type may provide more information to later folds, and the smaller logic
1058 // instruction may be cheaper (particularly in the case of vectors).
Sanjay Patel60312bc42016-09-12 00:16:23 +00001059 Value *X;
Sanjay Patel60312bc42016-09-12 00:16:23 +00001060 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1061 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1062 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1063 if (ZextTruncC == C) {
1064 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
Craig Topperbb4069e2017-07-07 23:16:26 +00001065 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
Sanjay Patel60312bc42016-09-12 00:16:23 +00001066 return new ZExtInst(NewOp, DestTy);
1067 }
1068 }
1069
Craig Topperae9b87d2017-08-02 20:25:56 +00001070 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1071 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1072 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1073 if (SextTruncC == C) {
1074 // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1075 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1076 return new SExtInst(NewOp, DestTy);
1077 }
1078 }
1079
Sanjay Patel60312bc42016-09-12 00:16:23 +00001080 return nullptr;
1081}
1082
1083/// Fold {and,or,xor} (cast X), Y.
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001084Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001085 auto LogicOpc = I.getOpcode();
Sanjay Patel1e6ca442016-11-22 22:54:36 +00001086 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001087
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001088 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001089 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
Sanjay Patel9bba7502016-03-03 19:19:04 +00001090 if (!Cast0)
Sanjay Patel7d0d8102016-02-23 16:59:21 +00001091 return nullptr;
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001092
Sanjay Patel9bba7502016-03-03 19:19:04 +00001093 // This must be a cast from an integer or integer vector source type to allow
1094 // transformation of the logic operation to the source type.
1095 Type *DestTy = I.getType();
Sanjay Patel713f25e2016-02-23 17:41:34 +00001096 Type *SrcTy = Cast0->getSrcTy();
Sanjay Patel9bba7502016-03-03 19:19:04 +00001097 if (!SrcTy->isIntOrIntVectorTy())
1098 return nullptr;
1099
Sanjay Patel60312bc42016-09-12 00:16:23 +00001100 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1101 return Ret;
Sanjay Patel0753c062016-07-21 00:24:18 +00001102
Sanjay Patel9bba7502016-03-03 19:19:04 +00001103 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1104 if (!Cast1)
1105 return nullptr;
1106
1107 // Both operands of the logic operation are casts. The casts must be of the
1108 // same type for reduction.
1109 auto CastOpcode = Cast0->getOpcode();
1110 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
Sanjay Patel713f25e2016-02-23 17:41:34 +00001111 return nullptr;
1112
1113 Value *Cast0Src = Cast0->getOperand(0);
1114 Value *Cast1Src = Cast1->getOperand(0);
Sanjay Patel713f25e2016-02-23 17:41:34 +00001115
Tobias Grosser8ef834c2016-07-19 09:06:08 +00001116 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
Tobias Grosser8757e382016-08-03 19:30:35 +00001117 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001118 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001119 I.getName());
Sanjay Patel713f25e2016-02-23 17:41:34 +00001120 return CastInst::Create(CastOpcode, NewOp, DestTy);
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001121 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001122
Sanjay Pateldbbaca02016-02-24 17:00:34 +00001123 // For now, only 'and'/'or' have optimizations after this.
1124 if (LogicOpc == Instruction::Xor)
1125 return nullptr;
1126
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001127 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001128 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001129 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1130 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1131 if (ICmp0 && ICmp1) {
Craig Topperda6ea0d2017-06-16 05:10:37 +00001132 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001133 : foldOrOfICmps(ICmp0, ICmp1, I);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001134 if (Res)
1135 return CastInst::Create(CastOpcode, Res, DestTy);
1136 return nullptr;
1137 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001138
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001139 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
Sanjay Patel713f25e2016-02-23 17:41:34 +00001140 // cast is otherwise not optimizable. This happens for vector sexts.
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001141 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1142 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1143 if (FCmp0 && FCmp1) {
Sanjay Patel5e456b92017-05-18 20:53:16 +00001144 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1145 : foldOrOfFCmps(FCmp0, FCmp1);
Sanjay Patel75b4ae22016-02-23 23:56:23 +00001146 if (Res)
1147 return CastInst::Create(CastOpcode, Res, DestTy);
1148 return nullptr;
1149 }
Sanjay Patel713f25e2016-02-23 17:41:34 +00001150
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001151 return nullptr;
1152}
1153
Sanjay Patele0c26e02017-04-23 22:00:02 +00001154static Instruction *foldAndToXor(BinaryOperator &I,
1155 InstCombiner::BuilderTy &Builder) {
1156 assert(I.getOpcode() == Instruction::And);
1157 Value *Op0 = I.getOperand(0);
1158 Value *Op1 = I.getOperand(1);
1159 Value *A, *B;
1160
1161 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1162 // (A | B) & ~(A & B) --> A ^ B
1163 // (A | B) & ~(B & A) --> A ^ B
1164 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1165 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1166 return BinaryOperator::CreateXor(A, B);
1167
1168 // (A | ~B) & (~A | B) --> ~(A ^ B)
1169 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1170 // (~B | A) & (~A | B) --> ~(A ^ B)
1171 // (~B | A) & (B | ~A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001172 if (Op0->hasOneUse() || Op1->hasOneUse())
1173 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1174 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1175 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001176
1177 return nullptr;
1178}
1179
1180static Instruction *foldOrToXor(BinaryOperator &I,
1181 InstCombiner::BuilderTy &Builder) {
1182 assert(I.getOpcode() == Instruction::Or);
1183 Value *Op0 = I.getOperand(0);
1184 Value *Op1 = I.getOperand(1);
1185 Value *A, *B;
1186
1187 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1188 // (A & B) | ~(A | B) --> ~(A ^ B)
1189 // (A & B) | ~(B | A) --> ~(A ^ B)
Craig Topper0de5e6a2017-06-22 16:12:02 +00001190 if (Op0->hasOneUse() || Op1->hasOneUse())
1191 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1192 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1193 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
Sanjay Patele0c26e02017-04-23 22:00:02 +00001194
1195 // (A & ~B) | (~A & B) --> A ^ B
1196 // (A & ~B) | (B & ~A) --> A ^ B
1197 // (~B & A) | (~A & B) --> A ^ B
1198 // (~B & A) | (B & ~A) --> A ^ B
1199 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1200 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1201 return BinaryOperator::CreateXor(A, B);
1202
1203 return nullptr;
1204}
1205
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001206// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1207// here. We should standardize that construct where it is needed or choose some
1208// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001209Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001210 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1212
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001213 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001214 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001215
Craig Toppera4205622017-06-09 03:21:29 +00001216 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001217 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001218
Craig Topper9d4171a2012-12-20 07:09:41 +00001219 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001220 // purpose is to compute bits we don't care about.
1221 if (SimplifyDemandedInstructionBits(I))
Craig Topper9d4171a2012-12-20 07:09:41 +00001222 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001223
Sanjay Patele0c26e02017-04-23 22:00:02 +00001224 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001225 if (Instruction *Xor = foldAndToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001226 return Xor;
1227
1228 // (A|B)&(A|C) -> A|(B&C) etc
1229 if (Value *V = SimplifyUsingDistributiveLaws(I))
1230 return replaceInstUsesWith(I, V);
1231
Craig Topper95e41422017-07-06 16:24:23 +00001232 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001233 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001234
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001235 const APInt *C;
1236 if (match(Op1, m_APInt(C))) {
1237 Value *X, *Y;
1238 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1239 C->isOneValue()) {
1240 // (1 << X) & 1 --> zext(X == 0)
1241 // (1 >> X) & 1 --> zext(X == 0)
Sanjay Patel3437ee22017-07-15 17:26:01 +00001242 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(I.getType(), 0));
1243 return new ZExtInst(IsZero, I.getType());
1244 }
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001245
Craig Toppera1693a22017-08-06 23:11:49 +00001246 const APInt *XorC;
1247 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1248 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1249 Constant *NewC = ConstantInt::get(I.getType(), *C & *XorC);
1250 Value *And = Builder.CreateAnd(X, Op1);
1251 And->takeName(Op0);
1252 return BinaryOperator::CreateXor(And, NewC);
1253 }
1254
Craig Topper7091a742017-08-07 18:10:39 +00001255 const APInt *OrC;
1256 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1257 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1258 // NOTE: This reduces the number of bits set in the & mask, which
1259 // can expose opportunities for store narrowing for scalars.
1260 // NOTE: SimplifyDemandedBits should have already removed bits from C1
1261 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1262 // above, but this feels safer.
1263 APInt Together = *C & *OrC;
1264 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(),
1265 Together ^ *C));
1266 And->takeName(Op0);
1267 return BinaryOperator::CreateOr(And, ConstantInt::get(I.getType(),
1268 Together));
1269 }
1270
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001271 // If the mask is only needed on one incoming arm, push the 'and' op up.
1272 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1273 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1274 APInt NotAndMask(~(*C));
1275 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1276 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1277 // Not masking anything out for the LHS, move mask to RHS.
1278 // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1279 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1280 return BinaryOperator::Create(BinOp, X, NewRHS);
1281 }
1282 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1283 // Not masking anything out for the RHS, move mask to LHS.
1284 // and ({x}or X, Y), C --> {x}or (and X, C), Y
1285 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1286 return BinaryOperator::Create(BinOp, NewLHS, Y);
1287 }
1288 }
Craig Toppera1693a22017-08-06 23:11:49 +00001289
Sanjay Patel3437ee22017-07-15 17:26:01 +00001290 }
Sanjay Patel55b9f882017-07-15 15:29:47 +00001291
Chris Lattner0a8191e2010-01-05 07:50:36 +00001292 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1293 const APInt &AndRHSMask = AndRHS->getValue();
Chris Lattner0a8191e2010-01-05 07:50:36 +00001294
1295 // Optimize a variety of ((val OP C1) & C2) combinations...
1296 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
David Majnemerde55c602017-01-17 18:08:06 +00001297 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1298 // of X and OP behaves well when given trunc(C1) and X.
1299 switch (Op0I->getOpcode()) {
1300 default:
1301 break;
1302 case Instruction::Xor:
1303 case Instruction::Or:
1304 case Instruction::Mul:
1305 case Instruction::Add:
1306 case Instruction::Sub:
1307 Value *X;
1308 ConstantInt *C1;
Craig Topperb5194ee2017-04-12 05:49:28 +00001309 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
David Majnemerde55c602017-01-17 18:08:06 +00001310 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1311 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1312 Value *BinOp;
Sanjay Pateldac0ab22017-07-31 21:01:53 +00001313 Value *Op0LHS = Op0I->getOperand(0);
David Majnemerde55c602017-01-17 18:08:06 +00001314 if (isa<ZExtInst>(Op0LHS))
Craig Topperbb4069e2017-07-07 23:16:26 +00001315 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), X, TruncC1);
David Majnemerde55c602017-01-17 18:08:06 +00001316 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001317 BinOp = Builder.CreateBinOp(Op0I->getOpcode(), TruncC1, X);
David Majnemerde55c602017-01-17 18:08:06 +00001318 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
Craig Topperbb4069e2017-07-07 23:16:26 +00001319 auto *And = Builder.CreateAnd(BinOp, TruncC2);
David Majnemerde55c602017-01-17 18:08:06 +00001320 return new ZExtInst(And, I.getType());
1321 }
1322 }
1323 }
1324
Chris Lattner0a8191e2010-01-05 07:50:36 +00001325 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1326 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1327 return Res;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001328 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001329
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001330 // If this is an integer truncation, and if the source is an 'and' with
1331 // immediate, transform it. This frequently occurs for bitfield accesses.
1332 {
Craig Topperf40110f2014-04-25 05:29:35 +00001333 Value *X = nullptr; ConstantInt *YC = nullptr;
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001334 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1335 // Change: and (trunc (and X, YC) to T), C2
1336 // into : and (trunc X to T), trunc(YC) & C2
Craig Topper9d4171a2012-12-20 07:09:41 +00001337 // This will fold the two constants together, which may allow
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001338 // other simplifications.
Craig Topperbb4069e2017-07-07 23:16:26 +00001339 Value *NewCast = Builder.CreateTrunc(X, I.getType(), "and.shrunk");
Chris Lattnerdcef03f2011-02-10 05:17:27 +00001340 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1341 C3 = ConstantExpr::getAnd(C3, AndRHS);
1342 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001343 }
1344 }
Craig Topper86173602017-04-04 20:26:25 +00001345 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001346
Craig Topper86173602017-04-04 20:26:25 +00001347 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001348 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1349 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001350
Craig Topperbb4069e2017-07-07 23:16:26 +00001351 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001352 return DeMorgan;
Craig Topper9d4171a2012-12-20 07:09:41 +00001353
Chris Lattner0a8191e2010-01-05 07:50:36 +00001354 {
Sanjay Patele0c26e02017-04-23 22:00:02 +00001355 Value *A = nullptr, *B = nullptr, *C = nullptr;
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001356 // A&(A^B) => A & ~B
1357 {
1358 Value *tmpOp0 = Op0;
1359 Value *tmpOp1 = Op1;
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001360 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001361 if (A == Op1 || B == Op1 ) {
1362 tmpOp1 = Op0;
1363 tmpOp0 = Op1;
1364 // Simplify below
1365 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001366 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001367
Sanjay Patel7b7eec12016-01-18 18:36:38 +00001368 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001369 if (B == tmpOp0) {
1370 std::swap(A, B);
1371 }
Sanjay Pateld09b44a2016-01-18 17:50:23 +00001372 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
Eli Friedman61d7c8a2011-09-19 21:58:15 +00001373 // A is originally -1 (or a vector of -1 and undefs), then we enter
1374 // an endless loop. By checking that A is non-constant we ensure that
1375 // we will never get to the loop.
1376 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00001377 return BinaryOperator::CreateAnd(A, Builder.CreateNot(B));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001378 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001379 }
1380
David Majnemer42af3602014-07-30 21:26:37 +00001381 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1382 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1383 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001384 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001385 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
David Majnemer42af3602014-07-30 21:26:37 +00001386
1387 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1388 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1389 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001390 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
Craig Topperbb4069e2017-07-07 23:16:26 +00001391 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001392
1393 // (A | B) & ((~A) ^ B) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001394 // (A | B) & (B ^ (~A)) -> (A & B)
1395 // (B | A) & ((~A) ^ B) -> (A & B)
1396 // (B | A) & (B ^ (~A)) -> (A & B)
1397 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1398 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001399 return BinaryOperator::CreateAnd(A, B);
1400
1401 // ((~A) ^ B) & (A | B) -> (A & B)
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001402 // ((~A) ^ B) & (B | A) -> (A & B)
Craig Topperba011432017-04-25 15:19:04 +00001403 // (B ^ (~A)) & (A | B) -> (A & B)
1404 // (B ^ (~A)) & (B | A) -> (A & B)
1405 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001406 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
Suyog Sarda1c6c2f62014-08-01 04:59:26 +00001407 return BinaryOperator::CreateAnd(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001408 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001409
David Majnemer5e96f1b2014-08-30 06:18:20 +00001410 {
1411 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1412 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1413 if (LHS && RHS)
Craig Topperda6ea0d2017-06-16 05:10:37 +00001414 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001415 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001416
David Majnemer5e96f1b2014-08-30 06:18:20 +00001417 // TODO: Make this recursive; it's a little tricky because an arbitrary
1418 // number of 'and' instructions might have to be created.
1419 Value *X, *Y;
1420 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1421 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001422 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001423 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001424 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001425 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001426 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001427 }
1428 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1429 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001430 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001431 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001432 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperda6ea0d2017-06-16 05:10:37 +00001433 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00001434 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
David Majnemer5e96f1b2014-08-30 06:18:20 +00001435 }
1436 }
1437
Chris Lattner4e8137d2010-02-11 06:26:33 +00001438 // If and'ing two fcmp, try combine them into one.
1439 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1440 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00001441 if (Value *Res = foldAndOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00001442 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00001443
Sanjay Patel40e7ba02016-02-23 16:36:07 +00001444 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1445 return CastedAnd;
Craig Topper9d4171a2012-12-20 07:09:41 +00001446
Craig Topper760ff6e2017-08-04 16:07:20 +00001447 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
1448 Value *A;
1449 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
1450 A->getType()->isIntOrIntVectorTy(1))
1451 return SelectInst::Create(A, Op1, Constant::getNullValue(I.getType()));
1452 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
1453 A->getType()->isIntOrIntVectorTy(1))
1454 return SelectInst::Create(A, Op0, Constant::getNullValue(I.getType()));
Nadav Rotem513bd8a2013-01-30 06:35:22 +00001455
Craig Topperf40110f2014-04-25 05:29:35 +00001456 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001457}
1458
Chad Rosiera00df492016-05-25 16:22:14 +00001459/// Given an OR instruction, check to see if this is a bswap idiom. If so,
1460/// insert the new intrinsic and return it.
1461Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chad Rosiere5819e22016-05-26 14:58:51 +00001462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1463
1464 // Look through zero extends.
1465 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1466 Op0 = Ext->getOperand(0);
1467
1468 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1469 Op1 = Ext->getOperand(0);
1470
1471 // (A | B) | C and A | (B | C) -> bswap if possible.
1472 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1473 match(Op1, m_Or(m_Value(), m_Value()));
1474
1475 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1476 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1477 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1478
1479 // (A & B) | (C & D) -> bswap if possible.
1480 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1481 match(Op1, m_And(m_Value(), m_Value()));
1482
1483 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1484 return nullptr;
1485
James Molloyf01488e2016-01-15 09:20:19 +00001486 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00001487 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
Craig Topperf40110f2014-04-25 05:29:35 +00001488 return nullptr;
James Molloyf01488e2016-01-15 09:20:19 +00001489 Instruction *LastInst = Insts.pop_back_val();
1490 LastInst->removeFromParent();
Craig Topper9d4171a2012-12-20 07:09:41 +00001491
James Molloyf01488e2016-01-15 09:20:19 +00001492 for (auto *Inst : Insts)
1493 Worklist.Add(Inst);
1494 return LastInst;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001495}
1496
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001497/// If all elements of two constant vectors are 0/-1 and inverses, return true.
1498static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1499 unsigned NumElts = C1->getType()->getVectorNumElements();
1500 for (unsigned i = 0; i != NumElts; ++i) {
1501 Constant *EltC1 = C1->getAggregateElement(i);
1502 Constant *EltC2 = C2->getAggregateElement(i);
1503 if (!EltC1 || !EltC2)
1504 return false;
1505
1506 // One element must be all ones, and the other must be all zeros.
1507 // FIXME: Allow undef elements.
1508 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1509 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1510 return false;
1511 }
1512 return true;
1513}
1514
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001515/// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1516/// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1517/// B, it can be used as the condition operand of a select instruction.
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001518static Value *getSelectCondition(Value *A, Value *B,
1519 InstCombiner::BuilderTy &Builder) {
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001520 // If these are scalars or vectors of i1, A can be used directly.
1521 Type *Ty = A->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001522 if (match(A, m_Not(m_Specific(B))) && Ty->isIntOrIntVectorTy(1))
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001523 return A;
1524
1525 // If A and B are sign-extended, look through the sexts to find the booleans.
1526 Value *Cond;
Sanjay Pateld1e81192017-06-22 15:46:54 +00001527 Value *NotB;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001528 if (match(A, m_SExt(m_Value(Cond))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001529 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Pateld1e81192017-06-22 15:46:54 +00001530 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1531 NotB = peekThroughBitcast(NotB, true);
1532 if (match(NotB, m_SExt(m_Specific(Cond))))
1533 return Cond;
1534 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001535
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001536 // All scalar (and most vector) possibilities should be handled now.
1537 // Try more matches that only apply to non-splat constant vectors.
1538 if (!Ty->isVectorTy())
1539 return nullptr;
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001540
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001541 // If both operands are constants, see if the constants are inverse bitmasks.
1542 Constant *AC, *BC;
1543 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
Craig Topper57b4d862017-08-10 17:48:14 +00001544 areInverseVectorBitmasks(AC, BC)) {
1545 return Builder.CreateZExtOrTrunc(AC, CmpInst::makeCmpResultType(Ty));
1546 }
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001547
1548 // If both operands are xor'd with constants using the same sexted boolean
1549 // operand, see if the constants are inverse bitmasks.
1550 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1551 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00001552 Cond->getType()->isIntOrIntVectorTy(1) &&
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001553 areInverseVectorBitmasks(AC, BC)) {
1554 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1555 return Builder.CreateXor(Cond, AC);
1556 }
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001557 return nullptr;
1558}
1559
1560/// We have an expression of the form (A & C) | (B & D). Try to simplify this
1561/// to "A' ? C : D", where A' is a boolean or vector of booleans.
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001562static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
Sanjay Patel7ad98ba2016-06-30 14:18:18 +00001563 InstCombiner::BuilderTy &Builder) {
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001564 // The potential condition of the select may be bitcasted. In that case, look
1565 // through its bitcast and the corresponding bitcast of the 'not' condition.
1566 Type *OrigType = A->getType();
Sanjay Patele800df8e2017-06-22 15:28:01 +00001567 A = peekThroughBitcast(A, true);
1568 B = peekThroughBitcast(B, true);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001569
Sanjay Patelc00e48a2016-07-13 18:07:02 +00001570 if (Value *Cond = getSelectCondition(A, B, Builder)) {
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001571 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
Sanjay Patel4e8ebce2016-06-24 18:55:27 +00001572 // The bitcasts will either all exist or all not exist. The builder will
1573 // not create unnecessary casts if the types already match.
1574 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1575 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1576 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1577 return Builder.CreateBitCast(Select, OrigType);
Sanjay Patel6cf18af2016-06-03 14:42:07 +00001578 }
Sanjay Patel5c0bc022016-06-02 18:03:05 +00001579
Craig Topperf40110f2014-04-25 05:29:35 +00001580 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001581}
1582
Sanjay Patel18549272015-09-08 18:24:36 +00001583/// Fold (icmp)|(icmp) if possible.
Sanjay Patel5e456b92017-05-18 20:53:16 +00001584Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Craig Topperf2d3e6d2017-06-15 19:09:51 +00001585 Instruction &CxtI) {
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001586 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1587 // if K1 and K2 are a one-bit mask.
Craig Topperda6ea0d2017-06-16 05:10:37 +00001588 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1589 return V;
1590
1591 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1592
Sanjay Patel519a87a2017-04-05 17:38:34 +00001593 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1594 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
Nadav Rotem0ed2fdb2013-11-12 22:38:59 +00001595
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001596 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1597 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1598 // The original condition actually refers to the following two ranges:
1599 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1600 // We can fold these two ranges if:
1601 // 1) C1 and C2 is unsigned greater than C3.
1602 // 2) The two ranges are separated.
1603 // 3) C1 ^ C2 is one-bit mask.
1604 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1605 // This implies all values in the two ranges differ by exactly one bit.
1606
Sanjay Patel519a87a2017-04-05 17:38:34 +00001607 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1608 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1609 LHSC->getType() == RHSC->getType() &&
1610 LHSC->getValue() == (RHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001611
1612 Value *LAdd = LHS->getOperand(0);
1613 Value *RAdd = RHS->getOperand(0);
1614
1615 Value *LAddOpnd, *RAddOpnd;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001616 ConstantInt *LAddC, *RAddC;
1617 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1618 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1619 LAddC->getValue().ugt(LHSC->getValue()) &&
1620 RAddC->getValue().ugt(LHSC->getValue())) {
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001621
Sanjay Patel519a87a2017-04-05 17:38:34 +00001622 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1623 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1624 ConstantInt *MaxAddC = nullptr;
1625 if (LAddC->getValue().ult(RAddC->getValue()))
1626 MaxAddC = RAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001627 else
Sanjay Patel519a87a2017-04-05 17:38:34 +00001628 MaxAddC = LAddC;
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001629
Sanjay Patel519a87a2017-04-05 17:38:34 +00001630 APInt RRangeLow = -RAddC->getValue();
1631 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1632 APInt LRangeLow = -LAddC->getValue();
1633 APInt LRangeHigh = LRangeLow + LHSC->getValue();
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001634 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1635 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1636 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1637 : RRangeLow - LRangeLow;
1638
1639 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
Sanjay Patel519a87a2017-04-05 17:38:34 +00001640 RangeDiff.ugt(LHSC->getValue())) {
1641 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001642
Craig Topperbb4069e2017-07-07 23:16:26 +00001643 Value *NewAnd = Builder.CreateAnd(LAddOpnd, MaskC);
1644 Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
1645 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
Yi Jiang1a4e73d2014-08-20 22:55:40 +00001646 }
1647 }
1648 }
1649 }
1650
Chris Lattner0a8191e2010-01-05 07:50:36 +00001651 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001652 if (PredicatesFoldable(PredL, PredR)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00001653 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1654 LHS->getOperand(1) == RHS->getOperand(0))
1655 LHS->swapOperands();
1656 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1657 LHS->getOperand(1) == RHS->getOperand(1)) {
1658 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1659 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1660 bool isSigned = LHS->isSigned() || RHS->isSigned();
Pete Cooperebf98c12011-12-17 01:20:32 +00001661 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001662 }
1663 }
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001664
1665 // handle (roughly):
1666 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
Tim Northoverc0756c42013-09-04 11:57:13 +00001667 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
Benjamin Kramer2bca3a62010-12-20 16:21:59 +00001668 return V;
Owen Anderson3fe002d2010-09-08 22:16:17 +00001669
Sanjay Patele4159d22017-04-10 19:38:36 +00001670 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
David Majnemerc2a990b2013-07-05 00:31:17 +00001671 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1672 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1673 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
Craig Topperf40110f2014-04-25 05:29:35 +00001674 Value *A = nullptr, *B = nullptr;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001675 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001676 B = LHS0;
1677 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1678 A = RHS0;
1679 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001680 A = RHS->getOperand(1);
1681 }
1682 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1683 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001684 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
Sanjay Patele4159d22017-04-10 19:38:36 +00001685 B = RHS0;
1686 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1687 A = LHS0;
1688 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
David Majnemerc2a990b2013-07-05 00:31:17 +00001689 A = LHS->getOperand(1);
1690 }
1691 if (A && B)
Craig Topperbb4069e2017-07-07 23:16:26 +00001692 return Builder.CreateICmp(
David Majnemerc2a990b2013-07-05 00:31:17 +00001693 ICmpInst::ICMP_UGE,
Craig Topperbb4069e2017-07-07 23:16:26 +00001694 Builder.CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
David Majnemerc2a990b2013-07-05 00:31:17 +00001695 }
1696
Erik Ecksteind1817522014-12-03 10:39:15 +00001697 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1698 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1699 return V;
1700
1701 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1702 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1703 return V;
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001704
Sanjay Patelef9f5862017-04-15 17:55:06 +00001705 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1706 return V;
1707
David Majnemerc2a990b2013-07-05 00:31:17 +00001708 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001709 if (!LHSC || !RHSC)
1710 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001711
Sanjay Patel519a87a2017-04-05 17:38:34 +00001712 if (LHSC == RHSC && PredL == PredR) {
Owen Anderson8f306a72010-08-02 09:32:13 +00001713 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001714 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001715 Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1716 return Builder.CreateICmp(PredL, NewOr, LHSC);
Owen Anderson8f306a72010-08-02 09:32:13 +00001717 }
Benjamin Kramerda37e152012-01-08 18:32:24 +00001718 }
1719
Benjamin Kramerf7957d02010-12-20 20:00:31 +00001720 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001721 // iff C2 + CA == C1.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001722 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1723 ConstantInt *AddC;
Sanjay Patele4159d22017-04-10 19:38:36 +00001724 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
Sanjay Patel519a87a2017-04-05 17:38:34 +00001725 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
Craig Topperbb4069e2017-07-07 23:16:26 +00001726 return Builder.CreateICmpULE(LHS0, LHSC);
Benjamin Kramer68531ba2010-12-20 16:18:51 +00001727 }
1728
Chris Lattner0a8191e2010-01-05 07:50:36 +00001729 // From here on, we only handle:
1730 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
Sanjay Patele4159d22017-04-10 19:38:36 +00001731 if (LHS0 != RHS0)
Sanjay Patel519a87a2017-04-05 17:38:34 +00001732 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001733
Sanjay Patel519a87a2017-04-05 17:38:34 +00001734 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1735 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1736 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1737 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1738 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
Craig Topperf40110f2014-04-25 05:29:35 +00001739 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001740
Chris Lattner0a8191e2010-01-05 07:50:36 +00001741 // We can't fold (ugt x, C) | (sgt x, C2).
Sanjay Patel519a87a2017-04-05 17:38:34 +00001742 if (!PredicatesFoldable(PredL, PredR))
Craig Topperf40110f2014-04-25 05:29:35 +00001743 return nullptr;
Craig Topper9d4171a2012-12-20 07:09:41 +00001744
Chris Lattner0a8191e2010-01-05 07:50:36 +00001745 // Ensure that the larger constant is on the RHS.
1746 bool ShouldSwap;
Sanjay Patel28611ac2017-04-11 15:57:32 +00001747 if (CmpInst::isSigned(PredL) ||
1748 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
Sanjay Patel570e35c2017-04-10 16:55:57 +00001749 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
Sanjay Patel28611ac2017-04-11 15:57:32 +00001750 else
1751 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
Craig Topper9d4171a2012-12-20 07:09:41 +00001752
Chris Lattner0a8191e2010-01-05 07:50:36 +00001753 if (ShouldSwap) {
1754 std::swap(LHS, RHS);
Sanjay Patel519a87a2017-04-05 17:38:34 +00001755 std::swap(LHSC, RHSC);
1756 std::swap(PredL, PredR);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001757 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001758
Dan Gohman4a618822010-02-10 16:03:48 +00001759 // At this point, we know we have two icmp instructions
Chris Lattner0a8191e2010-01-05 07:50:36 +00001760 // comparing a value against two constants and or'ing the result
1761 // together. Because of the above check, we know that we only have
1762 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1763 // icmp folding check above), that the two constants are not
1764 // equal.
Sanjay Patel519a87a2017-04-05 17:38:34 +00001765 assert(LHSC != RHSC && "Compares not folded above?");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001766
Sanjay Patel519a87a2017-04-05 17:38:34 +00001767 switch (PredL) {
1768 default:
1769 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001770 case ICmpInst::ICMP_EQ:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001771 switch (PredR) {
1772 default:
1773 llvm_unreachable("Unknown integer condition code!");
Chris Lattner0a8191e2010-01-05 07:50:36 +00001774 case ICmpInst::ICMP_EQ:
Sanjay Patel7cfe4162017-04-14 19:23:50 +00001775 // Potential folds for this case should already be handled.
1776 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001777 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1778 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001779 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001780 }
1781 break;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001782 case ICmpInst::ICMP_ULT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001783 switch (PredR) {
1784 default:
1785 llvm_unreachable("Unknown integer condition code!");
1786 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001787 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001788 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001789 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001790 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1791 false, false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001792 }
1793 break;
1794 case ICmpInst::ICMP_SLT:
Sanjay Patel519a87a2017-04-05 17:38:34 +00001795 switch (PredR) {
1796 default:
1797 llvm_unreachable("Unknown integer condition code!");
1798 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
Chris Lattner0a8191e2010-01-05 07:50:36 +00001799 break;
Sanjay Patel519a87a2017-04-05 17:38:34 +00001800 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
Sanjay Patel599e65b2017-05-07 15:11:40 +00001801 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
Sanjay Patele4159d22017-04-10 19:38:36 +00001802 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
Sanjay Patel519a87a2017-04-05 17:38:34 +00001803 false);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001804 }
1805 break;
1806 }
Craig Topperf40110f2014-04-25 05:29:35 +00001807 return nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001808}
1809
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00001810// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1811// here. We should standardize that construct where it is needed or choose some
1812// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00001813Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001814 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001815 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1816
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001817 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001818 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001819
Craig Toppera4205622017-06-09 03:21:29 +00001820 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001821 return replaceInstUsesWith(I, V);
Bill Wendlingaf13d822010-03-03 00:35:56 +00001822
Craig Topper9d4171a2012-12-20 07:09:41 +00001823 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00001824 // purpose is to compute bits we don't care about.
1825 if (SimplifyDemandedInstructionBits(I))
1826 return &I;
1827
Sanjay Patele0c26e02017-04-23 22:00:02 +00001828 // Do this before using distributive laws to catch simple and/or/not patterns.
Craig Topperbb4069e2017-07-07 23:16:26 +00001829 if (Instruction *Xor = foldOrToXor(I, Builder))
Sanjay Patele0c26e02017-04-23 22:00:02 +00001830 return Xor;
1831
1832 // (A&B)|(A&C) -> A&(B|C) etc
1833 if (Value *V = SimplifyUsingDistributiveLaws(I))
1834 return replaceInstUsesWith(I, V);
1835
Craig Topper95e41422017-07-06 16:24:23 +00001836 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001837 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00001838
Craig Topper86173602017-04-04 20:26:25 +00001839 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001840 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1841 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001842
Chad Rosiere5819e22016-05-26 14:58:51 +00001843 // Given an OR instruction, check to see if this is a bswap.
1844 if (Instruction *BSwap = MatchBSwap(I))
1845 return BSwap;
1846
Craig Topperafa07c52017-04-09 06:12:41 +00001847 {
1848 Value *A;
1849 const APInt *C;
1850 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1851 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1852 MaskedValueIsZero(Op1, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001853 Value *NOr = Builder.CreateOr(A, Op1);
Craig Topperafa07c52017-04-09 06:12:41 +00001854 NOr->takeName(Op0);
1855 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001856 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001857 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001858
Craig Topperafa07c52017-04-09 06:12:41 +00001859 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1860 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
1861 MaskedValueIsZero(Op0, *C, 0, &I)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001862 Value *NOr = Builder.CreateOr(A, Op0);
Craig Topperafa07c52017-04-09 06:12:41 +00001863 NOr->takeName(Op0);
1864 return BinaryOperator::CreateXor(NOr,
Davide Italianocdc937d2017-04-17 20:49:50 +00001865 ConstantInt::get(NOr->getType(), *C));
Craig Topperafa07c52017-04-09 06:12:41 +00001866 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001867 }
1868
Craig Topperafa07c52017-04-09 06:12:41 +00001869 Value *A, *B;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001870
1871 // (A & C)|(B & D)
Craig Topperf40110f2014-04-25 05:29:35 +00001872 Value *C = nullptr, *D = nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001873 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1874 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Craig Topperafa07c52017-04-09 06:12:41 +00001875 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1876 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
Chris Lattner0a8191e2010-01-05 07:50:36 +00001877 if (C1 && C2) { // (A & C1)|(B & C2)
Craig Topperf7200992017-08-14 00:04:21 +00001878 Value *V1 = nullptr, *V2 = nullptr;
Craig Topper73ba1c82017-06-07 07:40:37 +00001879 if ((C1->getValue() & C2->getValue()).isNullValue()) {
Chris Lattner95188692010-01-11 06:55:24 +00001880 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001881 // iff (C1&C2) == 0 and (N&~C1) == 0
Chris Lattner0a8191e2010-01-05 07:50:36 +00001882 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001883 ((V1 == B &&
1884 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
1885 (V2 == B &&
1886 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001887 return BinaryOperator::CreateAnd(A,
Craig Topperbb4069e2017-07-07 23:16:26 +00001888 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner0a8191e2010-01-05 07:50:36 +00001889 // Or commutes, try both ways.
1890 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001891 ((V1 == A &&
1892 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
1893 (V2 == A &&
1894 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
Chris Lattner0a8191e2010-01-05 07:50:36 +00001895 return BinaryOperator::CreateAnd(B,
Craig Topperbb4069e2017-07-07 23:16:26 +00001896 Builder.getInt(C1->getValue()|C2->getValue()));
Craig Topper9d4171a2012-12-20 07:09:41 +00001897
Chris Lattner95188692010-01-11 06:55:24 +00001898 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001899 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
Craig Topperf40110f2014-04-25 05:29:35 +00001900 ConstantInt *C3 = nullptr, *C4 = nullptr;
Chris Lattner95188692010-01-11 06:55:24 +00001901 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001902 (C3->getValue() & ~C1->getValue()).isNullValue() &&
Chris Lattner95188692010-01-11 06:55:24 +00001903 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
Craig Topper73ba1c82017-06-07 07:40:37 +00001904 (C4->getValue() & ~C2->getValue()).isNullValue()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001905 V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
Chris Lattner95188692010-01-11 06:55:24 +00001906 return BinaryOperator::CreateAnd(V2,
Craig Topperbb4069e2017-07-07 23:16:26 +00001907 Builder.getInt(C1->getValue()|C2->getValue()));
Chris Lattner95188692010-01-11 06:55:24 +00001908 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001909 }
Craig Topperf7200992017-08-14 00:04:21 +00001910
1911 if (C1->getValue() == ~C2->getValue()) {
1912 Value *X;
1913
1914 // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
1915 if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
1916 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
1917 // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
1918 if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
1919 return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
1920
1921 // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
1922 if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
1923 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
1924 // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
1925 if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
1926 return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
1927 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001928 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001929
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001930 // Don't try to form a select if it's unlikely that we'll get rid of at
1931 // least one of the operands. A select is generally more expensive than the
1932 // 'or' that it is replacing.
1933 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1934 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
Craig Topperbb4069e2017-07-07 23:16:26 +00001935 if (Value *V = matchSelectFromAndOr(A, C, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001936 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001937 if (Value *V = matchSelectFromAndOr(A, C, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001938 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001939 if (Value *V = matchSelectFromAndOr(C, A, B, D, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001940 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001941 if (Value *V = matchSelectFromAndOr(C, A, D, B, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001942 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001943 if (Value *V = matchSelectFromAndOr(B, D, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001944 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001945 if (Value *V = matchSelectFromAndOr(B, D, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001946 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001947 if (Value *V = matchSelectFromAndOr(D, B, A, C, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001948 return replaceInstUsesWith(I, V);
Craig Topperbb4069e2017-07-07 23:16:26 +00001949 if (Value *V = matchSelectFromAndOr(D, B, C, A, Builder))
Sanjay Patelf4a08ed2016-07-08 20:53:29 +00001950 return replaceInstUsesWith(I, V);
1951 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00001952 }
Craig Topper9d4171a2012-12-20 07:09:41 +00001953
David Majnemer42af3602014-07-30 21:26:37 +00001954 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
1955 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1956 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001957 return BinaryOperator::CreateOr(Op0, C);
David Majnemer42af3602014-07-30 21:26:37 +00001958
1959 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
1960 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1961 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
Craig Toppera7529b62017-06-19 16:23:49 +00001962 return BinaryOperator::CreateOr(Op1, C);
David Majnemer42af3602014-07-30 21:26:37 +00001963
David Majnemerf1eda232014-08-14 06:41:38 +00001964 // ((B | C) & A) | B -> B | (A & C)
1965 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00001966 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
David Majnemerf1eda232014-08-14 06:41:38 +00001967
Craig Topperbb4069e2017-07-07 23:16:26 +00001968 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
Sanjay Patelb54e62f2015-09-08 20:14:13 +00001969 return DeMorgan;
Chris Lattner0a8191e2010-01-05 07:50:36 +00001970
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001971 // Canonicalize xor to the RHS.
Eli Friedmane06535b2012-03-16 00:52:42 +00001972 bool SwappedForXor = false;
1973 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001974 std::swap(Op0, Op1);
Eli Friedmane06535b2012-03-16 00:52:42 +00001975 SwappedForXor = true;
1976 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001977
1978 // A | ( A ^ B) -> A | B
1979 // A | (~A ^ B) -> A | ~B
Chad Rosier7813dce2012-04-26 23:29:14 +00001980 // (A & B) | (A ^ B)
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001981 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1982 if (Op0 == A || Op0 == B)
1983 return BinaryOperator::CreateOr(A, B);
1984
Chad Rosier7813dce2012-04-26 23:29:14 +00001985 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1986 match(Op0, m_And(m_Specific(B), m_Specific(A))))
1987 return BinaryOperator::CreateOr(A, B);
1988
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001989 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001990 Value *Not = Builder.CreateNot(B, B->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001991 return BinaryOperator::CreateOr(Not, Op0);
1992 }
1993 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001994 Value *Not = Builder.CreateNot(A, A->getName() + ".not");
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00001995 return BinaryOperator::CreateOr(Not, Op0);
1996 }
1997 }
1998
1999 // A | ~(A | B) -> A | ~B
2000 // A | ~(A ^ B) -> A | ~B
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002001 if (match(Op1, m_Not(m_Value(A))))
2002 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002003 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2004 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2005 B->getOpcode() == Instruction::Xor)) {
2006 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2007 B->getOperand(0);
Craig Topperbb4069e2017-07-07 23:16:26 +00002008 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00002009 return BinaryOperator::CreateOr(Not, Op0);
2010 }
Benjamin Kramerd5d7f372011-02-20 13:23:43 +00002011
Eli Friedmane06535b2012-03-16 00:52:42 +00002012 if (SwappedForXor)
2013 std::swap(Op0, Op1);
2014
David Majnemer3d6f80b2014-11-28 19:58:29 +00002015 {
2016 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2017 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2018 if (LHS && RHS)
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002019 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002020 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002021
David Majnemer3d6f80b2014-11-28 19:58:29 +00002022 // TODO: Make this recursive; it's a little tricky because an arbitrary
2023 // number of 'or' instructions might have to be created.
2024 Value *X, *Y;
2025 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2026 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002027 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002028 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002029 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002030 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002031 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002032 }
2033 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2034 if (auto *Cmp = dyn_cast<ICmpInst>(X))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002035 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002036 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002037 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
Craig Topperf2d3e6d2017-06-15 19:09:51 +00002038 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
Craig Topperbb4069e2017-07-07 23:16:26 +00002039 return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
David Majnemer3d6f80b2014-11-28 19:58:29 +00002040 }
2041 }
2042
Chris Lattner4e8137d2010-02-11 06:26:33 +00002043 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2044 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2045 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
Sanjay Patel5e456b92017-05-18 20:53:16 +00002046 if (Value *Res = foldOrOfFCmps(LHS, RHS))
Sanjay Patel4b198802016-02-01 22:23:39 +00002047 return replaceInstUsesWith(I, Res);
Craig Topper9d4171a2012-12-20 07:09:41 +00002048
Sanjay Patel75b4ae22016-02-23 23:56:23 +00002049 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2050 return CastedOr;
Eli Friedman23956262011-04-14 22:41:27 +00002051
Sanjay Patelcbfca9e2016-07-08 17:01:15 +00002052 // 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 +00002053 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002054 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002055 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
Sanjay Patel1b6b8242016-07-08 17:26:47 +00002056 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
Craig Topperfde47232017-07-09 07:04:03 +00002057 A->getType()->isIntOrIntVectorTy(1))
Eli Friedman23956262011-04-14 22:41:27 +00002058 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2059
Owen Andersonc237a842010-09-13 17:59:27 +00002060 // Note: If we've gotten to the point of visiting the outer OR, then the
2061 // inner one couldn't be simplified. If it was a constant, then it won't
2062 // be simplified by a later pass either, so we try swapping the inner/outer
2063 // ORs in the hopes that we'll be able to simplify it this way.
2064 // (X|C) | V --> (X|V) | C
Craig Topperafa07c52017-04-09 06:12:41 +00002065 ConstantInt *C1;
Owen Andersonc237a842010-09-13 17:59:27 +00002066 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2067 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002068 Value *Inner = Builder.CreateOr(A, Op1);
Owen Andersonc237a842010-09-13 17:59:27 +00002069 Inner->takeName(Op0);
2070 return BinaryOperator::CreateOr(Inner, C1);
2071 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002072
Bill Wendling23242092013-02-16 23:41:36 +00002073 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2074 // Since this OR statement hasn't been optimized further yet, we hope
2075 // that this transformation will allow the new ORs to be optimized.
2076 {
Craig Topperf40110f2014-04-25 05:29:35 +00002077 Value *X = nullptr, *Y = nullptr;
Bill Wendling23242092013-02-16 23:41:36 +00002078 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2079 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2080 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002081 Value *orTrue = Builder.CreateOr(A, C);
2082 Value *orFalse = Builder.CreateOr(B, D);
Bill Wendling23242092013-02-16 23:41:36 +00002083 return SelectInst::Create(X, orTrue, orFalse);
2084 }
2085 }
2086
Craig Topperf40110f2014-04-25 05:29:35 +00002087 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002088}
2089
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002090/// A ^ B can be specified using other logic ops in a variety of patterns. We
2091/// can fold these early and efficiently by morphing an existing instruction.
Craig Topperf60ab472017-07-02 01:15:51 +00002092static Instruction *foldXorToXor(BinaryOperator &I,
2093 InstCombiner::BuilderTy &Builder) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002094 assert(I.getOpcode() == Instruction::Xor);
2095 Value *Op0 = I.getOperand(0);
2096 Value *Op1 = I.getOperand(1);
2097 Value *A, *B;
2098
2099 // There are 4 commuted variants for each of the basic patterns.
2100
2101 // (A & B) ^ (A | B) -> A ^ B
2102 // (A & B) ^ (B | A) -> A ^ B
2103 // (A | B) ^ (A & B) -> A ^ B
2104 // (A | B) ^ (B & A) -> A ^ B
2105 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2106 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2107 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2108 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2109 I.setOperand(0, A);
2110 I.setOperand(1, B);
2111 return &I;
2112 }
2113
2114 // (A | ~B) ^ (~A | B) -> A ^ B
2115 // (~B | A) ^ (~A | B) -> A ^ B
2116 // (~A | B) ^ (A | ~B) -> A ^ B
2117 // (B | ~A) ^ (A | ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002118 if ((match(Op0, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2119 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2120 (match(Op0, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2121 match(Op1, m_c_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002122 I.setOperand(0, A);
2123 I.setOperand(1, B);
2124 return &I;
2125 }
2126
2127 // (A & ~B) ^ (~A & B) -> A ^ B
2128 // (~B & A) ^ (~A & B) -> A ^ B
2129 // (~A & B) ^ (A & ~B) -> A ^ B
2130 // (B & ~A) ^ (A & ~B) -> A ^ B
Craig Topper880bf822017-06-30 07:37:41 +00002131 if ((match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2132 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2133 (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2134 match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))))) {
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002135 I.setOperand(0, A);
2136 I.setOperand(1, B);
2137 return &I;
2138 }
2139
Craig Topperf60ab472017-07-02 01:15:51 +00002140 // For the remaining cases we need to get rid of one of the operands.
2141 if (!Op0->hasOneUse() && !Op1->hasOneUse())
2142 return nullptr;
2143
2144 // (A | B) ^ ~(A & B) -> ~(A ^ B)
2145 // (A | B) ^ ~(B & A) -> ~(A ^ B)
2146 // (A & B) ^ ~(A | B) -> ~(A ^ B)
2147 // (A & B) ^ ~(B | A) -> ~(A ^ B)
2148 // Complexity sorting ensures the not will be on the right side.
2149 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2150 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
2151 (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2152 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
2153 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
2154
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002155 return nullptr;
2156}
2157
Sanjay Patel5e456b92017-05-18 20:53:16 +00002158Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2159 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2160 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2161 LHS->getOperand(1) == RHS->getOperand(0))
2162 LHS->swapOperands();
2163 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2164 LHS->getOperand(1) == RHS->getOperand(1)) {
2165 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2166 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2167 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2168 bool isSigned = LHS->isSigned() || RHS->isSigned();
2169 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2170 }
2171 }
2172
Sanjay Pateladca8252017-06-20 12:40:55 +00002173 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2174 // into those logic ops. That is, try to turn this into an and-of-icmps
2175 // because we have many folds for that pattern.
2176 //
2177 // This is based on a truth table definition of xor:
2178 // X ^ Y --> (X | Y) & !(X & Y)
2179 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2180 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2181 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2182 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2183 // TODO: Independently handle cases where the 'and' side is a constant.
2184 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2185 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2186 RHS->setPredicate(RHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002187 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002188 }
2189 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
Sanjay Patel4ccbd582017-06-20 12:45:46 +00002190 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
Sanjay Pateladca8252017-06-20 12:40:55 +00002191 LHS->setPredicate(LHS->getInversePredicate());
Craig Topperbb4069e2017-07-07 23:16:26 +00002192 return Builder.CreateAnd(LHS, RHS);
Sanjay Pateladca8252017-06-20 12:40:55 +00002193 }
2194 }
2195 }
2196
Sanjay Patel5e456b92017-05-18 20:53:16 +00002197 return nullptr;
2198}
2199
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002200// FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2201// here. We should standardize that construct where it is needed or choose some
2202// other way to ensure that commutated variants of patterns are not missed.
Chris Lattner0a8191e2010-01-05 07:50:36 +00002203Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00002204 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2206
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002207 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002208 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00002209
Craig Toppera4205622017-06-09 03:21:29 +00002210 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002211 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002212
Craig Topperbb4069e2017-07-07 23:16:26 +00002213 if (Instruction *NewXor = foldXorToXor(I, Builder))
Sanjay Pateld13b0bf2017-04-23 16:03:00 +00002214 return NewXor;
2215
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00002216 // (A&B)^(A&C) -> A&(B^C) etc
2217 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002218 return replaceInstUsesWith(I, V);
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002219
Craig Topper9d4171a2012-12-20 07:09:41 +00002220 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner0a8191e2010-01-05 07:50:36 +00002221 // purpose is to compute bits we don't care about.
2222 if (SimplifyDemandedInstructionBits(I))
2223 return &I;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002224
Craig Topper95e41422017-07-06 16:24:23 +00002225 if (Value *V = SimplifyBSwap(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002226 return replaceInstUsesWith(I, V);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002227
Sanjay Patel6381db12017-05-02 15:31:40 +00002228 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2229 Value *X, *Y;
2230
2231 // We must eliminate the and/or (one-use) for these transforms to not increase
2232 // the instruction count.
2233 // ~(~X & Y) --> (X | ~Y)
2234 // ~(Y & ~X) --> (X | ~Y)
2235 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 +00002236 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002237 return BinaryOperator::CreateOr(X, NotY);
2238 }
2239 // ~(~X | Y) --> (X & ~Y)
2240 // ~(Y | ~X) --> (X & ~Y)
2241 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 +00002242 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Sanjay Patel6381db12017-05-02 15:31:40 +00002243 return BinaryOperator::CreateAnd(X, NotY);
2244 }
2245
Sanjay Patel3b863f82017-04-22 18:05:35 +00002246 // Is this a 'not' (~) fed by a binary operator?
Sanjay Patela1c88142017-05-08 20:49:59 +00002247 BinaryOperator *NotVal;
2248 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2249 if (NotVal->getOpcode() == Instruction::And ||
2250 NotVal->getOpcode() == Instruction::Or) {
Sanjay Patel6381db12017-05-02 15:31:40 +00002251 // Apply DeMorgan's Law when inverts are free:
2252 // ~(X & Y) --> (~X | ~Y)
2253 // ~(X | Y) --> (~X & ~Y)
Sanjay Patela1c88142017-05-08 20:49:59 +00002254 if (IsFreeToInvert(NotVal->getOperand(0),
2255 NotVal->getOperand(0)->hasOneUse()) &&
2256 IsFreeToInvert(NotVal->getOperand(1),
2257 NotVal->getOperand(1)->hasOneUse())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00002258 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
2259 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
Sanjay Patela1c88142017-05-08 20:49:59 +00002260 if (NotVal->getOpcode() == Instruction::And)
Sanjay Patel3b863f82017-04-22 18:05:35 +00002261 return BinaryOperator::CreateOr(NotX, NotY);
2262 return BinaryOperator::CreateAnd(NotX, NotY);
2263 }
Sanjay Patela1c88142017-05-08 20:49:59 +00002264 }
2265
2266 // ~(~X >>s Y) --> (X >>s Y)
2267 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2268 return BinaryOperator::CreateAShr(X, Y);
2269
2270 // If we are inverting a right-shifted constant, we may be able to eliminate
2271 // the 'not' by inverting the constant and using the opposite shift type.
2272 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2273 // but we must check that in case that transform has not fired yet.
2274 const APInt *C;
2275 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2276 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2277 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2278 return BinaryOperator::CreateLShr(NotC, Y);
2279 }
2280
2281 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2282 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2283 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2284 return BinaryOperator::CreateAShr(NotC, Y);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002285 }
2286 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002287
Craig Topper798a19a2017-06-29 00:07:08 +00002288 // not (cmp A, B) = !cmp A, B
Craig Toppercc418b62017-07-05 20:31:00 +00002289 CmpInst::Predicate Pred;
Craig Topper798a19a2017-06-29 00:07:08 +00002290 if (match(&I, m_Not(m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))))) {
Sanjay Patel33439f92017-04-12 15:11:33 +00002291 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2292 return replaceInstUsesWith(I, Op0);
Benjamin Kramer443c7962015-02-12 20:26:46 +00002293 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002294
Craig Topperb5bf0162017-08-06 06:28:41 +00002295 {
2296 const APInt *RHSC;
2297 if (match(Op1, m_APInt(RHSC))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002298 Value *X;
Craig Topperb5bf0162017-08-06 06:28:41 +00002299 const APInt *C;
Craig Topper9a6110b2017-08-10 20:35:34 +00002300 if (match(Op0, m_Sub(m_APInt(C), m_Value(X)))) {
Craig Topperb5bf0162017-08-06 06:28:41 +00002301 // ~(c-X) == X-c-1 == X+(-c-1)
2302 if (RHSC->isAllOnesValue()) {
2303 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
Craig Topper9a6110b2017-08-10 20:35:34 +00002304 return BinaryOperator::CreateAdd(X, NewC);
Craig Topperb5bf0162017-08-06 06:28:41 +00002305 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002306 if (RHSC->isSignMask()) {
2307 // (C - X) ^ signmask -> (C + signmask - X)
2308 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
Craig Topper9a6110b2017-08-10 20:35:34 +00002309 return BinaryOperator::CreateSub(NewC, X);
Craig Topper9cbdbef2017-08-06 22:17:21 +00002310 }
Craig Topper9a6110b2017-08-10 20:35:34 +00002311 } else if (match(Op0, m_Add(m_Value(X), m_APInt(C)))) {
Craig Topperb5bf0162017-08-06 06:28:41 +00002312 // ~(X-c) --> (-c-1)-X
2313 if (RHSC->isAllOnesValue()) {
2314 Constant *NewC = ConstantInt::get(I.getType(), -(*C) - 1);
Craig Topper9a6110b2017-08-10 20:35:34 +00002315 return BinaryOperator::CreateSub(NewC, X);
Craig Topperb5bf0162017-08-06 06:28:41 +00002316 }
Craig Topper9cbdbef2017-08-06 22:17:21 +00002317 if (RHSC->isSignMask()) {
2318 // (X + C) ^ signmask -> (X + C + signmask)
2319 Constant *NewC = ConstantInt::get(I.getType(), *C + *RHSC);
Craig Topper9a6110b2017-08-10 20:35:34 +00002320 return BinaryOperator::CreateAdd(X, NewC);
Craig Topper9cbdbef2017-08-06 22:17:21 +00002321 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002322 }
Craig Topper9a6110b2017-08-10 20:35:34 +00002323
2324 // (X|C1)^C2 -> X^(C1^C2) iff X&~C1 == 0
2325 if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
2326 MaskedValueIsZero(X, *C, 0, &I)) {
2327 Constant *NewC = ConstantInt::get(I.getType(), *C ^ *RHSC);
2328 Worklist.Add(cast<Instruction>(Op0));
2329 I.setOperand(0, X);
2330 I.setOperand(1, NewC);
2331 return &I;
2332 }
Craig Topperb5bf0162017-08-06 06:28:41 +00002333 }
2334 }
2335
Craig Topper9d1821b2017-04-09 06:12:31 +00002336 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002337 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002338 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Craig Topper9a6110b2017-08-10 20:35:34 +00002339 if (Op0I->getOpcode() == Instruction::LShr) {
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002340 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2341 // E1 = "X ^ C1"
Craig Topper9d4171a2012-12-20 07:09:41 +00002342 BinaryOperator *E1;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002343 ConstantInt *C1;
2344 if (Op0I->hasOneUse() &&
2345 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2346 E1->getOpcode() == Instruction::Xor &&
2347 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2348 // fold (C1 >> C2) ^ C3
Craig Topper9d1821b2017-04-09 06:12:31 +00002349 ConstantInt *C2 = Op0CI, *C3 = RHSC;
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002350 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2351 FoldConst ^= C3->getValue();
2352 // Prepare the two operands.
Craig Topperbb4069e2017-07-07 23:16:26 +00002353 Value *Opnd0 = Builder.CreateLShr(E1->getOperand(0), C2);
Shuxin Yang6ea79e82012-11-26 21:44:25 +00002354 Opnd0->takeName(Op0I);
2355 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2356 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2357
2358 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2359 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002360 }
2361 }
2362 }
Craig Topper86173602017-04-04 20:26:25 +00002363 }
Chris Lattner0a8191e2010-01-05 07:50:36 +00002364
Craig Topper86173602017-04-04 20:26:25 +00002365 if (isa<Constant>(Op1))
Sanjay Pateldb0938f2017-01-10 23:49:07 +00002366 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2367 return FoldedLogic;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002368
Craig Topper76394602017-04-10 06:53:23 +00002369 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002370 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002371 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Craig Topper47383212017-04-10 06:53:21 +00002372 if (A == Op0) { // A^(A|B) == A^(B|A)
Craig Topper76394602017-04-10 06:53:23 +00002373 cast<BinaryOperator>(Op1)->swapOperands();
Craig Topper47383212017-04-10 06:53:21 +00002374 std::swap(A, B);
2375 }
2376 if (B == Op0) { // A^(B|A) == (B|A)^A
Chris Lattner0a8191e2010-01-05 07:50:36 +00002377 I.swapOperands(); // Simplified below.
2378 std::swap(Op0, Op1);
2379 }
Craig Topper76394602017-04-10 06:53:23 +00002380 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002381 if (A == Op0) { // A^(A&B) -> A^(B&A)
Craig Topper76394602017-04-10 06:53:23 +00002382 cast<BinaryOperator>(Op1)->swapOperands();
Chris Lattner0a8191e2010-01-05 07:50:36 +00002383 std::swap(A, B);
2384 }
2385 if (B == Op0) { // A^(B&A) -> (B&A)^A
2386 I.swapOperands(); // Simplified below.
2387 std::swap(Op0, Op1);
2388 }
2389 }
2390 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002391
Craig Topper76394602017-04-10 06:53:23 +00002392 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002393 Value *A, *B;
Craig Topper76394602017-04-10 06:53:23 +00002394 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002395 if (A == Op1) // (B|A)^B == (A|B)^B
2396 std::swap(A, B);
2397 if (B == Op1) // (A|B)^B == A & ~B
Craig Topperbb4069e2017-07-07 23:16:26 +00002398 return BinaryOperator::CreateAnd(A, Builder.CreateNot(Op1));
Craig Topper76394602017-04-10 06:53:23 +00002399 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002400 if (A == Op1) // (A&B)^A -> (B&A)^A
2401 std::swap(A, B);
Craig Toppere63c21b2017-04-09 06:12:39 +00002402 const APInt *C;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002403 if (B == Op1 && // (B&A)^A == ~B & A
Craig Toppere63c21b2017-04-09 06:12:39 +00002404 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
Craig Topperbb4069e2017-07-07 23:16:26 +00002405 return BinaryOperator::CreateAnd(Builder.CreateNot(A), Op1);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002406 }
2407 }
2408 }
Craig Topper9d4171a2012-12-20 07:09:41 +00002409
Craig Topper76394602017-04-10 06:53:23 +00002410 {
Chris Lattner0a8191e2010-01-05 07:50:36 +00002411 Value *A, *B, *C, *D;
David Majnemer6fe6ea72014-09-05 06:09:24 +00002412 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002413 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2414 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002415 if (D == A)
2416 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002417 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002418 if (D == B)
2419 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002420 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002421 }
David Majnemer6fe6ea72014-09-05 06:09:24 +00002422 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
Craig Topper76394602017-04-10 06:53:23 +00002423 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2424 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
David Majnemer6fe6ea72014-09-05 06:09:24 +00002425 if (D == A)
2426 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002427 Builder.CreateAnd(Builder.CreateNot(A), B), C);
David Majnemer6fe6ea72014-09-05 06:09:24 +00002428 if (D == B)
2429 return BinaryOperator::CreateXor(
Craig Topperbb4069e2017-07-07 23:16:26 +00002430 Builder.CreateAnd(Builder.CreateNot(B), A), C);
Karthik Bhata4a4db92014-08-13 05:13:14 +00002431 }
Suyog Sardab60ec902014-07-22 18:30:54 +00002432 // (A & B) ^ (A ^ B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002433 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002434 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002435 return BinaryOperator::CreateOr(A, B);
2436 // (A ^ B) ^ (A & B) -> (A | B)
Craig Topper76394602017-04-10 06:53:23 +00002437 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topperd8840d72017-04-10 06:53:28 +00002438 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
Suyog Sardab60ec902014-07-22 18:30:54 +00002439 return BinaryOperator::CreateOr(A, B);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002440 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +00002441
Sanjay Patel2b9d4b42016-12-18 18:49:48 +00002442 // (A & ~B) ^ ~A -> ~(A & B)
2443 // (~B & A) ^ ~A -> ~(A & B)
2444 Value *A, *B;
2445 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
Suyog Sarda56c9a872014-08-01 05:07:20 +00002446 match(Op1, m_Not(m_Specific(A))))
Craig Topperbb4069e2017-07-07 23:16:26 +00002447 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
Suyog Sarda56c9a872014-08-01 05:07:20 +00002448
Sanjay Patel5e456b92017-05-18 20:53:16 +00002449 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2450 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2451 if (Value *V = foldXorOfICmps(LHS, RHS))
2452 return replaceInstUsesWith(I, V);
Chris Lattner0a8191e2010-01-05 07:50:36 +00002453
Sanjay Pateldbbaca02016-02-24 17:00:34 +00002454 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2455 return CastedXor;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002456
Craig Topperf40110f2014-04-25 05:29:35 +00002457 return Changed ? &I : nullptr;
Chris Lattner0a8191e2010-01-05 07:50:36 +00002458}