blob: b71841a1607dc15b3165c715bdffe347892a5e18 [file] [log] [blame]
Chris Lattner084a1b52009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner084a1b52009-11-09 22:57:59 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements routines for folding instructions into simpler forms
Duncan Sandsa0219882010-11-23 10:50:08 +000010// that do not require creating new instructions. This does constant folding
11// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsed6d6c32010-12-20 14:47:04 +000013// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14// simplified: This is usually true and assuming it simplifies the logic (if
15// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner084a1b52009-11-09 22:57:59 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/Statistic.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000022#include "llvm/Analysis/AliasAnalysis.h"
Daniel Berlin4d0fe642017-04-28 19:55:38 +000023#include "llvm/Analysis/AssumptionCache.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000024#include "llvm/Analysis/CaptureTracking.h"
Craig Topper0aa3a192017-08-14 21:39:51 +000025#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000026#include "llvm/Analysis/ConstantFolding.h"
Daniel Berlin4d0fe642017-04-28 19:55:38 +000027#include "llvm/Analysis/LoopAnalysisManager.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000030#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000031#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000034#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/GlobalAlias.h"
Chandler Carruthdac20a82019-02-11 07:54:10 +000036#include "llvm/IR/InstrTypes.h"
37#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000039#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000040#include "llvm/IR/ValueHandle.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000041#include "llvm/Support/KnownBits.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000042#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000043using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000044using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000045
Chandler Carruthf1221bd2014-04-22 02:48:03 +000046#define DEBUG_TYPE "instsimplify"
47
Chris Lattner9e4aa022011-02-09 17:15:04 +000048enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000049
Duncan Sands3547d2e2010-12-22 09:40:51 +000050STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000051STATISTIC(NumReassoc, "Number of reassociations");
52
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000053static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
Cameron McInallyc3167692019-05-06 16:05:10 +000054static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
55static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
56 const SimplifyQuery &, unsigned);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000057static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000058 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000059static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000060 const SimplifyQuery &, unsigned);
61static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000062 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000063static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000064 const SimplifyQuery &Q, unsigned MaxRecurse);
65static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
66static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000067static Value *SimplifyCastInst(unsigned, Value *, Type *,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000068 const SimplifyQuery &, unsigned);
George Burgess IV8e807bf2018-04-24 00:25:01 +000069static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
70 unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000071
David Bolvanskyf9476082018-07-28 06:55:51 +000072static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
73 Value *FalseVal) {
74 BinaryOperator::BinaryOps BinOpCode;
75 if (auto *BO = dyn_cast<BinaryOperator>(Cond))
76 BinOpCode = BO->getOpcode();
77 else
78 return nullptr;
79
David Bolvansky16d8a692018-07-31 14:17:15 +000080 CmpInst::Predicate ExpectedPred, Pred1, Pred2;
David Bolvanskyf9476082018-07-28 06:55:51 +000081 if (BinOpCode == BinaryOperator::Or) {
82 ExpectedPred = ICmpInst::ICMP_NE;
83 } else if (BinOpCode == BinaryOperator::And) {
84 ExpectedPred = ICmpInst::ICMP_EQ;
85 } else
86 return nullptr;
87
David Bolvansky16d8a692018-07-31 14:17:15 +000088 // %A = icmp eq %TV, %FV
89 // %B = icmp eq %X, %Y (and one of these is a select operand)
90 // %C = and %A, %B
91 // %D = select %C, %TV, %FV
92 // -->
93 // %FV
94
95 // %A = icmp ne %TV, %FV
96 // %B = icmp ne %X, %Y (and one of these is a select operand)
97 // %C = or %A, %B
98 // %D = select %C, %TV, %FV
99 // -->
100 // %TV
101 Value *X, *Y;
102 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
103 m_Specific(FalseVal)),
104 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
David Bolvanskyf9476082018-07-28 06:55:51 +0000105 Pred1 != Pred2 || Pred1 != ExpectedPred)
106 return nullptr;
107
David Bolvansky16d8a692018-07-31 14:17:15 +0000108 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
109 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
110
111 return nullptr;
David Bolvanskyf9476082018-07-28 06:55:51 +0000112}
113
Sanjay Patel35ed2412017-04-16 17:43:11 +0000114/// For a boolean type or a vector of boolean type, return false or a vector
115/// with every element false.
Duncan Sandsc1c92712011-07-26 15:03:53 +0000116static Constant *getFalse(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +0000117 return ConstantInt::getFalse(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +0000118}
119
Sanjay Patel35ed2412017-04-16 17:43:11 +0000120/// For a boolean type or a vector of boolean type, return true or a vector
121/// with every element true.
Duncan Sandsc1c92712011-07-26 15:03:53 +0000122static Constant *getTrue(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +0000123 return ConstantInt::getTrue(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +0000124}
125
Duncan Sands3d5692a2011-10-30 19:56:36 +0000126/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
127static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
128 Value *RHS) {
129 CmpInst *Cmp = dyn_cast<CmpInst>(V);
130 if (!Cmp)
131 return false;
132 CmpInst::Predicate CPred = Cmp->getPredicate();
133 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
134 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
135 return true;
136 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
137 CRHS == LHS;
138}
139
Sanjay Patel472cc782016-01-11 22:14:42 +0000140/// Does the given value dominate the specified phi node?
Sanjay Patel5da361a2018-04-10 18:38:19 +0000141static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
Duncan Sands5ffc2982010-11-16 12:16:38 +0000142 Instruction *I = dyn_cast<Instruction>(V);
143 if (!I)
144 // Arguments and constants dominate all instructions.
145 return true;
146
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000147 // If we are processing instructions (and/or basic blocks) that have not been
148 // fully added to a function, the parent nodes may still be null. Simply
149 // return the conservative answer in these cases.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000150 if (!I->getParent() || !P->getParent() || !I->getFunction())
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000151 return false;
152
Duncan Sands5ffc2982010-11-16 12:16:38 +0000153 // If we have a DominatorTree then do a precise test.
Daniel Berlin71ff6632017-05-31 01:47:24 +0000154 if (DT)
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000155 return DT->dominates(I, P);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000156
David Majnemer8a1c45d2015-12-12 05:38:55 +0000157 // Otherwise, if the instruction is in the entry block and is not an invoke,
158 // then it obviously dominates all phi nodes.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000159 if (I->getParent() == &I->getFunction()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000160 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000161 return true;
162
163 return false;
164}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000165
Sanjay Patel472cc782016-01-11 22:14:42 +0000166/// Simplify "A op (B op' C)" by distributing op over op', turning it into
167/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000168/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
169/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
170/// Returns the simplified value, or null if no simplification was performed.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000171static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
Craig Topper9c913bf2017-05-19 16:56:53 +0000172 Instruction::BinaryOps OpcodeToExpand,
173 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000174 // Recursion is always used, so bail out at once if we already hit the limit.
175 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000176 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000177
178 // Check whether the expression has the form "(A op' B) op C".
179 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
180 if (Op0->getOpcode() == OpcodeToExpand) {
181 // It does! Try turning it into "(A op C) op' (B op C)".
182 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
183 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000184 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
185 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000186 // They do! Return "L op' R" if it simplifies or is already available.
187 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000188 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
189 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000190 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000191 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000192 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000193 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000194 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000195 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000196 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000197 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000198 }
199 }
200
201 // Check whether the expression has the form "A op (B op' C)".
202 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
203 if (Op1->getOpcode() == OpcodeToExpand) {
204 // It does! Try turning it into "(A op B) op' (A op C)".
205 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
206 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000207 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
208 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000209 // They do! Return "L op' R" if it simplifies or is already available.
210 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000211 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
212 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000213 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000214 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000215 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000216 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000217 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000218 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000219 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000220 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000221 }
222 }
223
Craig Topper9f008862014-04-15 04:59:12 +0000224 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000225}
226
Sanjay Patel472cc782016-01-11 22:14:42 +0000227/// Generic simplifications for associative binary operations.
228/// Returns the simpler value, or null if none was found.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000229static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
Craig Topper9c913bf2017-05-19 16:56:53 +0000230 Value *LHS, Value *RHS,
231 const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000232 unsigned MaxRecurse) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000233 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
234
235 // Recursion is always used, so bail out at once if we already hit the limit.
236 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000237 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000238
239 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
240 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
241
242 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
243 if (Op0 && Op0->getOpcode() == Opcode) {
244 Value *A = Op0->getOperand(0);
245 Value *B = Op0->getOperand(1);
246 Value *C = RHS;
247
248 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000249 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000250 // It does! Return "A op V" if it simplifies or is already available.
251 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000252 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000253 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000254 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000255 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000256 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000257 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000258 }
259 }
260
261 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
262 if (Op1 && Op1->getOpcode() == Opcode) {
263 Value *A = LHS;
264 Value *B = Op1->getOperand(0);
265 Value *C = Op1->getOperand(1);
266
267 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000268 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000269 // It does! Return "V op C" if it simplifies or is already available.
270 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000271 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000272 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000273 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000274 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000275 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000276 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000277 }
278 }
279
280 // The remaining transforms require commutativity as well as associativity.
281 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000282 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283
284 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
285 if (Op0 && Op0->getOpcode() == Opcode) {
286 Value *A = Op0->getOperand(0);
287 Value *B = Op0->getOperand(1);
288 Value *C = RHS;
289
290 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000291 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292 // It does! Return "V op B" if it simplifies or is already available.
293 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000294 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000295 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000296 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000297 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000298 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000299 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000300 }
301 }
302
303 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
304 if (Op1 && Op1->getOpcode() == Opcode) {
305 Value *A = LHS;
306 Value *B = Op1->getOperand(0);
307 Value *C = Op1->getOperand(1);
308
309 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000310 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000311 // It does! Return "B op V" if it simplifies or is already available.
312 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000313 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000314 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000315 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000316 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000317 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000318 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000319 }
320 }
321
Craig Topper9f008862014-04-15 04:59:12 +0000322 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000323}
324
Sanjay Patel472cc782016-01-11 22:14:42 +0000325/// In the case of a binary operation with a select instruction as an operand,
326/// try to simplify the binop by seeing whether evaluating it on both branches
327/// of the select results in the same value. Returns the common value if so,
328/// otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000329static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000330 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000331 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000332 // Recursion is always used, so bail out at once if we already hit the limit.
333 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000334 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000335
Duncan Sandsb0579e92010-11-10 13:00:08 +0000336 SelectInst *SI;
337 if (isa<SelectInst>(LHS)) {
338 SI = cast<SelectInst>(LHS);
339 } else {
340 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
341 SI = cast<SelectInst>(RHS);
342 }
343
344 // Evaluate the BinOp on the true and false branches of the select.
345 Value *TV;
346 Value *FV;
347 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000348 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
349 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000350 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000351 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
352 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000353 }
354
Duncan Sandse3c53952011-01-01 16:12:09 +0000355 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000356 // If they both failed to simplify then return null.
357 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000358 return TV;
359
360 // If one branch simplified to undef, return the other one.
361 if (TV && isa<UndefValue>(TV))
362 return FV;
363 if (FV && isa<UndefValue>(FV))
364 return TV;
365
366 // If applying the operation did not change the true and false select values,
367 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000368 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000369 return SI;
370
371 // If one branch simplified and the other did not, and the simplified
372 // value is equal to the unsimplified one, return the simplified value.
373 // For example, select (cond, X, X & Z) & Z -> X & Z.
374 if ((FV && !TV) || (TV && !FV)) {
375 // Check that the simplified value has the form "X op Y" where "op" is the
376 // same as the original operation.
377 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
Zachary Turner260fe3e2017-12-14 22:07:03 +0000378 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
Duncan Sandsb0579e92010-11-10 13:00:08 +0000379 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
380 // We already know that "op" is the same as for the simplified value. See
381 // if the operands match too. If so, return the simplified value.
382 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
383 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
384 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000385 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
386 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000387 return Simplified;
388 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000389 Simplified->getOperand(1) == UnsimplifiedLHS &&
390 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000391 return Simplified;
392 }
393 }
394
Craig Topper9f008862014-04-15 04:59:12 +0000395 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000396}
397
Sanjay Patel472cc782016-01-11 22:14:42 +0000398/// In the case of a comparison with a select instruction, try to simplify the
399/// comparison by seeing whether both branches of the select result in the same
400/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000401static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000402 Value *RHS, const SimplifyQuery &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000403 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000404 // Recursion is always used, so bail out at once if we already hit the limit.
405 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000406 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000407
Duncan Sandsb0579e92010-11-10 13:00:08 +0000408 // Make sure the select is on the LHS.
409 if (!isa<SelectInst>(LHS)) {
410 std::swap(LHS, RHS);
411 Pred = CmpInst::getSwappedPredicate(Pred);
412 }
413 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
414 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000415 Value *Cond = SI->getCondition();
416 Value *TV = SI->getTrueValue();
417 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000418
Duncan Sands06504022011-02-03 09:37:39 +0000419 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000420 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000421 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000422 if (TCmp == Cond) {
423 // It not only simplified, it simplified to the select condition. Replace
424 // it with 'true'.
425 TCmp = getTrue(Cond->getType());
426 } else if (!TCmp) {
427 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
428 // condition then we can replace it with 'true'. Otherwise give up.
429 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000430 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000431 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000432 }
433
Duncan Sands3d5692a2011-10-30 19:56:36 +0000434 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000435 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000436 if (FCmp == Cond) {
437 // It not only simplified, it simplified to the select condition. Replace
438 // it with 'false'.
439 FCmp = getFalse(Cond->getType());
440 } else if (!FCmp) {
441 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
442 // condition then we can replace it with 'false'. Otherwise give up.
443 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000445 FCmp = getFalse(Cond->getType());
446 }
447
448 // If both sides simplified to the same value, then use it as the result of
449 // the original comparison.
450 if (TCmp == FCmp)
451 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000452
453 // The remaining cases only make sense if the select condition has the same
454 // type as the result of the comparison, so bail out if this is not so.
455 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000456 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000457 // If the false value simplified to false, then the result of the compare
458 // is equal to "Cond && TCmp". This also catches the case when the false
459 // value simplified to false and the true value to true, returning "Cond".
460 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000461 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000462 return V;
463 // If the true value simplified to true, then the result of the compare
464 // is equal to "Cond || FCmp".
465 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000466 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000467 return V;
468 // Finally, if the false value simplified to true and the true value to
469 // false, then the result of the compare is equal to "!Cond".
470 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
471 if (Value *V =
472 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000473 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000474 return V;
475
Craig Topper9f008862014-04-15 04:59:12 +0000476 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000477}
478
Sanjay Patel472cc782016-01-11 22:14:42 +0000479/// In the case of a binary operation with an operand that is a PHI instruction,
480/// try to simplify the binop by seeing whether evaluating it on the incoming
481/// phi values yields the same result for every value. If so returns the common
482/// value, otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000483static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000484 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000485 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000486 // Recursion is always used, so bail out at once if we already hit the limit.
487 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000488 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000489
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000490 PHINode *PI;
491 if (isa<PHINode>(LHS)) {
492 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000493 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000494 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000495 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000496 } else {
497 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
498 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000499 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000500 if (!valueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000501 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000502 }
503
504 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000505 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000506 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000507 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000508 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000509 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000510 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
511 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 // If the operation failed to simplify, or simplified to a different value
513 // to previously, then give up.
514 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000515 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000516 CommonValue = V;
517 }
518
519 return CommonValue;
520}
521
Sanjay Patel472cc782016-01-11 22:14:42 +0000522/// In the case of a comparison with a PHI instruction, try to simplify the
523/// comparison by seeing whether comparing with all of the incoming phi values
524/// yields the same result every time. If so returns the common result,
525/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000526static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000527 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000528 // Recursion is always used, so bail out at once if we already hit the limit.
529 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000530 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000531
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000532 // Make sure the phi is on the LHS.
533 if (!isa<PHINode>(LHS)) {
534 std::swap(LHS, RHS);
535 Pred = CmpInst::getSwappedPredicate(Pred);
536 }
537 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
538 PHINode *PI = cast<PHINode>(LHS);
539
Duncan Sands5ffc2982010-11-16 12:16:38 +0000540 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000541 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000542 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000543
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000544 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000545 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000546 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000547 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000548 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000549 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000553 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000554 CommonValue = V;
555 }
556
557 return CommonValue;
558}
559
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000560static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
561 Value *&Op0, Value *&Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000562 const SimplifyQuery &Q) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000563 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
564 if (auto *CRHS = dyn_cast<Constant>(Op1))
565 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
566
567 // Canonicalize the constant to the RHS if this is a commutative operation.
568 if (Instruction::isCommutative(Opcode))
569 std::swap(Op0, Op1);
570 }
571 return nullptr;
572}
573
Sanjay Patel472cc782016-01-11 22:14:42 +0000574/// Given operands for an Add, see if we can fold the result.
575/// If not, this returns null.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000576static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000577 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000578 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
579 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000580
Duncan Sands0a2c41682010-12-15 14:07:39 +0000581 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000582 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000583 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000584
Duncan Sands0a2c41682010-12-15 14:07:39 +0000585 // X + 0 -> X
586 if (match(Op1, m_Zero()))
587 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000588
Chen Zhengfdf13ef2018-07-12 03:06:04 +0000589 // If two operands are negative, return 0.
590 if (isKnownNegation(Op0, Op1))
591 return Constant::getNullValue(Op0->getType());
592
Duncan Sands0a2c41682010-12-15 14:07:39 +0000593 // X + (Y - X) -> Y
594 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000595 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000596 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000597 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
598 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000599 return Y;
600
601 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000602 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000603 if (match(Op0, m_Not(m_Specific(Op1))) ||
604 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000605 return Constant::getAllOnesValue(Ty);
606
Craig Topperbcfd2d12017-04-20 16:56:25 +0000607 // add nsw/nuw (xor Y, signmask), signmask --> Y
Sanjay Patelfe672552017-02-18 21:59:09 +0000608 // The no-wrapping add guarantees that the top bit will be set by the add.
609 // Therefore, the xor must be clearing the already set sign bit of Y.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000610 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
Craig Topperbcfd2d12017-04-20 16:56:25 +0000611 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000612 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000613
Roman Lebedevb060ce42018-06-08 15:44:47 +0000614 // add nuw %x, -1 -> -1, because %x can only be 0.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000615 if (IsNUW && match(Op1, m_AllOnes()))
Roman Lebedevb060ce42018-06-08 15:44:47 +0000616 return Op1; // Which is -1.
617
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000618 /// i1 add -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000619 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000620 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000621 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000622
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000623 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000624 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000625 MaxRecurse))
626 return V;
627
Duncan Sandsb238de02010-11-19 09:20:39 +0000628 // Threading Add over selects and phi nodes is pointless, so don't bother.
629 // Threading over the select in "A + select(cond, B, C)" means evaluating
630 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
631 // only if B and C are equal. If B and C are equal then (since we assume
632 // that operands have already been simplified) "select(cond, B, C)" should
633 // have been simplified to the common value of B and C already. Analysing
634 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
635 // for threading over phi nodes.
636
Craig Topper9f008862014-04-15 04:59:12 +0000637 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000638}
639
Roman Lebedevf87321a2018-06-08 15:44:53 +0000640Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000641 const SimplifyQuery &Query) {
Roman Lebedevf87321a2018-06-08 15:44:53 +0000642 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000643}
644
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000645/// Compute the base pointer and cumulative constant offsets for V.
Chandler Carrutha0796552012-03-12 11:19:31 +0000646///
647/// This strips all constant offsets off of V, leaving it the base pointer, and
648/// accumulates the total constant offset applied in the returned constant. It
649/// returns 0 if V is not a pointer, and returns the constant '0' if there are
650/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000651///
652/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
653/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
654/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000655static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000656 bool AllowNonInbounds = false) {
Craig Topper95d23472017-07-09 07:04:00 +0000657 assert(V->getType()->isPtrOrPtrVectorTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000658
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000659 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000660 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000661
662 // Even though we don't look through PHI nodes, we could be called on an
663 // instruction in an unreachable block, which may be on a cycle.
664 SmallPtrSet<Value *, 4> Visited;
665 Visited.insert(V);
666 do {
667 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000668 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000669 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000670 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000671 V = GEP->getPointerOperand();
672 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000673 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000674 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000675 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000676 break;
677 V = GA->getAliasee();
678 } else {
Chandler Carruthdac20a82019-02-11 07:54:10 +0000679 if (auto *Call = dyn_cast<CallBase>(V))
680 if (Value *RV = Call->getReturnedArgOperand()) {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000681 V = RV;
682 continue;
683 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000684 break;
685 }
Craig Topper95d23472017-07-09 07:04:00 +0000686 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000687 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000688
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000689 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
690 if (V->getType()->isVectorTy())
691 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
692 OffsetIntPtr);
693 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000694}
695
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000696/// Compute the constant difference between two pointer values.
Chandler Carrutha0796552012-03-12 11:19:31 +0000697/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000698static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
699 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000700 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
701 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000702
703 // If LHS and RHS are not related via constant offsets to the same base
704 // value, there is nothing we can do here.
705 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000706 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000707
708 // Otherwise, the difference of LHS - RHS can be computed as:
709 // LHS - RHS
710 // = (LHSOffset + Base) - (RHSOffset + Base)
711 // = LHSOffset - RHSOffset
712 return ConstantExpr::getSub(LHSOffset, RHSOffset);
713}
714
Sanjay Patel472cc782016-01-11 22:14:42 +0000715/// Given operands for a Sub, see if we can fold the result.
716/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000717static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000718 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000719 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
720 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000721
722 // X - undef -> undef
723 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000724 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000725 return UndefValue::get(Op0->getType());
726
727 // X - 0 -> X
728 if (match(Op1, m_Zero()))
729 return Op0;
730
731 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000732 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000733 return Constant::getNullValue(Op0->getType());
734
Sanjay Patelefd88852016-10-19 21:23:45 +0000735 // Is this a negation?
736 if (match(Op0, m_Zero())) {
737 // 0 - X -> 0 if the sub is NUW.
738 if (isNUW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000739 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000740
Craig Topper8205a1a2017-05-24 16:53:07 +0000741 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +0000742 if (Known.Zero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000743 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
744 // Op1 must be 0 because negating the minimum signed value is undefined.
745 if (isNSW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000746 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000747
748 // 0 - X -> X if X is 0 or the minimum signed value.
749 return Op1;
750 }
751 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000752
Duncan Sands99589d02011-01-18 11:50:19 +0000753 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
754 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000755 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000756 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
757 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000758 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000759 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000760 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000761 // It does, we successfully reassociated!
762 ++NumReassoc;
763 return W;
764 }
765 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000766 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000767 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000768 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000769 // It does, we successfully reassociated!
770 ++NumReassoc;
771 return W;
772 }
773 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000774
Duncan Sands99589d02011-01-18 11:50:19 +0000775 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
776 // For example, X - (X + 1) -> -1
777 X = Op0;
778 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
779 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000780 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000781 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000782 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000783 // It does, we successfully reassociated!
784 ++NumReassoc;
785 return W;
786 }
787 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000788 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000789 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000790 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000791 // It does, we successfully reassociated!
792 ++NumReassoc;
793 return W;
794 }
795 }
796
797 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
798 // For example, X - (X - Y) -> Y.
799 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000800 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
801 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000802 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000803 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000804 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000805 // It does, we successfully reassociated!
806 ++NumReassoc;
807 return W;
808 }
809
Duncan Sands395ac42d2012-03-13 14:07:05 +0000810 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
811 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
812 match(Op1, m_Trunc(m_Value(Y))))
813 if (X->getType() == Y->getType())
814 // See if "V === X - Y" simplifies.
815 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
816 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000817 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
818 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000819 // It does, return the simplified "trunc V".
820 return W;
821
822 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000823 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000824 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000825 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000826 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
827
Duncan Sands99589d02011-01-18 11:50:19 +0000828 // i1 sub -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000829 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000830 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000831 return V;
832
Duncan Sands0a2c41682010-12-15 14:07:39 +0000833 // Threading Sub over selects and phi nodes is pointless, so don't bother.
834 // Threading over the select in "A - select(cond, B, C)" means evaluating
835 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
836 // only if B and C are equal. If B and C are equal then (since we assume
837 // that operands have already been simplified) "select(cond, B, C)" should
838 // have been simplified to the common value of B and C already. Analysing
839 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
840 // for threading over phi nodes.
841
Craig Topper9f008862014-04-15 04:59:12 +0000842 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000843}
844
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000845Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000846 const SimplifyQuery &Q) {
847 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
848}
849
Sanjay Patel472cc782016-01-11 22:14:42 +0000850/// Given operands for a Mul, see if we can fold the result.
851/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000852static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000853 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000854 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
855 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000856
857 // X * undef -> 0
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000858 // X * 0 -> 0
Sanjay Patel30be6652018-04-22 17:07:44 +0000859 if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
860 return Constant::getNullValue(Op0->getType());
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000861
862 // X * 1 -> X
863 if (match(Op1, m_One()))
864 return Op0;
865
Duncan Sandsb67edc62011-01-30 18:03:50 +0000866 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000867 Value *X = nullptr;
Florian Hahn19f9e322018-08-17 14:39:04 +0000868 if (Q.IIQ.UseInstrInfo &&
869 (match(Op0,
870 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
871 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000872 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000873
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000874 // i1 mul -> and.
Craig Topperfde47232017-07-09 07:04:03 +0000875 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000876 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000877 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000878
879 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000880 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000881 MaxRecurse))
882 return V;
883
Dmitry Venikovd2257be2018-01-02 05:47:42 +0000884 // Mul distributes over Add. Try some generic simplifications based on this.
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000885 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000886 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000887 return V;
888
889 // If the operation is with the result of a select instruction, check whether
890 // operating on either branch of the select always yields the same value.
891 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000892 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000893 MaxRecurse))
894 return V;
895
896 // If the operation is with the result of a phi instruction, check whether
897 // operating on all incoming values of the phi always yields the same value.
898 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000899 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000900 MaxRecurse))
901 return V;
902
Craig Topper9f008862014-04-15 04:59:12 +0000903 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000904}
905
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000906Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
907 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
908}
909
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000910/// Check for common or similar folds of integer division or integer remainder.
Sanjay Patelfa877fd2017-09-11 13:34:27 +0000911/// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000912static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
913 Type *Ty = Op0->getType();
914
915 // X / undef -> undef
916 // X % undef -> undef
917 if (match(Op1, m_Undef()))
918 return Op1;
919
920 // X / 0 -> undef
921 // X % 0 -> undef
922 // We don't need to preserve faults!
923 if (match(Op1, m_Zero()))
924 return UndefValue::get(Ty);
925
Zvi Rackover51f0d642018-01-24 17:22:00 +0000926 // If any element of a constant divisor vector is zero or undef, the whole op
927 // is undef.
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000928 auto *Op1C = dyn_cast<Constant>(Op1);
929 if (Op1C && Ty->isVectorTy()) {
930 unsigned NumElts = Ty->getVectorNumElements();
931 for (unsigned i = 0; i != NumElts; ++i) {
932 Constant *Elt = Op1C->getAggregateElement(i);
Zvi Rackover51f0d642018-01-24 17:22:00 +0000933 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000934 return UndefValue::get(Ty);
935 }
936 }
937
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000938 // undef / X -> 0
939 // undef % X -> 0
940 if (match(Op0, m_Undef()))
941 return Constant::getNullValue(Ty);
942
943 // 0 / X -> 0
944 // 0 % X -> 0
945 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +0000946 return Constant::getNullValue(Op0->getType());
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000947
948 // X / X -> 1
949 // X % X -> 0
950 if (Op0 == Op1)
951 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
952
953 // X / 1 -> X
954 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +0000955 // If this is a boolean op (single-bit element type), we can't have
956 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
Sanjay Patel1e911fa2018-06-25 18:51:21 +0000957 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
958 Value *X;
959 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
960 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000961 return IsDiv ? Op0 : Constant::getNullValue(Ty);
962
963 return nullptr;
964}
965
Sanjay Patelcca8f782017-09-14 14:09:11 +0000966/// Given a predicate and two operands, return true if the comparison is true.
967/// This is a helper for div/rem simplification where we return some other value
968/// when we can prove a relationship between the operands.
969static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
970 const SimplifyQuery &Q, unsigned MaxRecurse) {
971 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
972 Constant *C = dyn_cast_or_null<Constant>(V);
973 return (C && C->isAllOnesValue());
974}
975
976/// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
977/// to simplify X % Y to X.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000978static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
Sanjay Patelcca8f782017-09-14 14:09:11 +0000979 unsigned MaxRecurse, bool IsSigned) {
980 // Recursion is always used, so bail out at once if we already hit the limit.
981 if (!MaxRecurse--)
982 return false;
983
984 if (IsSigned) {
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000985 // |X| / |Y| --> 0
986 //
987 // We require that 1 operand is a simple constant. That could be extended to
988 // 2 variables if we computed the sign bit for each.
989 //
990 // Make sure that a constant is not the minimum signed value because taking
991 // the abs() of that is undefined.
992 Type *Ty = X->getType();
993 const APInt *C;
994 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
995 // Is the variable divisor magnitude always greater than the constant
996 // dividend magnitude?
997 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
998 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
999 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1000 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1001 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1002 return true;
1003 }
1004 if (match(Y, m_APInt(C))) {
1005 // Special-case: we can't take the abs() of a minimum signed value. If
1006 // that's the divisor, then all we have to do is prove that the dividend
1007 // is also not the minimum signed value.
1008 if (C->isMinSignedValue())
1009 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1010
1011 // Is the variable dividend magnitude always less than the constant
1012 // divisor magnitude?
1013 // |X| < |C| --> X > -abs(C) and X < abs(C)
1014 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1015 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1016 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1017 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1018 return true;
1019 }
Sanjay Patelcca8f782017-09-14 14:09:11 +00001020 return false;
1021 }
1022
1023 // IsSigned == false.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +00001024 // Is the dividend unsigned less than the divisor?
1025 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
Sanjay Patelcca8f782017-09-14 14:09:11 +00001026}
1027
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001028/// These are simplifications common to SDiv and UDiv.
1029static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001030 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001031 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1032 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +00001033
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001034 if (Value *V = simplifyDivRem(Op0, Op1, true))
1035 return V;
1036
Sanjay Patelcca8f782017-09-14 14:09:11 +00001037 bool IsSigned = Opcode == Instruction::SDiv;
Duncan Sands65995fa2011-01-28 18:50:50 +00001038
Duncan Sands771e82a2011-01-28 16:51:11 +00001039 // (X * Y) / Y -> X if the multiplication does not overflow.
Sanjay Patel33cb8452018-01-19 16:12:55 +00001040 Value *X;
1041 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1042 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1043 // If the Mul does not overflow, then we are good to go.
Florian Hahn19f9e322018-08-17 14:39:04 +00001044 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1045 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
Duncan Sands5747aba2011-02-02 20:52:00 +00001046 return X;
Sanjay Patel33cb8452018-01-19 16:12:55 +00001047 // If X has the form X = A / Y, then X * Y cannot overflow.
1048 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1049 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1050 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001051 }
1052
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 // (X rem Y) / Y -> 0
Sanjay Patelcca8f782017-09-14 14:09:11 +00001054 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1055 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
Duncan Sands65995fa2011-01-28 18:50:50 +00001056 return Constant::getNullValue(Op0->getType());
1057
David Majnemercb9d5962014-10-11 10:20:01 +00001058 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1059 ConstantInt *C1, *C2;
Sanjay Patelcca8f782017-09-14 14:09:11 +00001060 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
David Majnemercb9d5962014-10-11 10:20:01 +00001061 match(Op1, m_ConstantInt(C2))) {
1062 bool Overflow;
Craig Topper9b71a402017-04-19 21:09:45 +00001063 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
David Majnemercb9d5962014-10-11 10:20:01 +00001064 if (Overflow)
1065 return Constant::getNullValue(Op0->getType());
1066 }
1067
Duncan Sands65995fa2011-01-28 18:50:50 +00001068 // If the operation is with the result of a select instruction, check whether
1069 // operating on either branch of the select always yields the same value.
1070 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001071 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001072 return V;
1073
1074 // If the operation is with the result of a phi instruction, check whether
1075 // operating on all incoming values of the phi always yields the same value.
1076 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001077 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001078 return V;
1079
Sanjay Patelcca8f782017-09-14 14:09:11 +00001080 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1081 return Constant::getNullValue(Op0->getType());
1082
Craig Topper9f008862014-04-15 04:59:12 +00001083 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001084}
1085
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001086/// These are simplifications common to SRem and URem.
1087static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001088 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001089 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1090 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001091
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001092 if (Value *V = simplifyDivRem(Op0, Op1, false))
1093 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001094
David Majnemerb435a422014-09-17 04:16:35 +00001095 // (X % Y) % Y -> X % Y
1096 if ((Opcode == Instruction::SRem &&
1097 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1098 (Opcode == Instruction::URem &&
1099 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001100 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001101
Anton Bikineev82f61152018-01-23 09:27:47 +00001102 // (X << Y) % X -> 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001103 if (Q.IIQ.UseInstrInfo &&
1104 ((Opcode == Instruction::SRem &&
1105 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1106 (Opcode == Instruction::URem &&
1107 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
Anton Bikineev82f61152018-01-23 09:27:47 +00001108 return Constant::getNullValue(Op0->getType());
1109
Duncan Sandsa3e36992011-05-02 16:27:02 +00001110 // If the operation is with the result of a select instruction, check whether
1111 // operating on either branch of the select always yields the same value.
1112 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001113 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001114 return V;
1115
1116 // If the operation is with the result of a phi instruction, check whether
1117 // operating on all incoming values of the phi always yields the same value.
1118 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001119 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001120 return V;
1121
Sanjay Patelcca8f782017-09-14 14:09:11 +00001122 // If X / Y == 0, then X % Y == X.
1123 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1124 return Op0;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001125
1126 return nullptr;
1127}
1128
1129/// Given operands for an SDiv, see if we can fold the result.
1130/// If not, this returns null.
1131static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1132 unsigned MaxRecurse) {
Chen Zheng69bb0642018-07-21 12:27:54 +00001133 // If two operands are negated and no signed overflow, return -1.
1134 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1135 return Constant::getAllOnesValue(Op0->getType());
1136
Sanjay Patelcca8f782017-09-14 14:09:11 +00001137 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001138}
1139
1140Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1141 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1142}
1143
1144/// Given operands for a UDiv, see if we can fold the result.
1145/// If not, this returns null.
1146static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1147 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001148 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001149}
1150
1151Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1152 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1153}
1154
Sanjay Patel472cc782016-01-11 22:14:42 +00001155/// Given operands for an SRem, see if we can fold the result.
1156/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001157static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001158 unsigned MaxRecurse) {
Sanjay Patel2b7e3102018-06-26 15:32:54 +00001159 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1160 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1161 Value *X;
1162 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1163 return ConstantInt::getNullValue(Op0->getType());
1164
Chen Zhengf801d0f2018-07-20 13:00:47 +00001165 // If the two operands are negated, return 0.
1166 if (isKnownNegation(Op0, Op1))
Chen Zheng69bb0642018-07-21 12:27:54 +00001167 return ConstantInt::getNullValue(Op0->getType());
Chen Zhengf801d0f2018-07-20 13:00:47 +00001168
Sanjay Patelcca8f782017-09-14 14:09:11 +00001169 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001170}
1171
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001172Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1173 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1174}
1175
Sanjay Patel472cc782016-01-11 22:14:42 +00001176/// Given operands for a URem, see if we can fold the result.
1177/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001178static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001179 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001180 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001181}
1182
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001183Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1184 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1185}
1186
Sanjay Patel472cc782016-01-11 22:14:42 +00001187/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001188static bool isUndefShift(Value *Amount) {
1189 Constant *C = dyn_cast<Constant>(Amount);
1190 if (!C)
1191 return false;
1192
1193 // X shift by undef -> undef because it may shift by the bitwidth.
1194 if (isa<UndefValue>(C))
1195 return true;
1196
1197 // Shifting by the bitwidth or more is undefined.
1198 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1199 if (CI->getValue().getLimitedValue() >=
1200 CI->getType()->getScalarSizeInBits())
1201 return true;
1202
1203 // If all lanes of a vector shift are undefined the whole shift is.
1204 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1205 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1206 if (!isUndefShift(C->getAggregateElement(I)))
1207 return false;
1208 return true;
1209 }
1210
1211 return false;
1212}
1213
Sanjay Patel472cc782016-01-11 22:14:42 +00001214/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1215/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001216static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001217 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001218 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1219 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001220
Duncan Sands571fd9a2011-01-14 14:44:12 +00001221 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001222 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001223 return Constant::getNullValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001224
Duncan Sands571fd9a2011-01-14 14:44:12 +00001225 // X shift by 0 -> X
Sanjay Patelad0bfb82018-06-26 17:31:38 +00001226 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1227 // would be poison.
1228 Value *X;
1229 if (match(Op1, m_Zero()) ||
1230 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001231 return Op0;
1232
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001233 // Fold undefined shifts.
1234 if (isUndefShift(Op1))
1235 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001236
Duncan Sands571fd9a2011-01-14 14:44:12 +00001237 // If the operation is with the result of a select instruction, check whether
1238 // operating on either branch of the select always yields the same value.
1239 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001240 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001241 return V;
1242
1243 // If the operation is with the result of a phi instruction, check whether
1244 // operating on all incoming values of the phi always yields the same value.
1245 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001246 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001247 return V;
1248
Sanjay Patel6786bc52016-05-10 20:46:54 +00001249 // If any bits in the shift amount make that value greater than or equal to
1250 // the number of bits in the type, the shift is undefined.
Craig Topper8205a1a2017-05-24 16:53:07 +00001251 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1252 if (Known.One.getLimitedValue() >= Known.getBitWidth())
Sanjay Patel6786bc52016-05-10 20:46:54 +00001253 return UndefValue::get(Op0->getType());
1254
1255 // If all valid bits in the shift amount are known zero, the first operand is
1256 // unchanged.
Craig Topper8205a1a2017-05-24 16:53:07 +00001257 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
Craig Topper8df66c62017-05-12 17:20:30 +00001258 if (Known.countMinTrailingZeros() >= NumValidShiftBits)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001259 return Op0;
1260
Craig Topper9f008862014-04-15 04:59:12 +00001261 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001262}
1263
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001264/// Given operands for an Shl, LShr or AShr, see if we can
David Majnemerbf7550e2014-11-05 00:59:59 +00001265/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001266static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001267 Value *Op1, bool isExact, const SimplifyQuery &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001268 unsigned MaxRecurse) {
1269 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1270 return V;
1271
1272 // X >> X -> 0
1273 if (Op0 == Op1)
1274 return Constant::getNullValue(Op0->getType());
1275
David Majnemer65c52ae2014-12-17 01:54:33 +00001276 // undef >> X -> 0
1277 // undef >> X -> undef (if it's exact)
1278 if (match(Op0, m_Undef()))
1279 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1280
David Majnemerbf7550e2014-11-05 00:59:59 +00001281 // The low bit cannot be shifted out of an exact shift if it is set.
1282 if (isExact) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001283 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +00001284 if (Op0Known.One[0])
David Majnemerbf7550e2014-11-05 00:59:59 +00001285 return Op0;
1286 }
1287
1288 return nullptr;
1289}
1290
Sanjay Patel472cc782016-01-11 22:14:42 +00001291/// Given operands for an Shl, see if we can fold the result.
1292/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001293static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001294 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001295 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001296 return V;
1297
1298 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001299 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001300 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001301 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001302
Chris Lattner9e4aa022011-02-09 17:15:04 +00001303 // (X >> A) << A -> X
1304 Value *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001305 if (Q.IIQ.UseInstrInfo &&
1306 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001307 return X;
Roman Lebedev26838022018-06-07 20:03:45 +00001308
1309 // shl nuw i8 C, %x -> C iff C has sign bit set.
1310 if (isNUW && match(Op0, m_Negative()))
1311 return Op0;
1312 // NOTE: could use computeKnownBits() / LazyValueInfo,
1313 // but the cost-benefit analysis suggests it isn't worth it.
1314
Craig Topper9f008862014-04-15 04:59:12 +00001315 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001316}
1317
Chris Lattner9e4aa022011-02-09 17:15:04 +00001318Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001319 const SimplifyQuery &Q) {
1320 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1321}
1322
Sanjay Patel472cc782016-01-11 22:14:42 +00001323/// Given operands for an LShr, see if we can fold the result.
1324/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001325static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001326 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001327 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1328 MaxRecurse))
1329 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001330
Chris Lattner9e4aa022011-02-09 17:15:04 +00001331 // (X << A) >> A -> X
1332 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001333 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001334 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001335
Hiroshi Inoue02f79ea2018-08-01 04:40:32 +00001336 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1337 // We can return X as we do in the above case since OR alters no bits in X.
1338 // SimplifyDemandedBits in InstCombine can do more general optimization for
1339 // bit manipulation. This pattern aims to provide opportunities for other
1340 // optimizers by supporting a simple but common case in InstSimplify.
1341 Value *Y;
1342 const APInt *ShRAmt, *ShLAmt;
1343 if (match(Op1, m_APInt(ShRAmt)) &&
1344 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1345 *ShRAmt == *ShLAmt) {
1346 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1347 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1348 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
Benjamin Kramerbae6aab2018-08-12 11:43:03 +00001349 if (ShRAmt->uge(EffWidthY))
Hiroshi Inoue02f79ea2018-08-01 04:40:32 +00001350 return X;
1351 }
1352
Craig Topper9f008862014-04-15 04:59:12 +00001353 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001354}
1355
Chris Lattner9e4aa022011-02-09 17:15:04 +00001356Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001357 const SimplifyQuery &Q) {
1358 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1359}
1360
Sanjay Patel472cc782016-01-11 22:14:42 +00001361/// Given operands for an AShr, see if we can fold the result.
1362/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001363static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001364 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001365 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1366 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001367 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001368
Sanjay Pateladf6e882018-02-18 18:05:08 +00001369 // all ones >>a X -> -1
1370 // Do not return Op0 because it may contain undef elements if it's a vector.
Duncan Sands7f60dc12011-01-14 00:37:45 +00001371 if (match(Op0, m_AllOnes()))
Sanjay Pateladf6e882018-02-18 18:05:08 +00001372 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001373
Chris Lattner9e4aa022011-02-09 17:15:04 +00001374 // (X << A) >> A -> X
1375 Value *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001376 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001377 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001378
Suyog Sarda68862412014-07-17 06:28:15 +00001379 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001380 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001381 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1382 return Op0;
1383
Craig Topper9f008862014-04-15 04:59:12 +00001384 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001385}
1386
Chris Lattner9e4aa022011-02-09 17:15:04 +00001387Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001388 const SimplifyQuery &Q) {
1389 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1390}
1391
Craig Topper348314d2017-05-26 22:42:34 +00001392/// Commuted variants are assumed to be handled by calling this function again
1393/// with the parameters swapped.
David Majnemer1af36e52014-12-06 10:51:40 +00001394static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1395 ICmpInst *UnsignedICmp, bool IsAnd) {
1396 Value *X, *Y;
1397
1398 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001399 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1400 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001401 return nullptr;
1402
1403 ICmpInst::Predicate UnsignedPred;
1404 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1405 ICmpInst::isUnsigned(UnsignedPred))
1406 ;
1407 else if (match(UnsignedICmp,
Sanjay Patel0c57de42018-06-20 14:22:49 +00001408 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
David Majnemer1af36e52014-12-06 10:51:40 +00001409 ICmpInst::isUnsigned(UnsignedPred))
1410 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1411 else
1412 return nullptr;
1413
1414 // X < Y && Y != 0 --> X < Y
1415 // X < Y || Y != 0 --> Y != 0
1416 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1417 return IsAnd ? UnsignedICmp : ZeroICmp;
1418
1419 // X >= Y || Y != 0 --> true
1420 // X >= Y || Y == 0 --> X >= Y
1421 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1422 if (EqPred == ICmpInst::ICMP_NE)
1423 return getTrue(UnsignedICmp->getType());
1424 return UnsignedICmp;
1425 }
1426
David Majnemerd5b3aa42014-12-08 18:30:43 +00001427 // X < Y && Y == 0 --> false
1428 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1429 IsAnd)
1430 return getFalse(UnsignedICmp->getType());
1431
David Majnemer1af36e52014-12-06 10:51:40 +00001432 return nullptr;
1433}
1434
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001435/// Commuted variants are assumed to be handled by calling this function again
1436/// with the parameters swapped.
1437static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1438 ICmpInst::Predicate Pred0, Pred1;
1439 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001440 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1441 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001442 return nullptr;
1443
1444 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1445 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1446 // can eliminate Op1 from this 'and'.
1447 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1448 return Op0;
1449
1450 // Check for any combination of predicates that are guaranteed to be disjoint.
1451 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1452 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1453 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1454 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1455 return getFalse(Op0->getType());
1456
1457 return nullptr;
1458}
1459
1460/// Commuted variants are assumed to be handled by calling this function again
1461/// with the parameters swapped.
Sanjay Patel142cb832017-05-04 18:19:17 +00001462static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1463 ICmpInst::Predicate Pred0, Pred1;
1464 Value *A ,*B;
1465 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1466 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1467 return nullptr;
1468
1469 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1470 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1471 // can eliminate Op0 from this 'or'.
1472 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1473 return Op1;
1474
1475 // Check for any combination of predicates that cover the entire range of
1476 // possibilities.
1477 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1478 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1479 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1480 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1481 return getTrue(Op0->getType());
1482
1483 return nullptr;
1484}
1485
Sanjay Patel599e65b2017-05-07 15:11:40 +00001486/// Test if a pair of compares with a shared operand and 2 constants has an
1487/// empty set intersection, full set union, or if one compare is a superset of
1488/// the other.
1489static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1490 bool IsAnd) {
1491 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1492 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1493 return nullptr;
1494
1495 const APInt *C0, *C1;
1496 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1497 !match(Cmp1->getOperand(1), m_APInt(C1)))
1498 return nullptr;
1499
1500 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1501 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1502
Sanjay Patel67454472017-05-08 16:35:02 +00001503 // For and-of-compares, check if the intersection is empty:
Sanjay Patel599e65b2017-05-07 15:11:40 +00001504 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1505 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1506 return getFalse(Cmp0->getType());
1507
1508 // For or-of-compares, check if the union is full:
1509 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1510 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1511 return getTrue(Cmp0->getType());
1512
1513 // Is one range a superset of the other?
1514 // If this is and-of-compares, take the smaller set:
1515 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1516 // If this is or-of-compares, take the larger set:
1517 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1518 if (Range0.contains(Range1))
1519 return IsAnd ? Cmp1 : Cmp0;
1520 if (Range1.contains(Range0))
1521 return IsAnd ? Cmp0 : Cmp1;
1522
1523 return nullptr;
1524}
1525
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001526static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1527 bool IsAnd) {
1528 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1529 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1530 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1531 return nullptr;
1532
1533 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1534 return nullptr;
1535
Sanjay Patel4158eff2018-01-13 15:44:44 +00001536 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001537 Value *X = Cmp0->getOperand(0);
1538 Value *Y = Cmp1->getOperand(0);
1539
1540 // If one of the compares is a masked version of a (not) null check, then
Sanjay Patel4158eff2018-01-13 15:44:44 +00001541 // that compare implies the other, so we eliminate the other. Optionally, look
1542 // through a pointer-to-int cast to match a null check of a pointer type.
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001543
Sanjay Patel9568f422018-01-14 15:58:18 +00001544 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1545 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1546 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1547 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001548 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1549 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001550 return Cmp1;
1551
Sanjay Patel9568f422018-01-14 15:58:18 +00001552 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1553 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1554 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1555 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001556 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1557 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001558 return Cmp0;
1559
1560 return nullptr;
1561}
1562
Florian Hahn19f9e322018-08-17 14:39:04 +00001563static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1564 const InstrInfoQuery &IIQ) {
Sanjay Patel599e65b2017-05-07 15:11:40 +00001565 // (icmp (add V, C0), C1) & (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001566 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001567 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001568 Value *V;
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001569 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001570 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001571
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001572 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001573 return nullptr;
1574
Florian Hahn19f9e322018-08-17 14:39:04 +00001575 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001576 if (AddInst->getOperand(1) != Op1->getOperand(1))
1577 return nullptr;
1578
Craig Topper9bce1ad2017-05-26 19:04:02 +00001579 Type *ITy = Op0->getType();
Florian Hahn19f9e322018-08-17 14:39:04 +00001580 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1581 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
David Majnemera315bd82014-09-15 08:15:28 +00001582
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001583 const APInt Delta = *C1 - *C0;
1584 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001585 if (Delta == 2) {
1586 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1587 return getFalse(ITy);
1588 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1589 return getFalse(ITy);
1590 }
1591 if (Delta == 1) {
1592 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1593 return getFalse(ITy);
1594 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1595 return getFalse(ITy);
1596 }
1597 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001598 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001599 if (Delta == 2)
1600 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1601 return getFalse(ITy);
1602 if (Delta == 1)
1603 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1604 return getFalse(ITy);
1605 }
1606
1607 return nullptr;
1608}
1609
Florian Hahn19f9e322018-08-17 14:39:04 +00001610static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1611 const InstrInfoQuery &IIQ) {
Craig Topper348314d2017-05-26 22:42:34 +00001612 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1613 return X;
1614 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
Sanjay Patel142cb832017-05-04 18:19:17 +00001615 return X;
1616
Craig Topper348314d2017-05-26 22:42:34 +00001617 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1618 return X;
1619 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
Sanjay Patel142cb832017-05-04 18:19:17 +00001620 return X;
1621
Craig Topper348314d2017-05-26 22:42:34 +00001622 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
Sanjay Patel599e65b2017-05-07 15:11:40 +00001623 return X;
1624
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001625 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1626 return X;
1627
Florian Hahn19f9e322018-08-17 14:39:04 +00001628 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001629 return X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001630 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001631 return X;
1632
1633 return nullptr;
1634}
1635
Florian Hahn19f9e322018-08-17 14:39:04 +00001636static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1637 const InstrInfoQuery &IIQ) {
Sanjay Patel142cb832017-05-04 18:19:17 +00001638 // (icmp (add V, C0), C1) | (icmp V, C0)
1639 ICmpInst::Predicate Pred0, Pred1;
1640 const APInt *C0, *C1;
1641 Value *V;
1642 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1643 return nullptr;
1644
1645 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1646 return nullptr;
1647
1648 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1649 if (AddInst->getOperand(1) != Op1->getOperand(1))
1650 return nullptr;
1651
1652 Type *ITy = Op0->getType();
Florian Hahn19f9e322018-08-17 14:39:04 +00001653 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1654 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
Sanjay Patel142cb832017-05-04 18:19:17 +00001655
1656 const APInt Delta = *C1 - *C0;
1657 if (C0->isStrictlyPositive()) {
1658 if (Delta == 2) {
1659 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1660 return getTrue(ITy);
1661 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1662 return getTrue(ITy);
1663 }
1664 if (Delta == 1) {
1665 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1666 return getTrue(ITy);
1667 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1668 return getTrue(ITy);
1669 }
1670 }
1671 if (C0->getBoolValue() && isNUW) {
1672 if (Delta == 2)
1673 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1674 return getTrue(ITy);
1675 if (Delta == 1)
1676 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1677 return getTrue(ITy);
1678 }
1679
1680 return nullptr;
1681}
1682
Florian Hahn19f9e322018-08-17 14:39:04 +00001683static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1684 const InstrInfoQuery &IIQ) {
Craig Topper348314d2017-05-26 22:42:34 +00001685 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1686 return X;
1687 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1688 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001689
Craig Topper348314d2017-05-26 22:42:34 +00001690 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1691 return X;
1692 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1693 return X;
1694
1695 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1696 return X;
1697
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001698 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1699 return X;
1700
Florian Hahn19f9e322018-08-17 14:39:04 +00001701 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001702 return X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001703 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001704 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001705
1706 return nullptr;
1707}
1708
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001709static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1710 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
Sanjay Pateleb731b02017-11-19 15:34:27 +00001711 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1712 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1713 if (LHS0->getType() != RHS0->getType())
1714 return nullptr;
1715
1716 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1717 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1718 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1719 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1720 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1721 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1722 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1723 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1724 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1725 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1726 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001727 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1728 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
Sanjay Pateleb731b02017-11-19 15:34:27 +00001729 return RHS;
1730
1731 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1732 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1733 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1734 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1735 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1736 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1737 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1738 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001739 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1740 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
Sanjay Pateleb731b02017-11-19 15:34:27 +00001741 return LHS;
1742 }
1743
1744 return nullptr;
1745}
1746
Florian Hahn19f9e322018-08-17 14:39:04 +00001747static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001748 Value *Op0, Value *Op1, bool IsAnd) {
Sanjay Patele42b4d52017-05-04 19:51:34 +00001749 // Look through casts of the 'and' operands to find compares.
1750 auto *Cast0 = dyn_cast<CastInst>(Op0);
1751 auto *Cast1 = dyn_cast<CastInst>(Op1);
1752 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1753 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1754 Op0 = Cast0->getOperand(0);
1755 Op1 = Cast1->getOperand(0);
1756 }
1757
Sanjay Pateleb731b02017-11-19 15:34:27 +00001758 Value *V = nullptr;
1759 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1760 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1761 if (ICmp0 && ICmp1)
Florian Hahn19f9e322018-08-17 14:39:04 +00001762 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q.IIQ)
1763 : simplifyOrOfICmps(ICmp0, ICmp1, Q.IIQ);
Sanjay Patele42b4d52017-05-04 19:51:34 +00001764
Sanjay Pateleb731b02017-11-19 15:34:27 +00001765 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1766 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1767 if (FCmp0 && FCmp1)
Florian Hahn19f9e322018-08-17 14:39:04 +00001768 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
Sanjay Pateleb731b02017-11-19 15:34:27 +00001769
Craig Topper348314d2017-05-26 22:42:34 +00001770 if (!V)
1771 return nullptr;
1772 if (!Cast0)
Sanjay Patele42b4d52017-05-04 19:51:34 +00001773 return V;
Craig Topper348314d2017-05-26 22:42:34 +00001774
1775 // If we looked through casts, we can only handle a constant simplification
1776 // because we are not allowed to create a cast instruction here.
1777 if (auto *C = dyn_cast<Constant>(V))
1778 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
Sanjay Patele42b4d52017-05-04 19:51:34 +00001779
1780 return nullptr;
1781}
1782
Sanjay Patel472cc782016-01-11 22:14:42 +00001783/// Given operands for an And, see if we can fold the result.
1784/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001785static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001786 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001787 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1788 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001789
Chris Lattnera71e9d62009-11-10 00:55:12 +00001790 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001791 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001792 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001793
Chris Lattnera71e9d62009-11-10 00:55:12 +00001794 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001795 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001796 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001797
Duncan Sandsc89ac072010-11-17 18:52:15 +00001798 // X & 0 = 0
1799 if (match(Op1, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001800 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001801
Duncan Sandsc89ac072010-11-17 18:52:15 +00001802 // X & -1 = X
1803 if (match(Op1, m_AllOnes()))
1804 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001805
Chris Lattnera71e9d62009-11-10 00:55:12 +00001806 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001807 if (match(Op0, m_Not(m_Specific(Op1))) ||
1808 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001809 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001810
Chris Lattnera71e9d62009-11-10 00:55:12 +00001811 // (A | ?) & A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001812 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001813 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001814
Chris Lattnera71e9d62009-11-10 00:55:12 +00001815 // A & (A | ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001816 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001817 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001818
Sanjay Patel877364f2017-05-16 21:51:04 +00001819 // A mask that only clears known zeros of a shifted value is a no-op.
1820 Value *X;
1821 const APInt *Mask;
1822 const APInt *ShAmt;
1823 if (match(Op1, m_APInt(Mask))) {
1824 // If all bits in the inverted and shifted mask are clear:
1825 // and (shl X, ShAmt), Mask --> shl X, ShAmt
1826 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1827 (~(*Mask)).lshr(*ShAmt).isNullValue())
1828 return Op0;
1829
1830 // If all bits in the inverted and shifted mask are clear:
1831 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1832 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1833 (~(*Mask)).shl(*ShAmt).isNullValue())
1834 return Op0;
1835 }
1836
Duncan Sandsba286d72011-10-26 20:55:21 +00001837 // A & (-A) = A if A is a power of two or zero.
1838 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1839 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001840 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1841 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001842 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001843 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1844 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001845 return Op1;
1846 }
1847
Florian Hahn19f9e322018-08-17 14:39:04 +00001848 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001849 return V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001850
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001851 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001852 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1853 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001854 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001855
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001856 // And distributes over Or. Try some generic simplifications based on this.
1857 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001858 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001859 return V;
1860
1861 // And distributes over Xor. Try some generic simplifications based on this.
1862 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001863 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001864 return V;
1865
Duncan Sandsb0579e92010-11-10 13:00:08 +00001866 // If the operation is with the result of a select instruction, check whether
1867 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001868 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001869 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1870 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001871 return V;
1872
1873 // If the operation is with the result of a phi instruction, check whether
1874 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001875 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001876 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001877 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001878 return V;
1879
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001880 // Assuming the effective width of Y is not larger than A, i.e. all bits
1881 // from X and Y are disjoint in (X << A) | Y,
1882 // if the mask of this AND op covers all bits of X or Y, while it covers
1883 // no bits from the other, we can bypass this AND op. E.g.,
1884 // ((X << A) | Y) & Mask -> Y,
1885 // if Mask = ((1 << effective_width_of(Y)) - 1)
1886 // ((X << A) | Y) & Mask -> X << A,
1887 // if Mask = ((1 << effective_width_of(X)) - 1) << A
1888 // SimplifyDemandedBits in InstCombine can optimize the general case.
1889 // This pattern aims to help other passes for a common case.
1890 Value *Y, *XShifted;
1891 if (match(Op1, m_APInt(Mask)) &&
1892 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
1893 m_Value(XShifted)),
1894 m_Value(Y)))) {
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001895 const unsigned Width = Op0->getType()->getScalarSizeInBits();
Benjamin Kramerbae6aab2018-08-12 11:43:03 +00001896 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
1897 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001898 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1899 if (EffWidthY <= ShftCnt) {
1900 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
1901 Q.DT);
1902 const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
1903 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
1904 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
1905 // If the mask is extracting all bits from X or Y as is, we can skip
1906 // this AND op.
1907 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
1908 return Y;
1909 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
1910 return XShifted;
1911 }
1912 }
1913
Craig Topper9f008862014-04-15 04:59:12 +00001914 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001915}
1916
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001917Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1918 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1919}
1920
Sanjay Patel472cc782016-01-11 22:14:42 +00001921/// Given operands for an Or, see if we can fold the result.
1922/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001923static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001924 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001925 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1926 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001927
Chris Lattnera71e9d62009-11-10 00:55:12 +00001928 // X | undef -> -1
Sanjay Pateladf6e882018-02-18 18:05:08 +00001929 // X | -1 = -1
1930 // Do not return Op1 because it may contain undef elements if it's a vector.
1931 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001932 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001933
Chris Lattnera71e9d62009-11-10 00:55:12 +00001934 // X | X = X
Duncan Sandsc89ac072010-11-17 18:52:15 +00001935 // X | 0 = X
Sanjay Pateladf6e882018-02-18 18:05:08 +00001936 if (Op0 == Op1 || match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001937 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001938
Chris Lattnera71e9d62009-11-10 00:55:12 +00001939 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001940 if (match(Op0, m_Not(m_Specific(Op1))) ||
1941 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001942 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001943
Chris Lattnera71e9d62009-11-10 00:55:12 +00001944 // (A & ?) | A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001945 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001946 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001947
Chris Lattnera71e9d62009-11-10 00:55:12 +00001948 // A | (A & ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001949 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001950 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001951
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001952 // ~(A & ?) | A = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001953 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001954 return Constant::getAllOnesValue(Op1->getType());
1955
1956 // A | ~(A & ?) = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001957 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001958 return Constant::getAllOnesValue(Op0->getType());
1959
Craig Topperdad7d8d2017-07-16 06:57:41 +00001960 Value *A, *B;
Sanjay Patel08892252017-04-24 18:24:36 +00001961 // (A & ~B) | (A ^ B) -> (A ^ B)
1962 // (~B & A) | (A ^ B) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001963 // (A & ~B) | (B ^ A) -> (B ^ A)
1964 // (~B & A) | (B ^ A) -> (B ^ A)
1965 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1966 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1967 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001968 return Op1;
1969
1970 // Commute the 'or' operands.
1971 // (A ^ B) | (A & ~B) -> (A ^ B)
1972 // (A ^ B) | (~B & A) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001973 // (B ^ A) | (A & ~B) -> (B ^ A)
1974 // (B ^ A) | (~B & A) -> (B ^ A)
1975 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1976 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1977 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001978 return Op0;
1979
Craig Topper479daaf2017-05-14 07:54:43 +00001980 // (A & B) | (~A ^ B) -> (~A ^ B)
1981 // (B & A) | (~A ^ B) -> (~A ^ B)
1982 // (A & B) | (B ^ ~A) -> (B ^ ~A)
1983 // (B & A) | (B ^ ~A) -> (B ^ ~A)
1984 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1985 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1986 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1987 return Op1;
1988
1989 // (~A ^ B) | (A & B) -> (~A ^ B)
1990 // (~A ^ B) | (B & A) -> (~A ^ B)
1991 // (B ^ ~A) | (A & B) -> (B ^ ~A)
1992 // (B ^ ~A) | (B & A) -> (B ^ ~A)
1993 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1994 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1995 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1996 return Op0;
1997
Florian Hahn19f9e322018-08-17 14:39:04 +00001998 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001999 return V;
David Majnemera315bd82014-09-15 08:15:28 +00002000
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002001 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002002 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2003 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002004 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00002005
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00002006 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002007 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
2008 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00002009 return V;
2010
Duncan Sandsb0579e92010-11-10 13:00:08 +00002011 // If the operation is with the result of a select instruction, check whether
2012 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002013 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002014 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00002015 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002016 return V;
2017
Craig Topper50500d52017-05-26 05:16:20 +00002018 // (A & C1)|(B & C2)
Craig Topper1da22c32017-05-26 19:03:53 +00002019 const APInt *C1, *C2;
2020 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2021 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2022 if (*C1 == ~*C2) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002023 // (A & C1)|(B & C2)
2024 // If we have: ((V + N) & C1) | (V & C2)
2025 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2026 // replace with V+N.
Craig Topperc8bebb12017-05-26 19:03:59 +00002027 Value *N;
Craig Topper1da22c32017-05-26 19:03:53 +00002028 if (C2->isMask() && // C2 == 0+1+
Craig Topperc8bebb12017-05-26 19:03:59 +00002029 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002030 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00002031 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00002032 return A;
2033 }
2034 // Or commutes, try both ways.
Craig Topper1da22c32017-05-26 19:03:53 +00002035 if (C1->isMask() &&
Craig Topperc8bebb12017-05-26 19:03:59 +00002036 match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002037 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00002038 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00002039 return B;
2040 }
2041 }
2042 }
2043
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002044 // If the operation is with the result of a phi instruction, check whether
2045 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002046 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002047 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00002048 return V;
2049
Craig Topper9f008862014-04-15 04:59:12 +00002050 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00002051}
2052
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002053Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2054 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2055}
2056
Sanjay Patel472cc782016-01-11 22:14:42 +00002057/// Given operands for a Xor, see if we can fold the result.
2058/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002059static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002060 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00002061 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2062 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002063
2064 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00002065 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00002066 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002067
2068 // A ^ 0 = A
2069 if (match(Op1, m_Zero()))
2070 return Op0;
2071
Eli Friedmanad3cfe72011-08-17 19:31:49 +00002072 // A ^ A = 0
2073 if (Op0 == Op1)
2074 return Constant::getNullValue(Op0->getType());
2075
Duncan Sandsc89ac072010-11-17 18:52:15 +00002076 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00002077 if (match(Op0, m_Not(m_Specific(Op1))) ||
2078 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002079 return Constant::getAllOnesValue(Op0->getType());
2080
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002081 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002082 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2083 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002084 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002085
Duncan Sandsb238de02010-11-19 09:20:39 +00002086 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2087 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2088 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2089 // only if B and C are equal. If B and C are equal then (since we assume
2090 // that operands have already been simplified) "select(cond, B, C)" should
2091 // have been simplified to the common value of B and C already. Analysing
2092 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2093 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002094
Craig Topper9f008862014-04-15 04:59:12 +00002095 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002096}
2097
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002098Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2099 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2100}
2101
2102
Chris Lattner229907c2011-07-18 04:54:35 +00002103static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002104 return CmpInst::makeCmpResultType(Op->getType());
2105}
2106
Sanjay Patel472cc782016-01-11 22:14:42 +00002107/// Rummage around inside V looking for something equivalent to the comparison
2108/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2109/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002110static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2111 Value *LHS, Value *RHS) {
2112 SelectInst *SI = dyn_cast<SelectInst>(V);
2113 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002114 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002115 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2116 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002117 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002118 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2119 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2120 return Cmp;
2121 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2122 LHS == CmpRHS && RHS == CmpLHS)
2123 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002124 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002125}
2126
Dan Gohman9631d902013-02-01 00:49:06 +00002127// A significant optimization not implemented here is assuming that alloca
2128// addresses are not equal to incoming argument values. They don't *alias*,
2129// as we say, but that doesn't mean they aren't equal, so we take a
2130// conservative approach.
2131//
2132// This is inspired in part by C++11 5.10p1:
2133// "Two pointers of the same type compare equal if and only if they are both
2134// null, both point to the same function, or both represent the same
2135// address."
2136//
2137// This is pretty permissive.
2138//
2139// It's also partly due to C11 6.5.9p6:
2140// "Two pointers compare equal if and only if both are null pointers, both are
2141// pointers to the same object (including a pointer to an object and a
2142// subobject at its beginning) or function, both are pointers to one past the
2143// last element of the same array object, or one is a pointer to one past the
2144// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002145// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002146// object in the address space.)
2147//
2148// C11's version is more restrictive, however there's no reason why an argument
2149// couldn't be a one-past-the-end value for a stack object in the caller and be
2150// equal to the beginning of a stack object in the callee.
2151//
2152// If the C and C++ standards are ever made sufficiently restrictive in this
2153// area, it may be possible to update LLVM's semantics accordingly and reinstate
2154// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002155static Constant *
2156computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2157 const DominatorTree *DT, CmpInst::Predicate Pred,
Nuno Lopes404f1062017-09-09 18:23:11 +00002158 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +00002159 const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002160 // First, skip past any trivial no-ops.
2161 LHS = LHS->stripPointerCasts();
2162 RHS = RHS->stripPointerCasts();
2163
2164 // A non-null pointer is not equal to a null pointer.
Florian Hahn19f9e322018-08-17 14:39:04 +00002165 if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2166 IIQ.UseInstrInfo) &&
2167 isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002168 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2169 return ConstantInt::get(GetCompareTy(LHS),
2170 !CmpInst::isTrueWhenEqual(Pred));
2171
Chandler Carruth8059c842012-03-25 21:28:14 +00002172 // We can only fold certain predicates on pointer comparisons.
2173 switch (Pred) {
2174 default:
Craig Topper9f008862014-04-15 04:59:12 +00002175 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002176
2177 // Equality comaprisons are easy to fold.
2178 case CmpInst::ICMP_EQ:
2179 case CmpInst::ICMP_NE:
2180 break;
2181
2182 // We can only handle unsigned relational comparisons because 'inbounds' on
2183 // a GEP only protects against unsigned wrapping.
2184 case CmpInst::ICMP_UGT:
2185 case CmpInst::ICMP_UGE:
2186 case CmpInst::ICMP_ULT:
2187 case CmpInst::ICMP_ULE:
2188 // However, we have to switch them to their signed variants to handle
2189 // negative indices from the base pointer.
2190 Pred = ICmpInst::getSignedPredicate(Pred);
2191 break;
2192 }
2193
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002194 // Strip off any constant offsets so that we can reason about them.
2195 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2196 // here and compare base addresses like AliasAnalysis does, however there are
2197 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2198 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2199 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002200 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2201 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002202
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002203 // If LHS and RHS are related via constant offsets to the same base
2204 // value, we can replace it with an icmp which just compares the offsets.
2205 if (LHS == RHS)
2206 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002207
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002208 // Various optimizations for (in)equality comparisons.
2209 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2210 // Different non-empty allocations that exist at the same time have
2211 // different addresses (if the program can tell). Global variables always
2212 // exist, so they always exist during the lifetime of each other and all
2213 // allocas. Two different allocas usually have different addresses...
2214 //
2215 // However, if there's an @llvm.stackrestore dynamically in between two
2216 // allocas, they may have the same address. It's tempting to reduce the
2217 // scope of the problem by only looking at *static* allocas here. That would
2218 // cover the majority of allocas while significantly reducing the likelihood
2219 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2220 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2221 // an entry block. Also, if we have a block that's not attached to a
2222 // function, we can't tell if it's "static" under the current definition.
2223 // Theoretically, this problem could be fixed by creating a new kind of
2224 // instruction kind specifically for static allocas. Such a new instruction
2225 // could be required to be at the top of the entry block, thus preventing it
2226 // from being subject to a @llvm.stackrestore. Instcombine could even
2227 // convert regular allocas into these special allocas. It'd be nifty.
2228 // However, until then, this problem remains open.
2229 //
2230 // So, we'll assume that two non-empty allocas have different addresses
2231 // for now.
2232 //
2233 // With all that, if the offsets are within the bounds of their allocations
2234 // (and not one-past-the-end! so we can't use inbounds!), and their
2235 // allocations aren't the same, the pointers are not equal.
2236 //
2237 // Note that it's not necessary to check for LHS being a global variable
2238 // address, due to canonicalization and constant folding.
2239 if (isa<AllocaInst>(LHS) &&
2240 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002241 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2242 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002243 uint64_t LHSSize, RHSSize;
Manoj Gupta77eeac32018-07-09 22:27:23 +00002244 ObjectSizeOpts Opts;
2245 Opts.NullIsUnknownSize =
2246 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002247 if (LHSOffsetCI && RHSOffsetCI &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002248 getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2249 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002250 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2251 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002252 if (!LHSOffsetValue.isNegative() &&
2253 !RHSOffsetValue.isNegative() &&
2254 LHSOffsetValue.ult(LHSSize) &&
2255 RHSOffsetValue.ult(RHSSize)) {
2256 return ConstantInt::get(GetCompareTy(LHS),
2257 !CmpInst::isTrueWhenEqual(Pred));
2258 }
2259 }
2260
2261 // Repeat the above check but this time without depending on DataLayout
2262 // or being able to compute a precise size.
2263 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2264 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2265 LHSOffset->isNullValue() &&
2266 RHSOffset->isNullValue())
2267 return ConstantInt::get(GetCompareTy(LHS),
2268 !CmpInst::isTrueWhenEqual(Pred));
2269 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002270
2271 // Even if an non-inbounds GEP occurs along the path we can still optimize
2272 // equality comparisons concerning the result. We avoid walking the whole
2273 // chain again by starting where the last calls to
2274 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002275 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2276 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002277 if (LHS == RHS)
2278 return ConstantExpr::getICmp(Pred,
2279 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2280 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002281
2282 // If one side of the equality comparison must come from a noalias call
2283 // (meaning a system memory allocation function), and the other side must
2284 // come from a pointer that cannot overlap with dynamically-allocated
2285 // memory within the lifetime of the current function (allocas, byval
2286 // arguments, globals), then determine the comparison result here.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00002287 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
Hal Finkelafcd8db2014-12-01 23:38:06 +00002288 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2289 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2290
2291 // Is the set of underlying objects all noalias calls?
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00002292 auto IsNAC = [](ArrayRef<const Value *> Objects) {
David Majnemer0a16c222016-08-11 21:15:00 +00002293 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002294 };
2295
2296 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002297 // noalias calls. For allocas, we consider only static ones (dynamic
2298 // allocas might be transformed into calls to malloc not simultaneously
2299 // live with the compared-to allocation). For globals, we exclude symbols
2300 // that might be resolve lazily to symbols in another dynamically-loaded
2301 // library (and, thus, could be malloc'ed by the implementation).
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00002302 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2303 return all_of(Objects, [](const Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002304 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2305 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2306 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2307 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002308 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002309 !GV->isThreadLocal();
2310 if (const Argument *A = dyn_cast<Argument>(V))
2311 return A->hasByValAttr();
2312 return false;
2313 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002314 };
2315
2316 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2317 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2318 return ConstantInt::get(GetCompareTy(LHS),
2319 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002320
2321 // Fold comparisons for non-escaping pointer even if the allocation call
2322 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2323 // dynamic allocation call could be either of the operands.
2324 Value *MI = nullptr;
Nuno Lopes404f1062017-09-09 18:23:11 +00002325 if (isAllocLikeFn(LHS, TLI) &&
2326 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002327 MI = LHS;
Nuno Lopes404f1062017-09-09 18:23:11 +00002328 else if (isAllocLikeFn(RHS, TLI) &&
2329 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002330 MI = RHS;
2331 // FIXME: We should also fold the compare when the pointer escapes, but the
2332 // compare dominates the pointer escape
2333 if (MI && !PointerMayBeCaptured(MI, true, true))
2334 return ConstantInt::get(GetCompareTy(LHS),
2335 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002336 }
2337
2338 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002339 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002340}
Chris Lattner01990f02012-02-24 19:01:58 +00002341
Sanjay Pateldc65a272016-12-03 17:30:22 +00002342/// Fold an icmp when its operands have i1 scalar type.
2343static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002344 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002345 Type *ITy = GetCompareTy(LHS); // The return type.
2346 Type *OpTy = LHS->getType(); // The operand type.
Craig Topperfde47232017-07-09 07:04:03 +00002347 if (!OpTy->isIntOrIntVectorTy(1))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002348 return nullptr;
2349
Sanjay Patele2787b92017-05-17 20:27:55 +00002350 // A boolean compared to true/false can be simplified in 14 out of the 20
2351 // (10 predicates * 2 constants) possible combinations. Cases not handled here
2352 // require a 'not' of the LHS, so those must be transformed in InstCombine.
2353 if (match(RHS, m_Zero())) {
2354 switch (Pred) {
2355 case CmpInst::ICMP_NE: // X != 0 -> X
2356 case CmpInst::ICMP_UGT: // X >u 0 -> X
2357 case CmpInst::ICMP_SLT: // X <s 0 -> X
2358 return LHS;
2359
2360 case CmpInst::ICMP_ULT: // X <u 0 -> false
2361 case CmpInst::ICMP_SGT: // X >s 0 -> false
2362 return getFalse(ITy);
2363
2364 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2365 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2366 return getTrue(ITy);
2367
2368 default: break;
2369 }
2370 } else if (match(RHS, m_One())) {
2371 switch (Pred) {
2372 case CmpInst::ICMP_EQ: // X == 1 -> X
2373 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2374 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2375 return LHS;
2376
2377 case CmpInst::ICMP_UGT: // X >u 1 -> false
2378 case CmpInst::ICMP_SLT: // X <s -1 -> false
2379 return getFalse(ITy);
2380
2381 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2382 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2383 return getTrue(ITy);
2384
2385 default: break;
2386 }
2387 }
2388
Sanjay Pateldc65a272016-12-03 17:30:22 +00002389 switch (Pred) {
2390 default:
2391 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002392 case ICmpInst::ICMP_UGE:
Sanjay Pateldc65a272016-12-03 17:30:22 +00002393 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2394 return getTrue(ITy);
2395 break;
2396 case ICmpInst::ICMP_SGE:
2397 /// For signed comparison, the values for an i1 are 0 and -1
2398 /// respectively. This maps into a truth table of:
2399 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2400 /// 0 | 0 | 1 (0 >= 0) | 1
2401 /// 0 | 1 | 1 (0 >= -1) | 1
2402 /// 1 | 0 | 0 (-1 >= 0) | 0
2403 /// 1 | 1 | 1 (-1 >= -1) | 1
2404 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2405 return getTrue(ITy);
2406 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002407 case ICmpInst::ICMP_ULE:
2408 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2409 return getTrue(ITy);
2410 break;
2411 }
2412
2413 return nullptr;
2414}
2415
2416/// Try hard to fold icmp with zero RHS because this is a common case.
2417static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002418 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002419 if (!match(RHS, m_Zero()))
2420 return nullptr;
2421
2422 Type *ITy = GetCompareTy(LHS); // The return type.
Sanjay Pateldc65a272016-12-03 17:30:22 +00002423 switch (Pred) {
2424 default:
2425 llvm_unreachable("Unknown ICmp predicate!");
2426 case ICmpInst::ICMP_ULT:
2427 return getFalse(ITy);
2428 case ICmpInst::ICMP_UGE:
2429 return getTrue(ITy);
2430 case ICmpInst::ICMP_EQ:
2431 case ICmpInst::ICMP_ULE:
Florian Hahn19f9e322018-08-17 14:39:04 +00002432 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002433 return getFalse(ITy);
2434 break;
2435 case ICmpInst::ICMP_NE:
2436 case ICmpInst::ICMP_UGT:
Florian Hahn19f9e322018-08-17 14:39:04 +00002437 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002438 return getTrue(ITy);
2439 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002440 case ICmpInst::ICMP_SLT: {
2441 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2442 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002443 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002444 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002445 return getFalse(ITy);
2446 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002447 }
2448 case ICmpInst::ICMP_SLE: {
2449 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2450 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002451 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002452 if (LHSKnown.isNonNegative() &&
2453 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002454 return getFalse(ITy);
2455 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002456 }
2457 case ICmpInst::ICMP_SGE: {
2458 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2459 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002460 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002461 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002462 return getTrue(ITy);
2463 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002464 }
2465 case ICmpInst::ICMP_SGT: {
2466 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2467 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002468 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002469 if (LHSKnown.isNonNegative() &&
2470 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002471 return getTrue(ITy);
2472 break;
2473 }
Craig Topper1a36b7d2017-05-15 06:39:41 +00002474 }
Sanjay Pateldc65a272016-12-03 17:30:22 +00002475
2476 return nullptr;
2477}
2478
Sanjay Patel67bde282016-08-22 23:12:02 +00002479static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
Florian Hahn19f9e322018-08-17 14:39:04 +00002480 Value *RHS, const InstrInfoQuery &IIQ) {
Roman Lebedev0c43d722018-03-15 16:17:40 +00002481 Type *ITy = GetCompareTy(RHS); // The return type.
2482
Roman Lebedev6aca3352018-03-15 16:17:46 +00002483 Value *X;
2484 // Sign-bit checks can be optimized to true/false after unsigned
2485 // floating-point casts:
2486 // icmp slt (bitcast (uitofp X)), 0 --> false
2487 // icmp sgt (bitcast (uitofp X)), -1 --> true
2488 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2489 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2490 return ConstantInt::getFalse(ITy);
2491 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2492 return ConstantInt::getTrue(ITy);
2493 }
2494
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002495 const APInt *C;
2496 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002497 return nullptr;
2498
2499 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002500 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002501 if (RHS_CR.isEmptySet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002502 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002503 if (RHS_CR.isFullSet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002504 return ConstantInt::getTrue(ITy);
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002505
Nikita Popov49097592019-03-09 21:17:42 +00002506 ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo);
Sanjay Patel67bde282016-08-22 23:12:02 +00002507 if (!LHS_CR.isFullSet()) {
2508 if (RHS_CR.contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002509 return ConstantInt::getTrue(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002510 if (RHS_CR.inverse().contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002511 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002512 }
2513
2514 return nullptr;
2515}
2516
Sanjay Patel2df38a82017-05-08 16:21:55 +00002517/// TODO: A large part of this logic is duplicated in InstCombine's
2518/// foldICmpBinOp(). We should be able to share that and avoid the code
2519/// duplication.
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002520static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002521 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002522 unsigned MaxRecurse) {
2523 Type *ITy = GetCompareTy(LHS); // The return type.
2524
2525 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2526 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2527 if (MaxRecurse && (LBO || RBO)) {
2528 // Analyze the case when either LHS or RHS is an add instruction.
2529 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2530 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2531 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2532 if (LBO && LBO->getOpcode() == Instruction::Add) {
2533 A = LBO->getOperand(0);
2534 B = LBO->getOperand(1);
2535 NoLHSWrapProblem =
2536 ICmpInst::isEquality(Pred) ||
Florian Hahn19f9e322018-08-17 14:39:04 +00002537 (CmpInst::isUnsigned(Pred) &&
2538 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2539 (CmpInst::isSigned(Pred) &&
2540 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002541 }
2542 if (RBO && RBO->getOpcode() == Instruction::Add) {
2543 C = RBO->getOperand(0);
2544 D = RBO->getOperand(1);
2545 NoRHSWrapProblem =
2546 ICmpInst::isEquality(Pred) ||
Florian Hahn19f9e322018-08-17 14:39:04 +00002547 (CmpInst::isUnsigned(Pred) &&
2548 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2549 (CmpInst::isSigned(Pred) &&
2550 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002551 }
2552
2553 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2554 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2555 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2556 Constant::getNullValue(RHS->getType()), Q,
2557 MaxRecurse - 1))
2558 return V;
2559
2560 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2561 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2562 if (Value *V =
2563 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2564 C == LHS ? D : C, Q, MaxRecurse - 1))
2565 return V;
2566
2567 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2568 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2569 NoRHSWrapProblem) {
2570 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2571 Value *Y, *Z;
2572 if (A == C) {
2573 // C + B == C + D -> B == D
2574 Y = B;
2575 Z = D;
2576 } else if (A == D) {
2577 // D + B == C + D -> B == C
2578 Y = B;
2579 Z = C;
2580 } else if (B == C) {
2581 // A + C == C + D -> A == D
2582 Y = A;
2583 Z = D;
2584 } else {
2585 assert(B == D);
2586 // A + D == C + D -> A == C
2587 Y = A;
2588 Z = C;
2589 }
2590 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2591 return V;
2592 }
2593 }
2594
2595 {
2596 Value *Y = nullptr;
2597 // icmp pred (or X, Y), X
2598 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2599 if (Pred == ICmpInst::ICMP_ULT)
2600 return getFalse(ITy);
2601 if (Pred == ICmpInst::ICMP_UGE)
2602 return getTrue(ITy);
2603
2604 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002605 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2606 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2607 if (RHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002608 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002609 if (RHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002610 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2611 }
2612 }
2613 // icmp pred X, (or X, Y)
2614 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2615 if (Pred == ICmpInst::ICMP_ULE)
2616 return getTrue(ITy);
2617 if (Pred == ICmpInst::ICMP_UGT)
2618 return getFalse(ITy);
2619
2620 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002621 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2622 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2623 if (LHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002624 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002625 if (LHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002626 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2627 }
2628 }
2629 }
2630
2631 // icmp pred (and X, Y), X
Craig Topper72ee6942017-06-24 06:24:01 +00002632 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002633 if (Pred == ICmpInst::ICMP_UGT)
2634 return getFalse(ITy);
2635 if (Pred == ICmpInst::ICMP_ULE)
2636 return getTrue(ITy);
2637 }
2638 // icmp pred X, (and X, Y)
Craig Topper72ee6942017-06-24 06:24:01 +00002639 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002640 if (Pred == ICmpInst::ICMP_UGE)
2641 return getTrue(ITy);
2642 if (Pred == ICmpInst::ICMP_ULT)
2643 return getFalse(ITy);
2644 }
2645
2646 // 0 - (zext X) pred C
2647 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2648 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2649 if (RHSC->getValue().isStrictlyPositive()) {
2650 if (Pred == ICmpInst::ICMP_SLT)
2651 return ConstantInt::getTrue(RHSC->getContext());
2652 if (Pred == ICmpInst::ICMP_SGE)
2653 return ConstantInt::getFalse(RHSC->getContext());
2654 if (Pred == ICmpInst::ICMP_EQ)
2655 return ConstantInt::getFalse(RHSC->getContext());
2656 if (Pred == ICmpInst::ICMP_NE)
2657 return ConstantInt::getTrue(RHSC->getContext());
2658 }
2659 if (RHSC->getValue().isNonNegative()) {
2660 if (Pred == ICmpInst::ICMP_SLE)
2661 return ConstantInt::getTrue(RHSC->getContext());
2662 if (Pred == ICmpInst::ICMP_SGT)
2663 return ConstantInt::getFalse(RHSC->getContext());
2664 }
2665 }
2666 }
2667
2668 // icmp pred (urem X, Y), Y
2669 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002670 switch (Pred) {
2671 default:
2672 break;
2673 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002674 case ICmpInst::ICMP_SGE: {
2675 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2676 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002677 break;
2678 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002679 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002680 case ICmpInst::ICMP_EQ:
2681 case ICmpInst::ICMP_UGT:
2682 case ICmpInst::ICMP_UGE:
2683 return getFalse(ITy);
2684 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002685 case ICmpInst::ICMP_SLE: {
2686 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2687 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002688 break;
2689 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002690 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002691 case ICmpInst::ICMP_NE:
2692 case ICmpInst::ICMP_ULT:
2693 case ICmpInst::ICMP_ULE:
2694 return getTrue(ITy);
2695 }
2696 }
2697
2698 // icmp pred X, (urem Y, X)
2699 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002700 switch (Pred) {
2701 default:
2702 break;
2703 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002704 case ICmpInst::ICMP_SGE: {
2705 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2706 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002707 break;
2708 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002709 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002710 case ICmpInst::ICMP_NE:
2711 case ICmpInst::ICMP_UGT:
2712 case ICmpInst::ICMP_UGE:
2713 return getTrue(ITy);
2714 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002715 case ICmpInst::ICMP_SLE: {
2716 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2717 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002718 break;
2719 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002720 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002721 case ICmpInst::ICMP_EQ:
2722 case ICmpInst::ICMP_ULT:
2723 case ICmpInst::ICMP_ULE:
2724 return getFalse(ITy);
2725 }
2726 }
2727
2728 // x >> y <=u x
2729 // x udiv y <=u x.
2730 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2731 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2732 // icmp pred (X op Y), X
2733 if (Pred == ICmpInst::ICMP_UGT)
2734 return getFalse(ITy);
2735 if (Pred == ICmpInst::ICMP_ULE)
2736 return getTrue(ITy);
2737 }
2738
2739 // x >=u x >> y
2740 // x >=u x udiv y.
2741 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2742 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2743 // icmp pred X, (X op Y)
2744 if (Pred == ICmpInst::ICMP_ULT)
2745 return getFalse(ITy);
2746 if (Pred == ICmpInst::ICMP_UGE)
2747 return getTrue(ITy);
2748 }
2749
2750 // handle:
2751 // CI2 << X == CI
2752 // CI2 << X != CI
2753 //
2754 // where CI2 is a power of 2 and CI isn't
2755 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2756 const APInt *CI2Val, *CIVal = &CI->getValue();
2757 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2758 CI2Val->isPowerOf2()) {
2759 if (!CIVal->isPowerOf2()) {
2760 // CI2 << X can equal zero in some circumstances,
2761 // this simplification is unsafe if CI is zero.
2762 //
2763 // We know it is safe if:
2764 // - The shift is nsw, we can't shift out the one bit.
2765 // - The shift is nuw, we can't shift out the one bit.
2766 // - CI2 is one
2767 // - CI isn't zero
Florian Hahn19f9e322018-08-17 14:39:04 +00002768 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2769 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
Craig Topper73ba1c82017-06-07 07:40:37 +00002770 CI2Val->isOneValue() || !CI->isZero()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002771 if (Pred == ICmpInst::ICMP_EQ)
2772 return ConstantInt::getFalse(RHS->getContext());
2773 if (Pred == ICmpInst::ICMP_NE)
2774 return ConstantInt::getTrue(RHS->getContext());
2775 }
2776 }
Craig Topper73ba1c82017-06-07 07:40:37 +00002777 if (CIVal->isSignMask() && CI2Val->isOneValue()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002778 if (Pred == ICmpInst::ICMP_UGT)
2779 return ConstantInt::getFalse(RHS->getContext());
2780 if (Pred == ICmpInst::ICMP_ULE)
2781 return ConstantInt::getTrue(RHS->getContext());
2782 }
2783 }
2784 }
2785
2786 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2787 LBO->getOperand(1) == RBO->getOperand(1)) {
2788 switch (LBO->getOpcode()) {
2789 default:
2790 break;
2791 case Instruction::UDiv:
2792 case Instruction::LShr:
Florian Hahn19f9e322018-08-17 14:39:04 +00002793 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
2794 !Q.IIQ.isExact(RBO))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002795 break;
Sanjay Patela23b1412017-05-15 19:16:49 +00002796 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2797 RBO->getOperand(0), Q, MaxRecurse - 1))
2798 return V;
2799 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002800 case Instruction::SDiv:
Florian Hahn19f9e322018-08-17 14:39:04 +00002801 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
2802 !Q.IIQ.isExact(RBO))
Sanjay Patela23b1412017-05-15 19:16:49 +00002803 break;
2804 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2805 RBO->getOperand(0), Q, MaxRecurse - 1))
2806 return V;
2807 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002808 case Instruction::AShr:
Florian Hahn19f9e322018-08-17 14:39:04 +00002809 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002810 break;
2811 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2812 RBO->getOperand(0), Q, MaxRecurse - 1))
2813 return V;
2814 break;
2815 case Instruction::Shl: {
Florian Hahn19f9e322018-08-17 14:39:04 +00002816 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
2817 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002818 if (!NUW && !NSW)
2819 break;
2820 if (!NSW && ICmpInst::isSigned(Pred))
2821 break;
2822 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2823 RBO->getOperand(0), Q, MaxRecurse - 1))
2824 return V;
2825 break;
2826 }
2827 }
2828 }
2829 return nullptr;
2830}
2831
Sanjay Patel35289c62016-12-10 17:40:47 +00002832/// Simplify integer comparisons where at least one operand of the compare
2833/// matches an integer min/max idiom.
2834static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002835 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel35289c62016-12-10 17:40:47 +00002836 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002837 Type *ITy = GetCompareTy(LHS); // The return type.
2838 Value *A, *B;
2839 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2840 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2841
2842 // Signed variants on "max(a,b)>=a -> true".
2843 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2844 if (A != RHS)
2845 std::swap(A, B); // smax(A, B) pred A.
2846 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2847 // We analyze this as smax(A, B) pred A.
2848 P = Pred;
2849 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2850 (A == LHS || B == LHS)) {
2851 if (A != LHS)
2852 std::swap(A, B); // A pred smax(A, B).
2853 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2854 // We analyze this as smax(A, B) swapped-pred A.
2855 P = CmpInst::getSwappedPredicate(Pred);
2856 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2857 (A == RHS || B == RHS)) {
2858 if (A != RHS)
2859 std::swap(A, B); // smin(A, B) pred A.
2860 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2861 // We analyze this as smax(-A, -B) swapped-pred -A.
2862 // Note that we do not need to actually form -A or -B thanks to EqP.
2863 P = CmpInst::getSwappedPredicate(Pred);
2864 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2865 (A == LHS || B == LHS)) {
2866 if (A != LHS)
2867 std::swap(A, B); // A pred smin(A, B).
2868 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2869 // We analyze this as smax(-A, -B) pred -A.
2870 // Note that we do not need to actually form -A or -B thanks to EqP.
2871 P = Pred;
2872 }
2873 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2874 // Cases correspond to "max(A, B) p A".
2875 switch (P) {
2876 default:
2877 break;
2878 case CmpInst::ICMP_EQ:
2879 case CmpInst::ICMP_SLE:
2880 // Equivalent to "A EqP B". This may be the same as the condition tested
2881 // in the max/min; if so, we can just return that.
2882 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2883 return V;
2884 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2885 return V;
2886 // Otherwise, see if "A EqP B" simplifies.
2887 if (MaxRecurse)
2888 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2889 return V;
2890 break;
2891 case CmpInst::ICMP_NE:
2892 case CmpInst::ICMP_SGT: {
2893 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2894 // Equivalent to "A InvEqP B". This may be the same as the condition
2895 // tested in the max/min; if so, we can just return that.
2896 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2897 return V;
2898 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2899 return V;
2900 // Otherwise, see if "A InvEqP B" simplifies.
2901 if (MaxRecurse)
2902 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2903 return V;
2904 break;
2905 }
2906 case CmpInst::ICMP_SGE:
2907 // Always true.
2908 return getTrue(ITy);
2909 case CmpInst::ICMP_SLT:
2910 // Always false.
2911 return getFalse(ITy);
2912 }
2913 }
2914
2915 // Unsigned variants on "max(a,b)>=a -> true".
2916 P = CmpInst::BAD_ICMP_PREDICATE;
2917 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2918 if (A != RHS)
2919 std::swap(A, B); // umax(A, B) pred A.
2920 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2921 // We analyze this as umax(A, B) pred A.
2922 P = Pred;
2923 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2924 (A == LHS || B == LHS)) {
2925 if (A != LHS)
2926 std::swap(A, B); // A pred umax(A, B).
2927 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2928 // We analyze this as umax(A, B) swapped-pred A.
2929 P = CmpInst::getSwappedPredicate(Pred);
2930 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2931 (A == RHS || B == RHS)) {
2932 if (A != RHS)
2933 std::swap(A, B); // umin(A, B) pred A.
2934 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2935 // We analyze this as umax(-A, -B) swapped-pred -A.
2936 // Note that we do not need to actually form -A or -B thanks to EqP.
2937 P = CmpInst::getSwappedPredicate(Pred);
2938 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2939 (A == LHS || B == LHS)) {
2940 if (A != LHS)
2941 std::swap(A, B); // A pred umin(A, B).
2942 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2943 // We analyze this as umax(-A, -B) pred -A.
2944 // Note that we do not need to actually form -A or -B thanks to EqP.
2945 P = Pred;
2946 }
2947 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2948 // Cases correspond to "max(A, B) p A".
2949 switch (P) {
2950 default:
2951 break;
2952 case CmpInst::ICMP_EQ:
2953 case CmpInst::ICMP_ULE:
2954 // Equivalent to "A EqP B". This may be the same as the condition tested
2955 // in the max/min; if so, we can just return that.
2956 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2957 return V;
2958 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2959 return V;
2960 // Otherwise, see if "A EqP B" simplifies.
2961 if (MaxRecurse)
2962 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2963 return V;
2964 break;
2965 case CmpInst::ICMP_NE:
2966 case CmpInst::ICMP_UGT: {
2967 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2968 // Equivalent to "A InvEqP B". This may be the same as the condition
2969 // tested in the max/min; if so, we can just return that.
2970 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2971 return V;
2972 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2973 return V;
2974 // Otherwise, see if "A InvEqP B" simplifies.
2975 if (MaxRecurse)
2976 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2977 return V;
2978 break;
2979 }
2980 case CmpInst::ICMP_UGE:
2981 // Always true.
2982 return getTrue(ITy);
2983 case CmpInst::ICMP_ULT:
2984 // Always false.
2985 return getFalse(ITy);
2986 }
2987 }
2988
2989 // Variants on "max(x,y) >= min(x,z)".
2990 Value *C, *D;
2991 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2992 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2993 (A == C || A == D || B == C || B == D)) {
2994 // max(x, ?) pred min(x, ?).
2995 if (Pred == CmpInst::ICMP_SGE)
2996 // Always true.
2997 return getTrue(ITy);
2998 if (Pred == CmpInst::ICMP_SLT)
2999 // Always false.
3000 return getFalse(ITy);
3001 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3002 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3003 (A == C || A == D || B == C || B == D)) {
3004 // min(x, ?) pred max(x, ?).
3005 if (Pred == CmpInst::ICMP_SLE)
3006 // Always true.
3007 return getTrue(ITy);
3008 if (Pred == CmpInst::ICMP_SGT)
3009 // Always false.
3010 return getFalse(ITy);
3011 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3012 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3013 (A == C || A == D || B == C || B == D)) {
3014 // max(x, ?) pred min(x, ?).
3015 if (Pred == CmpInst::ICMP_UGE)
3016 // Always true.
3017 return getTrue(ITy);
3018 if (Pred == CmpInst::ICMP_ULT)
3019 // Always false.
3020 return getFalse(ITy);
3021 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3022 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3023 (A == C || A == D || B == C || B == D)) {
3024 // min(x, ?) pred max(x, ?).
3025 if (Pred == CmpInst::ICMP_ULE)
3026 // Always true.
3027 return getTrue(ITy);
3028 if (Pred == CmpInst::ICMP_UGT)
3029 // Always false.
3030 return getFalse(ITy);
3031 }
3032
3033 return nullptr;
3034}
3035
Sanjay Patel472cc782016-01-11 22:14:42 +00003036/// Given operands for an ICmpInst, see if we can fold the result.
3037/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003038static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003039 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003040 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003041 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003042
Chris Lattnera71e9d62009-11-10 00:55:12 +00003043 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003044 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003045 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003046
3047 // If we have a constant, make sure it is on the RHS.
3048 std::swap(LHS, RHS);
3049 Pred = CmpInst::getSwappedPredicate(Pred);
3050 }
Simon Pilgrim8ee477a2019-03-19 14:08:23 +00003051 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
Duncan Sands7e800d62010-11-14 11:23:23 +00003052
Chris Lattner229907c2011-07-18 04:54:35 +00003053 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003054
Simon Pilgrim8ee477a2019-03-19 14:08:23 +00003055 // For EQ and NE, we can always pick a value for the undef to make the
3056 // predicate pass or fail, so we can return undef.
3057 // Matches behavior in llvm::ConstantFoldCompareInstruction.
3058 if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3059 return UndefValue::get(ITy);
3060
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003061 // icmp X, X -> true/false
Sanjay Patel30be6652018-04-22 17:07:44 +00003062 // icmp X, undef -> true/false because undef could be X.
Duncan Sands772749a2011-01-01 20:08:02 +00003063 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003064 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003065
Sanjay Pateldc65a272016-12-03 17:30:22 +00003066 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3067 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003068
Sanjay Pateldc65a272016-12-03 17:30:22 +00003069 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3070 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003071
Florian Hahn19f9e322018-08-17 14:39:04 +00003072 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
Sanjay Patel67bde282016-08-22 23:12:02 +00003073 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003074
Chen Li7452d952015-09-26 03:26:47 +00003075 // If both operands have range metadata, use the metadata
3076 // to simplify the comparison.
3077 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
Craig Topper0c198612017-04-10 19:37:10 +00003078 auto RHS_Instr = cast<Instruction>(RHS);
3079 auto LHS_Instr = cast<Instruction>(LHS);
Chen Li7452d952015-09-26 03:26:47 +00003080
Florian Hahn19f9e322018-08-17 14:39:04 +00003081 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3082 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003083 auto RHS_CR = getConstantRangeFromMetadata(
3084 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3085 auto LHS_CR = getConstantRangeFromMetadata(
3086 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003087
3088 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3089 if (Satisfied_CR.contains(LHS_CR))
3090 return ConstantInt::getTrue(RHS->getContext());
3091
3092 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3093 CmpInst::getInversePredicate(Pred), RHS_CR);
3094 if (InversedSatisfied_CR.contains(LHS_CR))
3095 return ConstantInt::getFalse(RHS->getContext());
3096 }
3097 }
3098
Duncan Sands8fb2c382011-01-20 13:21:55 +00003099 // Compare of cast, for example (zext X) != 0 -> X != 0
3100 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3101 Instruction *LI = cast<CastInst>(LHS);
3102 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003103 Type *SrcTy = SrcOp->getType();
3104 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003105
3106 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3107 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003108 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3109 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003110 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3111 // Transfer the cast to the constant.
3112 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3113 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003114 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003115 return V;
3116 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3117 if (RI->getOperand(0)->getType() == SrcTy)
3118 // Compare without the cast.
3119 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003120 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003121 return V;
3122 }
3123 }
3124
3125 if (isa<ZExtInst>(LHS)) {
3126 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3127 // same type.
3128 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3129 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3130 // Compare X and Y. Note that signed predicates become unsigned.
3131 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003132 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003133 MaxRecurse-1))
3134 return V;
3135 }
3136 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3137 // too. If not, then try to deduce the result of the comparison.
3138 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3139 // Compute the constant that would happen if we truncated to SrcTy then
3140 // reextended to DstTy.
3141 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3142 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3143
3144 // If the re-extended constant didn't change then this is effectively
3145 // also a case of comparing two zero-extended values.
3146 if (RExt == CI && MaxRecurse)
3147 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003148 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003149 return V;
3150
3151 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3152 // there. Use this to work out the result of the comparison.
3153 if (RExt != CI) {
3154 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003155 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003156 // LHS <u RHS.
3157 case ICmpInst::ICMP_EQ:
3158 case ICmpInst::ICMP_UGT:
3159 case ICmpInst::ICMP_UGE:
3160 return ConstantInt::getFalse(CI->getContext());
3161
3162 case ICmpInst::ICMP_NE:
3163 case ICmpInst::ICMP_ULT:
3164 case ICmpInst::ICMP_ULE:
3165 return ConstantInt::getTrue(CI->getContext());
3166
3167 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3168 // is non-negative then LHS <s RHS.
3169 case ICmpInst::ICMP_SGT:
3170 case ICmpInst::ICMP_SGE:
3171 return CI->getValue().isNegative() ?
3172 ConstantInt::getTrue(CI->getContext()) :
3173 ConstantInt::getFalse(CI->getContext());
3174
3175 case ICmpInst::ICMP_SLT:
3176 case ICmpInst::ICMP_SLE:
3177 return CI->getValue().isNegative() ?
3178 ConstantInt::getFalse(CI->getContext()) :
3179 ConstantInt::getTrue(CI->getContext());
3180 }
3181 }
3182 }
3183 }
3184
3185 if (isa<SExtInst>(LHS)) {
3186 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3187 // same type.
3188 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3189 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3190 // Compare X and Y. Note that the predicate does not change.
3191 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003192 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003193 return V;
3194 }
3195 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3196 // too. If not, then try to deduce the result of the comparison.
3197 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3198 // Compute the constant that would happen if we truncated to SrcTy then
3199 // reextended to DstTy.
3200 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3201 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3202
3203 // If the re-extended constant didn't change then this is effectively
3204 // also a case of comparing two sign-extended values.
3205 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003206 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003207 return V;
3208
3209 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3210 // bits there. Use this to work out the result of the comparison.
3211 if (RExt != CI) {
3212 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003213 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003214 case ICmpInst::ICMP_EQ:
3215 return ConstantInt::getFalse(CI->getContext());
3216 case ICmpInst::ICMP_NE:
3217 return ConstantInt::getTrue(CI->getContext());
3218
3219 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3220 // LHS >s RHS.
3221 case ICmpInst::ICMP_SGT:
3222 case ICmpInst::ICMP_SGE:
3223 return CI->getValue().isNegative() ?
3224 ConstantInt::getTrue(CI->getContext()) :
3225 ConstantInt::getFalse(CI->getContext());
3226 case ICmpInst::ICMP_SLT:
3227 case ICmpInst::ICMP_SLE:
3228 return CI->getValue().isNegative() ?
3229 ConstantInt::getFalse(CI->getContext()) :
3230 ConstantInt::getTrue(CI->getContext());
3231
3232 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3233 // LHS >u RHS.
3234 case ICmpInst::ICMP_UGT:
3235 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003236 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003237 if (MaxRecurse)
3238 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3239 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003240 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003241 return V;
3242 break;
3243 case ICmpInst::ICMP_ULT:
3244 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003245 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003246 if (MaxRecurse)
3247 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3248 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003249 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003250 return V;
3251 break;
3252 }
3253 }
3254 }
3255 }
3256 }
3257
James Molloy1d88d6f2015-10-22 13:18:42 +00003258 // icmp eq|ne X, Y -> false|true if X != Y
Craig Topperc2790ec2017-06-06 07:13:04 +00003259 if (ICmpInst::isEquality(Pred) &&
Florian Hahn19f9e322018-08-17 14:39:04 +00003260 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
Craig Topper2dfb4802017-06-06 07:13:13 +00003261 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
James Molloy1d88d6f2015-10-22 13:18:42 +00003262 }
Junmo Park53470fc2016-04-05 21:14:31 +00003263
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003264 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3265 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003266
Sanjay Patel35289c62016-12-10 17:40:47 +00003267 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003268 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003269
Chandler Carruth8059c842012-03-25 21:28:14 +00003270 // Simplify comparisons of related pointers using a powerful, recursive
3271 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003272 if (LHS->getType()->isPointerTy())
Florian Hahn19f9e322018-08-17 14:39:04 +00003273 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3274 Q.IIQ, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003275 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003276 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3277 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3278 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3279 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3280 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3281 Q.DL.getTypeSizeInBits(CRHS->getType()))
Nuno Lopes404f1062017-09-09 18:23:11 +00003282 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +00003283 Q.IIQ, CLHS->getPointerOperand(),
David Majnemerdc8767a2016-08-07 07:58:10 +00003284 CRHS->getPointerOperand()))
3285 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003286
Nick Lewycky3db143e2012-02-26 02:09:49 +00003287 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3288 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3289 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3290 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3291 (ICmpInst::isEquality(Pred) ||
3292 (GLHS->isInBounds() && GRHS->isInBounds() &&
3293 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3294 // The bases are equal and the indices are constant. Build a constant
3295 // expression GEP with the same indices and a null base pointer to see
3296 // what constant folding can make out of it.
3297 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3298 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003299 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3300 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003301
3302 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003303 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3304 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003305 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3306 }
3307 }
3308 }
3309
Duncan Sandsf532d312010-11-07 16:12:23 +00003310 // If the comparison is with the result of a select instruction, check whether
3311 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003312 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003313 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003314 return V;
3315
3316 // If the comparison is with the result of a phi instruction, check whether
3317 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003318 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003319 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003320 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003321
Craig Topper9f008862014-04-15 04:59:12 +00003322 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003323}
3324
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003325Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003326 const SimplifyQuery &Q) {
3327 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3328}
3329
Sanjay Patel472cc782016-01-11 22:14:42 +00003330/// Given operands for an FCmpInst, see if we can fold the result.
3331/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003332static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003333 FastMathFlags FMF, const SimplifyQuery &Q,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003334 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003335 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3336 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3337
Chris Lattnera71e9d62009-11-10 00:55:12 +00003338 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003339 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003340 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003341
Chris Lattnera71e9d62009-11-10 00:55:12 +00003342 // If we have a constant, make sure it is on the RHS.
3343 std::swap(LHS, RHS);
3344 Pred = CmpInst::getSwappedPredicate(Pred);
3345 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003346
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003347 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003348 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003349 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003350 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003351 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003352 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003353
Sanjay Patelf3ae9cc2018-08-21 14:45:13 +00003354 // Fold (un)ordered comparison if we can determine there are no NaNs.
3355 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3356 if (FMF.noNaNs() ||
3357 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3358 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003359
Sanjay Patel46b083e2018-03-02 18:36:08 +00003360 // NaN is unordered; NaN is not ordered.
3361 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3362 "Comparison must be either ordered or unordered");
3363 if (match(RHS, m_NaN()))
3364 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3365
Mehdi Aminieb242a52015-03-09 03:20:25 +00003366 // fcmp pred x, undef and fcmp pred undef, x
3367 // fold to true if unordered, false if ordered
3368 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3369 // Choosing NaN for the undef will always make unordered comparison succeed
3370 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003371 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003372 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003373
3374 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003375 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003376 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003377 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003378 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003379 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003380 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003381
Sanjay Patel4ca99682017-11-27 16:37:09 +00003382 // Handle fcmp with constant RHS.
Sanjay Patel68171e32019-02-20 14:34:00 +00003383 // TODO: Use match with a specific FP value, so these work with vectors with
3384 // undef lanes.
Sanjay Patel4ca99682017-11-27 16:37:09 +00003385 const APFloat *C;
3386 if (match(RHS, m_APFloat(C))) {
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003387 // Check whether the constant is an infinity.
Sanjay Patel4ca99682017-11-27 16:37:09 +00003388 if (C->isInfinity()) {
3389 if (C->isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003390 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003391 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003392 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003393 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003394 case FCmpInst::FCMP_UGE:
3395 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003396 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003397 default:
3398 break;
3399 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003400 } else {
3401 switch (Pred) {
3402 case FCmpInst::FCMP_OGT:
3403 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003404 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003405 case FCmpInst::FCMP_ULE:
3406 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003407 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003408 default:
3409 break;
3410 }
3411 }
Sanjay Patel49f97392019-02-20 00:20:38 +00003412 }
Sanjay Patel68171e32019-02-20 14:34:00 +00003413 if (C->isNegative() && !C->isNegZero()) {
Florian Hahn30932a32017-12-01 12:34:16 +00003414 assert(!C->isNaN() && "Unexpected NaN constant!");
3415 // TODO: We can catch more cases by using a range check rather than
3416 // relying on CannotBeOrderedLessThanZero.
3417 switch (Pred) {
3418 case FCmpInst::FCMP_UGE:
3419 case FCmpInst::FCMP_UGT:
3420 case FCmpInst::FCMP_UNE:
3421 // (X >= 0) implies (X > C) when (C < 0)
3422 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3423 return getTrue(RetTy);
3424 break;
3425 case FCmpInst::FCMP_OEQ:
3426 case FCmpInst::FCMP_OLE:
3427 case FCmpInst::FCMP_OLT:
3428 // (X >= 0) implies !(X < C) when (C < 0)
3429 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3430 return getFalse(RetTy);
3431 break;
3432 default:
3433 break;
3434 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003435 }
Sanjay Patel152f81f2019-05-16 14:03:10 +00003436
Sanjay Patel63fa6902019-05-20 17:52:18 +00003437 // Check comparison of [minnum/maxnum with constant] with other constant.
Sanjay Patel9ef99b42019-05-19 14:26:39 +00003438 const APFloat *C2;
3439 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3440 C2->compare(*C) == APFloat::cmpLessThan) ||
3441 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3442 C2->compare(*C) == APFloat::cmpGreaterThan)) {
3443 bool IsMaxNum =
3444 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3445 // The ordered relationship and minnum/maxnum guarantee that we do not
3446 // have NaN constants, so ordered/unordered preds are handled the same.
Sanjay Patel152f81f2019-05-16 14:03:10 +00003447 switch (Pred) {
3448 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ:
Sanjay Patel9ef99b42019-05-19 14:26:39 +00003449 // minnum(X, LesserC) == C --> false
3450 // maxnum(X, GreaterC) == C --> false
Sanjay Patel152f81f2019-05-16 14:03:10 +00003451 return getFalse(RetTy);
3452 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE:
Sanjay Patel9ef99b42019-05-19 14:26:39 +00003453 // minnum(X, LesserC) != C --> true
3454 // maxnum(X, GreaterC) != C --> true
3455 return getTrue(RetTy);
3456 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE:
3457 case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT:
3458 // minnum(X, LesserC) >= C --> false
3459 // minnum(X, LesserC) > C --> false
3460 // maxnum(X, GreaterC) >= C --> true
3461 // maxnum(X, GreaterC) > C --> true
3462 return ConstantInt::get(RetTy, IsMaxNum);
Sanjay Patel152f81f2019-05-16 14:03:10 +00003463 case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE:
3464 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT:
Sanjay Patel9ef99b42019-05-19 14:26:39 +00003465 // minnum(X, LesserC) <= C --> true
3466 // minnum(X, LesserC) < C --> true
3467 // maxnum(X, GreaterC) <= C --> false
3468 // maxnum(X, GreaterC) < C --> false
3469 return ConstantInt::get(RetTy, !IsMaxNum);
Sanjay Patel152f81f2019-05-16 14:03:10 +00003470 default:
3471 // TRUE/FALSE/ORD/UNO should be handled before this.
3472 llvm_unreachable("Unexpected fcmp predicate");
3473 }
3474 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003475 }
Sanjay Patel152f81f2019-05-16 14:03:10 +00003476
Sanjay Patel68171e32019-02-20 14:34:00 +00003477 if (match(RHS, m_AnyZeroFP())) {
3478 switch (Pred) {
3479 case FCmpInst::FCMP_OGE:
3480 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3481 return getTrue(RetTy);
3482 break;
3483 case FCmpInst::FCMP_UGE:
3484 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3485 return getTrue(RetTy);
3486 break;
3487 case FCmpInst::FCMP_ULT:
3488 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3489 return getFalse(RetTy);
3490 break;
3491 case FCmpInst::FCMP_OLT:
3492 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3493 return getFalse(RetTy);
3494 break;
3495 default:
3496 break;
3497 }
3498 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003499
Duncan Sandsa620bd12010-11-07 16:46:25 +00003500 // If the comparison is with the result of a select instruction, check whether
3501 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003502 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003503 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003504 return V;
3505
3506 // If the comparison is with the result of a phi instruction, check whether
3507 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003508 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003509 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003510 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003511
Craig Topper9f008862014-04-15 04:59:12 +00003512 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003513}
3514
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003515Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003516 FastMathFlags FMF, const SimplifyQuery &Q) {
3517 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003518}
3519
Sanjay Patel472cc782016-01-11 22:14:42 +00003520/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003521static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003522 const SimplifyQuery &Q,
David Majnemer3f0fb982015-06-06 22:40:21 +00003523 unsigned MaxRecurse) {
3524 // Trivial replacement.
3525 if (V == Op)
3526 return RepOp;
3527
Tim Northover997f5f12017-05-22 21:28:08 +00003528 // We cannot replace a constant, and shouldn't even try.
3529 if (isa<Constant>(Op))
3530 return nullptr;
3531
David Majnemer3f0fb982015-06-06 22:40:21 +00003532 auto *I = dyn_cast<Instruction>(V);
3533 if (!I)
3534 return nullptr;
3535
3536 // If this is a binary operator, try to simplify it with the replaced op.
3537 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3538 // Consider:
3539 // %cmp = icmp eq i32 %x, 2147483647
3540 // %add = add nsw i32 %x, 1
3541 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3542 //
3543 // We can't replace %sel with %add unless we strip away the flags.
3544 if (isa<OverflowingBinaryOperator>(B))
Florian Hahn19f9e322018-08-17 14:39:04 +00003545 if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
David Majnemer3f0fb982015-06-06 22:40:21 +00003546 return nullptr;
Florian Hahn19f9e322018-08-17 14:39:04 +00003547 if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3548 return nullptr;
David Majnemer3f0fb982015-06-06 22:40:21 +00003549
3550 if (MaxRecurse) {
3551 if (B->getOperand(0) == Op)
3552 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3553 MaxRecurse - 1);
3554 if (B->getOperand(1) == Op)
3555 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3556 MaxRecurse - 1);
3557 }
3558 }
3559
3560 // Same for CmpInsts.
3561 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3562 if (MaxRecurse) {
3563 if (C->getOperand(0) == Op)
3564 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3565 MaxRecurse - 1);
3566 if (C->getOperand(1) == Op)
3567 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3568 MaxRecurse - 1);
3569 }
3570 }
3571
George Burgess IV8e807bf2018-04-24 00:25:01 +00003572 // Same for GEPs.
3573 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3574 if (MaxRecurse) {
3575 SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3576 transform(GEP->operands(), NewOps.begin(),
3577 [&](Value *V) { return V == Op ? RepOp : V; });
3578 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3579 MaxRecurse - 1);
3580 }
3581 }
3582
David Majnemer3f0fb982015-06-06 22:40:21 +00003583 // TODO: We could hand off more cases to instsimplify here.
3584
3585 // If all operands are constant after substituting Op for RepOp then we can
3586 // constant fold the instruction.
3587 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3588 // Build a list of all constant operands.
3589 SmallVector<Constant *, 8> ConstOps;
3590 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3591 if (I->getOperand(i) == Op)
3592 ConstOps.push_back(CRepOp);
3593 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3594 ConstOps.push_back(COp);
3595 else
3596 break;
3597 }
3598
3599 // All operands were constants, fold it.
3600 if (ConstOps.size() == I->getNumOperands()) {
3601 if (CmpInst *C = dyn_cast<CmpInst>(I))
3602 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3603 ConstOps[1], Q.DL, Q.TLI);
3604
3605 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3606 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003607 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003608
Manuel Jacobe9024592016-01-21 06:33:22 +00003609 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003610 }
3611 }
3612
3613 return nullptr;
3614}
3615
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003616/// Try to simplify a select instruction when its condition operand is an
3617/// integer comparison where one operand of the compare is a constant.
3618static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3619 const APInt *Y, bool TrueWhenUnset) {
3620 const APInt *C;
3621
3622 // (X & Y) == 0 ? X & ~Y : X --> X
3623 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3624 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3625 *Y == ~*C)
3626 return TrueWhenUnset ? FalseVal : TrueVal;
3627
3628 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3629 // (X & Y) != 0 ? X : X & ~Y --> X
3630 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3631 *Y == ~*C)
3632 return TrueWhenUnset ? FalseVal : TrueVal;
3633
3634 if (Y->isPowerOf2()) {
3635 // (X & Y) == 0 ? X | Y : X --> X | Y
3636 // (X & Y) != 0 ? X | Y : X --> X
3637 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3638 *Y == *C)
3639 return TrueWhenUnset ? TrueVal : FalseVal;
3640
3641 // (X & Y) == 0 ? X : X | Y --> X
3642 // (X & Y) != 0 ? X : X | Y --> X | Y
3643 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3644 *Y == *C)
3645 return TrueWhenUnset ? TrueVal : FalseVal;
3646 }
Matt Arsenault82606662017-01-11 00:57:54 +00003647
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003648 return nullptr;
3649}
3650
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003651/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3652/// eq/ne.
Craig Topper0aa3a192017-08-14 21:39:51 +00003653static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3654 ICmpInst::Predicate Pred,
3655 Value *TrueVal, Value *FalseVal) {
3656 Value *X;
3657 APInt Mask;
3658 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3659 return nullptr;
3660
Craig Topper0aa3a192017-08-14 21:39:51 +00003661 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3662 Pred == ICmpInst::ICMP_EQ);
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003663}
3664
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003665/// Try to simplify a select instruction when its condition operand is an
3666/// integer comparison.
3667static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003668 Value *FalseVal, const SimplifyQuery &Q,
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003669 unsigned MaxRecurse) {
3670 ICmpInst::Predicate Pred;
3671 Value *CmpLHS, *CmpRHS;
3672 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3673 return nullptr;
3674
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003675 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3676 Value *X;
3677 const APInt *Y;
3678 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3679 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3680 Pred == ICmpInst::ICMP_EQ))
3681 return V;
Sanjay Patele98ec772018-11-15 14:53:37 +00003682
Sanjay Patel9dada832019-02-26 18:26:56 +00003683 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
Sanjay Patele98ec772018-11-15 14:53:37 +00003684 Value *ShAmt;
3685 auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3686 m_Value(ShAmt)),
3687 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3688 m_Value(ShAmt)));
Sanjay Patele98ec772018-11-15 14:53:37 +00003689 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3690 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
Sanjay Patel9dada832019-02-26 18:26:56 +00003691 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3692 Pred == ICmpInst::ICMP_EQ)
3693 return X;
Sanjay Patele98ec772018-11-15 14:53:37 +00003694 // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3695 // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
Sanjay Patel9dada832019-02-26 18:26:56 +00003696 if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3697 Pred == ICmpInst::ICMP_NE)
3698 return X;
3699
3700 // Test for a zero-shift-guard-op around rotates. These are used to
3701 // avoid UB from oversized shifts in raw IR rotate patterns, but the
3702 // intrinsics do not have that problem.
3703 // We do not allow this transform for the general funnel shift case because
3704 // that would not preserve the poison safety of the original code.
3705 auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3706 m_Deferred(X),
3707 m_Value(ShAmt)),
3708 m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3709 m_Deferred(X),
3710 m_Value(ShAmt)));
3711 // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3712 // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3713 if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3714 Pred == ICmpInst::ICMP_NE)
3715 return TrueVal;
3716 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3717 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3718 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3719 Pred == ICmpInst::ICMP_EQ)
3720 return FalseVal;
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003721 }
3722
Craig Topper0aa3a192017-08-14 21:39:51 +00003723 // Check for other compares that behave like bit test.
3724 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3725 TrueVal, FalseVal))
3726 return V;
3727
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003728 // If we have an equality comparison, then we know the value in one of the
3729 // arms of the select. See if substituting this value into the arm and
3730 // simplifying the result yields the same value as the other arm.
3731 if (Pred == ICmpInst::ICMP_EQ) {
3732 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3733 TrueVal ||
3734 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3735 TrueVal)
3736 return FalseVal;
3737 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3738 FalseVal ||
3739 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3740 FalseVal)
3741 return FalseVal;
3742 } else if (Pred == ICmpInst::ICMP_NE) {
3743 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3744 FalseVal ||
3745 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3746 FalseVal)
3747 return TrueVal;
3748 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3749 TrueVal ||
3750 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3751 TrueVal)
3752 return TrueVal;
3753 }
3754
3755 return nullptr;
3756}
3757
Sanjay Patel14401072018-11-05 21:51:39 +00003758/// Try to simplify a select instruction when its condition operand is a
3759/// floating-point comparison.
3760static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3761 FCmpInst::Predicate Pred;
3762 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3763 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3764 return nullptr;
3765
3766 // TODO: The transform may not be valid with -0.0. An incomplete way of
3767 // testing for that possibility is to check if at least one operand is a
3768 // non-zero constant.
3769 const APFloat *C;
3770 if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3771 (match(F, m_APFloat(C)) && C->isNonZero())) {
3772 // (T == F) ? T : F --> F
3773 // (F == T) ? T : F --> F
3774 if (Pred == FCmpInst::FCMP_OEQ)
3775 return F;
3776
3777 // (T != F) ? T : F --> T
3778 // (F != T) ? T : F --> T
3779 if (Pred == FCmpInst::FCMP_UNE)
3780 return T;
3781 }
3782
3783 return nullptr;
3784}
3785
Sanjay Patel472cc782016-01-11 22:14:42 +00003786/// Given operands for a SelectInst, see if we can fold the result.
3787/// If not, this returns null.
Sanjay Patelac395202018-02-17 14:50:13 +00003788static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3789 const SimplifyQuery &Q, unsigned MaxRecurse) {
3790 if (auto *CondC = dyn_cast<Constant>(Cond)) {
3791 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3792 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3793 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3794
3795 // select undef, X, Y -> X or Y
3796 if (isa<UndefValue>(CondC))
3797 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3798
3799 // TODO: Vector constants with undef elements don't simplify.
3800
3801 // select true, X, Y -> X
3802 if (CondC->isAllOnesValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003803 return TrueVal;
Sanjay Patelac395202018-02-17 14:50:13 +00003804 // select false, X, Y -> Y
3805 if (CondC->isNullValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003806 return FalseVal;
3807 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003808
Sanjay Patelac395202018-02-17 14:50:13 +00003809 // select ?, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003810 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003811 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003812
Sanjay Patelac395202018-02-17 14:50:13 +00003813 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00003814 return FalseVal;
Sanjay Patelac395202018-02-17 14:50:13 +00003815 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00003816 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003817
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003818 if (Value *V =
Sanjay Patelac395202018-02-17 14:50:13 +00003819 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003820 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003821
Sanjay Patel14401072018-11-05 21:51:39 +00003822 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
3823 return V;
3824
David Bolvanskyf9476082018-07-28 06:55:51 +00003825 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
3826 return V;
3827
Sanjay Patel7d82d372018-12-02 13:26:03 +00003828 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
3829 if (Imp)
3830 return *Imp ? TrueVal : FalseVal;
Sanjay Pateld8022702018-11-29 18:44:39 +00003831
Craig Topper9f008862014-04-15 04:59:12 +00003832 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003833}
3834
Duncan Sandsb8cee002012-03-13 11:42:19 +00003835Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003836 const SimplifyQuery &Q) {
3837 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003838}
3839
Sanjay Patel472cc782016-01-11 22:14:42 +00003840/// Given operands for an GetElementPtrInst, see if we can fold the result.
3841/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003842static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003843 const SimplifyQuery &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003844 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003845 unsigned AS =
3846 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003847
Chris Lattner8574aba2009-11-27 00:29:05 +00003848 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003849 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003850 return Ops[0];
3851
Nico Weber48c82402014-08-27 20:06:19 +00003852 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003853 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003854 Type *GEPTy = PointerType::get(LastType, AS);
3855 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3856 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Davide Italianoa9f047a2017-04-19 14:23:42 +00003857 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3858 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Nico Weber48c82402014-08-27 20:06:19 +00003859
3860 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003861 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003862
Jay Foadb992a632011-07-19 15:07:52 +00003863 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003864 // getelementptr P, 0 -> P.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00003865 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003866 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003867
David Blaikie4a2e73b2015-04-02 18:55:32 +00003868 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003869 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003870 Value *P;
3871 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003872 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003873 // getelementptr P, N -> P if P points to a type of zero size.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00003874 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003875 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003876
3877 // The following transforms are only safe if the ptrtoint cast
3878 // doesn't truncate the pointers.
3879 if (Ops[1]->getType()->getScalarSizeInBits() ==
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003880 Q.DL.getIndexSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003881 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3882 if (match(P, m_Zero()))
3883 return Constant::getNullValue(GEPTy);
3884 Value *Temp;
3885 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003886 if (Temp->getType() == GEPTy)
3887 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003888 return nullptr;
3889 };
3890
3891 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3892 if (TyAllocSize == 1 &&
3893 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3894 if (Value *R = PtrToIntOrZero(P))
3895 return R;
3896
3897 // getelementptr V, (ashr (sub P, V), C) -> Q
3898 // if P points to a type of size 1 << C.
3899 if (match(Ops[1],
3900 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3901 m_ConstantInt(C))) &&
3902 TyAllocSize == 1ULL << C)
3903 if (Value *R = PtrToIntOrZero(P))
3904 return R;
3905
3906 // getelementptr V, (sdiv (sub P, V), C) -> Q
3907 // if P points to a type of size C.
3908 if (match(Ops[1],
3909 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3910 m_SpecificInt(TyAllocSize))))
3911 if (Value *R = PtrToIntOrZero(P))
3912 return R;
3913 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003914 }
3915 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003916
David Majnemerd1501372016-08-07 07:58:12 +00003917 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3918 all_of(Ops.slice(1).drop_back(1),
3919 [](Value *Idx) { return match(Idx, m_Zero()); })) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003920 unsigned IdxWidth =
3921 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3922 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
3923 APInt BasePtrOffset(IdxWidth, 0);
David Majnemerd1501372016-08-07 07:58:12 +00003924 Value *StrippedBasePtr =
3925 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3926 BasePtrOffset);
3927
David Majnemer5c5df622016-08-16 06:13:46 +00003928 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003929 if (match(Ops.back(),
3930 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3931 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3932 return ConstantExpr::getIntToPtr(CI, GEPTy);
3933 }
David Majnemer5c5df622016-08-16 06:13:46 +00003934 // gep (gep V, C), (xor V, -1) -> C-1
3935 if (match(Ops.back(),
3936 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3937 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3938 return ConstantExpr::getIntToPtr(CI, GEPTy);
3939 }
David Majnemerd1501372016-08-07 07:58:12 +00003940 }
3941 }
3942
Chris Lattner8574aba2009-11-27 00:29:05 +00003943 // Check to see if this is constant foldable.
Craig Topperda8037f2017-06-04 22:41:56 +00003944 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
3945 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003946
Joey Gouly61eaa632017-06-06 10:17:14 +00003947 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3948 Ops.slice(1));
3949 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
3950 return CEFolded;
3951 return CE;
Chris Lattner8574aba2009-11-27 00:29:05 +00003952}
3953
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003954Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003955 const SimplifyQuery &Q) {
3956 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003957}
3958
Sanjay Patel472cc782016-01-11 22:14:42 +00003959/// Given operands for an InsertValueInst, see if we can fold the result.
3960/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003961static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003962 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003963 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003964 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3965 if (Constant *CVal = dyn_cast<Constant>(Val))
3966 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3967
3968 // insertvalue x, undef, n -> x
3969 if (match(Val, m_Undef()))
3970 return Agg;
3971
3972 // insertvalue x, (extractvalue y, n), n
3973 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003974 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3975 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003976 // insertvalue undef, (extractvalue y, n), n -> y
3977 if (match(Agg, m_Undef()))
3978 return EV->getAggregateOperand();
3979
3980 // insertvalue y, (extractvalue y, n), n -> y
3981 if (Agg == EV->getAggregateOperand())
3982 return Agg;
3983 }
3984
Craig Topper9f008862014-04-15 04:59:12 +00003985 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003986}
3987
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003988Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3989 ArrayRef<unsigned> Idxs,
3990 const SimplifyQuery &Q) {
3991 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3992}
3993
Igor Laevskye0edb662017-12-13 11:21:18 +00003994Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
3995 const SimplifyQuery &Q) {
3996 // Try to constant fold.
3997 auto *VecC = dyn_cast<Constant>(Vec);
3998 auto *ValC = dyn_cast<Constant>(Val);
3999 auto *IdxC = dyn_cast<Constant>(Idx);
4000 if (VecC && ValC && IdxC)
4001 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4002
4003 // Fold into undef if index is out of bounds.
4004 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4005 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
Igor Laevskye0edb662017-12-13 11:21:18 +00004006 if (CI->uge(NumElements))
4007 return UndefValue::get(Vec->getType());
4008 }
4009
Philip Reamese499bc32017-12-30 05:54:22 +00004010 // If index is undef, it might be out of bounds (see above case)
4011 if (isa<UndefValue>(Idx))
4012 return UndefValue::get(Vec->getType());
Igor Laevskye0edb662017-12-13 11:21:18 +00004013
4014 return nullptr;
4015}
4016
Sanjay Patel472cc782016-01-11 22:14:42 +00004017/// Given operands for an ExtractValueInst, see if we can fold the result.
4018/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00004019static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004020 const SimplifyQuery &, unsigned) {
David Majnemer25a796e2015-07-13 01:15:46 +00004021 if (auto *CAgg = dyn_cast<Constant>(Agg))
4022 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4023
4024 // extractvalue x, (insertvalue y, elt, n), n -> elt
4025 unsigned NumIdxs = Idxs.size();
4026 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4027 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4028 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4029 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4030 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4031 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4032 Idxs.slice(0, NumCommonIdxs)) {
4033 if (NumIdxs == NumInsertValueIdxs)
4034 return IVI->getInsertedValueOperand();
4035 break;
4036 }
4037 }
4038
4039 return nullptr;
4040}
4041
4042Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004043 const SimplifyQuery &Q) {
4044 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4045}
4046
Sanjay Patel472cc782016-01-11 22:14:42 +00004047/// Given operands for an ExtractElementInst, see if we can fold the result.
4048/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004049static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
David Majnemer599ca442015-07-13 01:15:53 +00004050 unsigned) {
4051 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4052 if (auto *CIdx = dyn_cast<Constant>(Idx))
4053 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4054
4055 // The index is not relevant if our vector is a splat.
4056 if (auto *Splat = CVec->getSplatValue())
4057 return Splat;
4058
4059 if (isa<UndefValue>(Vec))
4060 return UndefValue::get(Vec->getType()->getVectorElementType());
4061 }
4062
4063 // If extracting a specified index from the vector, see if we can recursively
4064 // find a previously computed scalar that was inserted into the vector.
Philip Reamese499bc32017-12-30 05:54:22 +00004065 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4066 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4067 // definitely out of bounds, thus undefined result
4068 return UndefValue::get(Vec->getType()->getVectorElementType());
4069 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4070 return Elt;
4071 }
David Majnemer599ca442015-07-13 01:15:53 +00004072
Zvi Rackover2e6e88f2017-12-06 17:51:46 +00004073 // An undef extract index can be arbitrarily chosen to be an out-of-range
4074 // index value, which would result in the instruction being undef.
4075 if (isa<UndefValue>(Idx))
4076 return UndefValue::get(Vec->getType()->getVectorElementType());
4077
David Majnemer599ca442015-07-13 01:15:53 +00004078 return nullptr;
4079}
4080
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004081Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4082 const SimplifyQuery &Q) {
4083 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4084}
4085
Sanjay Patel472cc782016-01-11 22:14:42 +00004086/// See if we can fold the given phi. If not, returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004087static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004088 // If all of the PHI's incoming values are the same then replace the PHI node
4089 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004090 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004091 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004092 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004093 // If the incoming value is the phi node itself, it can safely be skipped.
4094 if (Incoming == PN) continue;
4095 if (isa<UndefValue>(Incoming)) {
4096 // Remember that we saw an undef value, but otherwise ignore them.
4097 HasUndefInput = true;
4098 continue;
4099 }
4100 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004101 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004102 CommonValue = Incoming;
4103 }
4104
4105 // If CommonValue is null then all of the incoming values were either undef or
4106 // equal to the phi node itself.
4107 if (!CommonValue)
4108 return UndefValue::get(PN->getType());
4109
4110 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4111 // instruction, we cannot return X as the result of the PHI node unless it
4112 // dominates the PHI block.
4113 if (HasUndefInput)
Sanjay Patel5da361a2018-04-10 18:38:19 +00004114 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004115
4116 return CommonValue;
4117}
4118
David Majnemer6774d612016-07-26 17:58:05 +00004119static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004120 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004121 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004122 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004123
David Majnemer6774d612016-07-26 17:58:05 +00004124 if (auto *CI = dyn_cast<CastInst>(Op)) {
4125 auto *Src = CI->getOperand(0);
4126 Type *SrcTy = Src->getType();
4127 Type *MidTy = CI->getType();
4128 Type *DstTy = Ty;
4129 if (Src->getType() == Ty) {
4130 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4131 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4132 Type *SrcIntPtrTy =
4133 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4134 Type *MidIntPtrTy =
4135 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4136 Type *DstIntPtrTy =
4137 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4138 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4139 SrcIntPtrTy, MidIntPtrTy,
4140 DstIntPtrTy) == Instruction::BitCast)
4141 return Src;
4142 }
4143 }
David Majnemera90a6212016-07-26 05:52:29 +00004144
4145 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004146 if (CastOpc == Instruction::BitCast)
4147 if (Op->getType() == Ty)
4148 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004149
4150 return nullptr;
4151}
4152
David Majnemer6774d612016-07-26 17:58:05 +00004153Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004154 const SimplifyQuery &Q) {
4155 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4156}
4157
Sanjay Patela3c297d2017-04-19 16:48:22 +00004158/// For the given destination element of a shuffle, peek through shuffles to
4159/// match a root vector source operand that contains that element in the same
4160/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4161static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
Zvi Rackover558f86b2017-05-08 15:46:58 +00004162 int MaskVal, Value *RootVec,
Sanjay Patela3c297d2017-04-19 16:48:22 +00004163 unsigned MaxRecurse) {
4164 if (!MaxRecurse--)
4165 return nullptr;
4166
4167 // Bail out if any mask value is undefined. That kind of shuffle may be
4168 // simplified further based on demanded bits or other folds.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004169 if (MaskVal == -1)
4170 return nullptr;
4171
4172 // The mask value chooses which source operand we need to look at next.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004173 int InVecNumElts = Op0->getType()->getVectorNumElements();
Zvi Rackover558f86b2017-05-08 15:46:58 +00004174 int RootElt = MaskVal;
4175 Value *SourceOp = Op0;
4176 if (MaskVal >= InVecNumElts) {
Sanjay Patela3c297d2017-04-19 16:48:22 +00004177 RootElt = MaskVal - InVecNumElts;
4178 SourceOp = Op1;
4179 }
4180
4181 // If the source operand is a shuffle itself, look through it to find the
4182 // matching root vector.
4183 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4184 return foldIdentityShuffles(
4185 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
Zvi Rackover558f86b2017-05-08 15:46:58 +00004186 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004187 }
4188
4189 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4190 // size?
4191
4192 // The source operand is not a shuffle. Initialize the root vector value for
4193 // this shuffle if that has not been done yet.
4194 if (!RootVec)
4195 RootVec = SourceOp;
4196
4197 // Give up as soon as a source operand does not match the existing root value.
4198 if (RootVec != SourceOp)
4199 return nullptr;
4200
4201 // The element must be coming from the same lane in the source vector
4202 // (although it may have crossed lanes in intermediate shuffles).
4203 if (RootElt != DestElt)
4204 return nullptr;
4205
4206 return RootVec;
4207}
4208
Zvi Rackover8f460652017-04-03 22:05:30 +00004209static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004210 Type *RetTy, const SimplifyQuery &Q,
Zvi Rackover8f460652017-04-03 22:05:30 +00004211 unsigned MaxRecurse) {
Zvi Rackover4086e132017-04-30 06:06:26 +00004212 if (isa<UndefValue>(Mask))
4213 return UndefValue::get(RetTy);
4214
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004215 Type *InVecTy = Op0->getType();
Zvi Rackover8f460652017-04-03 22:05:30 +00004216 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004217 unsigned InVecNumElts = InVecTy->getVectorNumElements();
Zvi Rackover8f460652017-04-03 22:05:30 +00004218
Zvi Rackover0411e462017-04-30 06:10:54 +00004219 SmallVector<int, 32> Indices;
4220 ShuffleVectorInst::getShuffleMask(Mask, Indices);
4221 assert(MaskNumElts == Indices.size() &&
4222 "Size of Indices not same as number of mask elements?");
4223
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004224 // Canonicalization: If mask does not select elements from an input vector,
4225 // replace that input vector with undef.
Zvi Rackover8f460652017-04-03 22:05:30 +00004226 bool MaskSelects0 = false, MaskSelects1 = false;
4227 for (unsigned i = 0; i != MaskNumElts; ++i) {
Zvi Rackover0411e462017-04-30 06:10:54 +00004228 if (Indices[i] == -1)
Zvi Rackover8f460652017-04-03 22:05:30 +00004229 continue;
Zvi Rackover0411e462017-04-30 06:10:54 +00004230 if ((unsigned)Indices[i] < InVecNumElts)
Zvi Rackover8f460652017-04-03 22:05:30 +00004231 MaskSelects0 = true;
4232 else
4233 MaskSelects1 = true;
4234 }
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004235 if (!MaskSelects0)
4236 Op0 = UndefValue::get(InVecTy);
4237 if (!MaskSelects1)
4238 Op1 = UndefValue::get(InVecTy);
4239
4240 auto *Op0Const = dyn_cast<Constant>(Op0);
4241 auto *Op1Const = dyn_cast<Constant>(Op1);
4242
4243 // If all operands are constant, constant fold the shuffle.
4244 if (Op0Const && Op1Const)
4245 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4246
4247 // Canonicalization: if only one input vector is constant, it shall be the
4248 // second one.
4249 if (Op0Const && !Op1Const) {
4250 std::swap(Op0, Op1);
Zvi Rackoverdfbd3d72017-05-08 12:40:18 +00004251 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004252 }
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004253
4254 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4255 // value type is same as the input vectors' type.
4256 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004257 if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004258 OpShuf->getMask()->getSplatValue())
4259 return Op0;
Zvi Rackover8f460652017-04-03 22:05:30 +00004260
Sanjay Patela3c297d2017-04-19 16:48:22 +00004261 // Don't fold a shuffle with undef mask elements. This may get folded in a
4262 // better way using demanded bits or other analysis.
4263 // TODO: Should we allow this?
Zvi Rackover0411e462017-04-30 06:10:54 +00004264 if (find(Indices, -1) != Indices.end())
4265 return nullptr;
Sanjay Patela3c297d2017-04-19 16:48:22 +00004266
4267 // Check if every element of this shuffle can be mapped back to the
4268 // corresponding element of a single root vector. If so, we don't need this
4269 // shuffle. This handles simple identity shuffles as well as chains of
4270 // shuffles that may widen/narrow and/or move elements across lanes and back.
4271 Value *RootVec = nullptr;
4272 for (unsigned i = 0; i != MaskNumElts; ++i) {
4273 // Note that recursion is limited for each vector element, so if any element
4274 // exceeds the limit, this will fail to simplify.
Zvi Rackover558f86b2017-05-08 15:46:58 +00004275 RootVec =
4276 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004277
4278 // We can't replace a widening/narrowing shuffle with one of its operands.
4279 if (!RootVec || RootVec->getType() != RetTy)
4280 return nullptr;
4281 }
4282 return RootVec;
Zvi Rackover8f460652017-04-03 22:05:30 +00004283}
4284
4285/// Given operands for a ShuffleVectorInst, fold the result or return null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004286Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4287 Type *RetTy, const SimplifyQuery &Q) {
4288 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
Zvi Rackover8f460652017-04-03 22:05:30 +00004289}
4290
Cameron McInallyc3167692019-05-06 16:05:10 +00004291static Constant *foldConstant(Instruction::UnaryOps Opcode,
4292 Value *&Op, const SimplifyQuery &Q) {
4293 if (auto *C = dyn_cast<Constant>(Op))
4294 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4295 return nullptr;
4296}
4297
4298/// Given the operand for an FNeg, see if we can fold the result. If not, this
4299/// returns null.
4300static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
4301 const SimplifyQuery &Q, unsigned MaxRecurse) {
4302 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4303 return C;
4304
4305 Value *X;
4306 // fneg (fneg X) ==> X
4307 if (match(Op, m_FNeg(m_Value(X))))
4308 return X;
4309
4310 return nullptr;
4311}
4312
4313Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF,
4314 const SimplifyQuery &Q) {
4315 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
4316}
4317
Sanjay Patele2359422018-03-21 19:31:53 +00004318static Constant *propagateNaN(Constant *In) {
4319 // If the input is a vector with undef elements, just return a default NaN.
4320 if (!In->isNaN())
4321 return ConstantFP::getNaN(In->getType());
4322
4323 // Propagate the existing NaN constant when possible.
4324 // TODO: Should we quiet a signaling NaN?
4325 return In;
4326}
4327
4328static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4329 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4330 return ConstantFP::getNaN(Op0->getType());
4331
4332 if (match(Op0, m_NaN()))
4333 return propagateNaN(cast<Constant>(Op0));
4334 if (match(Op1, m_NaN()))
4335 return propagateNaN(cast<Constant>(Op1));
4336
4337 return nullptr;
4338}
4339
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004340/// Given operands for an FAdd, see if we can fold the result. If not, this
4341/// returns null.
4342static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4343 const SimplifyQuery &Q, unsigned MaxRecurse) {
4344 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4345 return C;
4346
Sanjay Patele2359422018-03-21 19:31:53 +00004347 if (Constant *C = simplifyFPBinop(Op0, Op1))
4348 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004349
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004350 // fadd X, -0 ==> X
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004351 if (match(Op1, m_NegZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004352 return Op0;
4353
4354 // fadd X, 0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004355 if (match(Op1, m_PosZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004356 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4357 return Op0;
4358
Cameron McInally0c82d9b2019-05-15 14:31:33 +00004359 // With nnan: -X + X --> 0.0 (and commuted variant)
Sanjay Patel11f7f992018-03-14 21:23:27 +00004360 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4361 // Negative zeros are allowed because we always end up with positive zero:
4362 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4363 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4364 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4365 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
Cameron McInally0c82d9b2019-05-15 14:31:33 +00004366 if (FMF.noNaNs()) {
4367 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4368 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4369 return ConstantFP::getNullValue(Op0->getType());
4370
4371 if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4372 match(Op1, m_FNeg(m_Specific(Op0))))
4373 return ConstantFP::getNullValue(Op0->getType());
4374 }
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004375
Sanjay Patel9b073472018-08-07 20:32:55 +00004376 // (X - Y) + Y --> X
4377 // Y + (X - Y) --> X
4378 Value *X;
4379 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4380 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4381 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4382 return X;
4383
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004384 return nullptr;
4385}
4386
4387/// Given operands for an FSub, see if we can fold the result. If not, this
4388/// returns null.
4389static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4390 const SimplifyQuery &Q, unsigned MaxRecurse) {
4391 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4392 return C;
4393
Sanjay Patele2359422018-03-21 19:31:53 +00004394 if (Constant *C = simplifyFPBinop(Op0, Op1))
4395 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004396
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004397 // fsub X, +0 ==> X
4398 if (match(Op1, m_PosZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004399 return Op0;
4400
4401 // fsub X, -0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004402 if (match(Op1, m_NegZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004403 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4404 return Op0;
4405
4406 // fsub -0.0, (fsub -0.0, X) ==> X
Cameron McInally2d2a46d2019-05-20 13:13:35 +00004407 // fsub -0.0, (fneg X) ==> X
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004408 Value *X;
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004409 if (match(Op0, m_NegZeroFP()) &&
Cameron McInally2d2a46d2019-05-20 13:13:35 +00004410 match(Op1, m_FNeg(m_Value(X))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004411 return X;
4412
4413 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Cameron McInally067e9462019-05-17 16:47:00 +00004414 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
Sanjay Patela4f42f22018-03-15 14:29:27 +00004415 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
Cameron McInally067e9462019-05-17 16:47:00 +00004416 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4417 match(Op1, m_FNeg(m_Value(X)))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004418 return X;
4419
4420 // fsub nnan x, x ==> 0.0
4421 if (FMF.noNaNs() && Op0 == Op1)
4422 return Constant::getNullValue(Op0->getType());
4423
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004424 // Y - (Y - X) --> X
Sanjay Patel4364d602018-08-07 20:23:49 +00004425 // (X + Y) - Y --> X
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004426 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
Sanjay Patel4364d602018-08-07 20:23:49 +00004427 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4428 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004429 return X;
4430
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004431 return nullptr;
4432}
4433
4434/// Given the operands for an FMul, see if we can fold the result
4435static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4436 const SimplifyQuery &Q, unsigned MaxRecurse) {
4437 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4438 return C;
4439
Sanjay Patele2359422018-03-21 19:31:53 +00004440 if (Constant *C = simplifyFPBinop(Op0, Op1))
4441 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004442
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004443 // fmul X, 1.0 ==> X
4444 if (match(Op1, m_FPOne()))
4445 return Op0;
4446
4447 // fmul nnan nsz X, 0 ==> 0
Sanjay Patela4f42f22018-03-15 14:29:27 +00004448 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4449 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004450
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004451 // sqrt(X) * sqrt(X) --> X, if we can:
4452 // 1. Remove the intermediate rounding (reassociate).
4453 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4454 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
Sanjay Pateldb53d182018-02-23 22:20:13 +00004455 Value *X;
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004456 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4457 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
Sanjay Pateldb53d182018-02-23 22:20:13 +00004458 return X;
4459
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004460 return nullptr;
4461}
4462
4463Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4464 const SimplifyQuery &Q) {
4465 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4466}
4467
4468
4469Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4470 const SimplifyQuery &Q) {
4471 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4472}
4473
4474Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4475 const SimplifyQuery &Q) {
4476 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4477}
4478
4479static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4480 const SimplifyQuery &Q, unsigned) {
4481 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4482 return C;
4483
Sanjay Patele2359422018-03-21 19:31:53 +00004484 if (Constant *C = simplifyFPBinop(Op0, Op1))
4485 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004486
4487 // X / 1.0 -> X
4488 if (match(Op1, m_FPOne()))
4489 return Op0;
4490
4491 // 0 / X -> 0
4492 // Requires that NaNs are off (X could be zero) and signed zeroes are
4493 // ignored (X could be positive or negative, so the output sign is unknown).
Sanjay Patela4f42f22018-03-15 14:29:27 +00004494 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4495 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004496
4497 if (FMF.noNaNs()) {
4498 // X / X -> 1.0 is legal when NaNs are ignored.
Sanjay Patel83f05662018-01-30 00:18:37 +00004499 // We can ignore infinities because INF/INF is NaN.
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004500 if (Op0 == Op1)
4501 return ConstantFP::get(Op0->getType(), 1.0);
4502
Sanjay Patel83f05662018-01-30 00:18:37 +00004503 // (X * Y) / Y --> X if we can reassociate to the above form.
4504 Value *X;
4505 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4506 return X;
4507
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004508 // -X / X -> -1.0 and
4509 // X / -X -> -1.0 are legal when NaNs are ignored.
4510 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
Cameron McInallybea59672018-10-09 21:48:00 +00004511 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4512 match(Op1, m_FNegNSZ(m_Specific(Op0))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004513 return ConstantFP::get(Op0->getType(), -1.0);
4514 }
4515
4516 return nullptr;
4517}
4518
4519Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4520 const SimplifyQuery &Q) {
4521 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4522}
4523
4524static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4525 const SimplifyQuery &Q, unsigned) {
4526 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4527 return C;
4528
Sanjay Patele2359422018-03-21 19:31:53 +00004529 if (Constant *C = simplifyFPBinop(Op0, Op1))
4530 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004531
Sanjay Patel8f063d02018-03-15 14:04:31 +00004532 // Unlike fdiv, the result of frem always matches the sign of the dividend.
4533 // The constant match may include undef elements in a vector, so return a full
4534 // zero constant as the result.
4535 if (FMF.noNaNs()) {
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004536 // +0 % X -> 0
4537 if (match(Op0, m_PosZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004538 return ConstantFP::getNullValue(Op0->getType());
4539 // -0 % X -> -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004540 if (match(Op0, m_NegZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004541 return ConstantFP::getNegativeZero(Op0->getType());
4542 }
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004543
4544 return nullptr;
4545}
4546
4547Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4548 const SimplifyQuery &Q) {
4549 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4550}
4551
Chris Lattnera71e9d62009-11-10 00:55:12 +00004552//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004553
Cameron McInallyc3167692019-05-06 16:05:10 +00004554/// Given the operand for a UnaryOperator, see if we can fold the result.
4555/// If not, this returns null.
4556static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
4557 unsigned MaxRecurse) {
4558 switch (Opcode) {
4559 case Instruction::FNeg:
4560 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
4561 default:
4562 llvm_unreachable("Unexpected opcode");
4563 }
4564}
4565
4566/// Given the operand for a UnaryOperator, see if we can fold the result.
4567/// If not, this returns null.
4568/// In contrast to SimplifyUnOp, try to use FastMathFlag when folding the
4569/// result. In case we don't need FastMathFlags, simply fall to SimplifyUnOp.
4570static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
4571 const FastMathFlags &FMF,
4572 const SimplifyQuery &Q, unsigned MaxRecurse) {
4573 switch (Opcode) {
4574 case Instruction::FNeg:
4575 return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
4576 default:
4577 return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
4578 }
4579}
4580
4581Value *llvm::SimplifyFPUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
4582 const SimplifyQuery &Q) {
4583 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
4584}
4585
Sanjay Patel472cc782016-01-11 22:14:42 +00004586/// Given operands for a BinaryOperator, see if we can fold the result.
4587/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004588static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004589 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004590 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004591 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004592 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004593 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004594 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004595 case Instruction::Mul:
4596 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004597 case Instruction::SDiv:
4598 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4599 case Instruction::UDiv:
4600 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004601 case Instruction::SRem:
4602 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4603 case Instruction::URem:
4604 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004605 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004606 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004607 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004608 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004609 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004610 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4611 case Instruction::And:
4612 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4613 case Instruction::Or:
4614 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4615 case Instruction::Xor:
4616 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004617 case Instruction::FAdd:
4618 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4619 case Instruction::FSub:
4620 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4621 case Instruction::FMul:
4622 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4623 case Instruction::FDiv:
4624 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4625 case Instruction::FRem:
4626 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004627 default:
Craig Topper8ef20ea2017-04-06 18:59:08 +00004628 llvm_unreachable("Unexpected opcode");
Chris Lattnera71e9d62009-11-10 00:55:12 +00004629 }
4630}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004631
Sanjay Patel472cc782016-01-11 22:14:42 +00004632/// Given operands for a BinaryOperator, see if we can fold the result.
4633/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004634/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4635/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4636static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004637 const FastMathFlags &FMF, const SimplifyQuery &Q,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004638 unsigned MaxRecurse) {
4639 switch (Opcode) {
4640 case Instruction::FAdd:
4641 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4642 case Instruction::FSub:
4643 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4644 case Instruction::FMul:
4645 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004646 case Instruction::FDiv:
4647 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004648 default:
4649 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4650 }
4651}
4652
Duncan Sands7e800d62010-11-14 11:23:23 +00004653Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004654 const SimplifyQuery &Q) {
4655 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4656}
4657
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004658Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berline8d74dc2017-04-26 04:10:00 +00004659 FastMathFlags FMF, const SimplifyQuery &Q) {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004660 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4661}
4662
Sanjay Patel472cc782016-01-11 22:14:42 +00004663/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004664static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004665 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004666 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004667 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004668 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004669}
4670
4671Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004672 const SimplifyQuery &Q) {
4673 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4674}
4675
Michael Ilseman54857292013-02-07 19:26:05 +00004676static bool IsIdempotent(Intrinsic::ID ID) {
4677 switch (ID) {
4678 default: return false;
4679
4680 // Unary idempotent: f(f(x)) = f(x)
4681 case Intrinsic::fabs:
4682 case Intrinsic::floor:
4683 case Intrinsic::ceil:
4684 case Intrinsic::trunc:
4685 case Intrinsic::rint:
4686 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004687 case Intrinsic::round:
Matt Arsenault3ced3d92017-09-07 01:21:43 +00004688 case Intrinsic::canonicalize:
Michael Ilseman54857292013-02-07 19:26:05 +00004689 return true;
4690 }
4691}
4692
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004693static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4694 const DataLayout &DL) {
4695 GlobalValue *PtrSym;
4696 APInt PtrOffset;
4697 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4698 return nullptr;
4699
4700 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4701 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4702 Type *Int32PtrTy = Int32Ty->getPointerTo();
4703 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4704
4705 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4706 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4707 return nullptr;
4708
4709 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4710 if (OffsetInt % 4 != 0)
4711 return nullptr;
4712
4713 Constant *C = ConstantExpr::getGetElementPtr(
4714 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4715 ConstantInt::get(Int64Ty, OffsetInt / 4));
4716 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4717 if (!Loaded)
4718 return nullptr;
4719
4720 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4721 if (!LoadedCE)
4722 return nullptr;
4723
4724 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4725 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4726 if (!LoadedCE)
4727 return nullptr;
4728 }
4729
4730 if (LoadedCE->getOpcode() != Instruction::Sub)
4731 return nullptr;
4732
4733 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4734 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4735 return nullptr;
4736 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4737
4738 Constant *LoadedRHS = LoadedCE->getOperand(1);
4739 GlobalValue *LoadedRHSSym;
4740 APInt LoadedRHSOffset;
4741 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4742 DL) ||
4743 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4744 return nullptr;
4745
4746 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4747}
4748
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004749static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4750 const SimplifyQuery &Q) {
4751 // Idempotent functions return the same result when called repeatedly.
David Majnemer15032582015-05-22 03:56:46 +00004752 Intrinsic::ID IID = F->getIntrinsicID();
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004753 if (IsIdempotent(IID))
4754 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4755 if (II->getIntrinsicID() == IID)
4756 return II;
Michael Ilseman54857292013-02-07 19:26:05 +00004757
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004758 Value *X;
4759 switch (IID) {
4760 case Intrinsic::fabs:
4761 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4762 break;
4763 case Intrinsic::bswap:
4764 // bswap(bswap(x)) -> x
4765 if (match(Op0, m_BSwap(m_Value(X)))) return X;
4766 break;
4767 case Intrinsic::bitreverse:
4768 // bitreverse(bitreverse(x)) -> x
4769 if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4770 break;
4771 case Intrinsic::exp:
4772 // exp(log(x)) -> x
4773 if (Q.CxtI->hasAllowReassoc() &&
4774 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4775 break;
4776 case Intrinsic::exp2:
4777 // exp2(log2(x)) -> x
4778 if (Q.CxtI->hasAllowReassoc() &&
4779 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4780 break;
4781 case Intrinsic::log:
4782 // log(exp(x)) -> x
4783 if (Q.CxtI->hasAllowReassoc() &&
4784 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4785 break;
4786 case Intrinsic::log2:
4787 // log2(exp2(x)) -> x
4788 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikovaaa709f2019-02-03 03:48:30 +00004789 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4790 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4791 m_Value(X))))) return X;
4792 break;
4793 case Intrinsic::log10:
4794 // log10(pow(10.0, x)) -> x
4795 if (Q.CxtI->hasAllowReassoc() &&
4796 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4797 m_Value(X)))) return X;
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004798 break;
Matt Arsenault03e749282019-04-03 00:25:06 +00004799 case Intrinsic::floor:
4800 case Intrinsic::trunc:
4801 case Intrinsic::ceil:
4802 case Intrinsic::round:
4803 case Intrinsic::nearbyint:
4804 case Intrinsic::rint: {
4805 // floor (sitofp x) -> sitofp x
4806 // floor (uitofp x) -> uitofp x
4807 //
4808 // Converting from int always results in a finite integral number or
4809 // infinity. For either of those inputs, these rounding functions always
4810 // return the same value, so the rounding can be eliminated.
4811 if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
4812 return Op0;
4813 break;
4814 }
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004815 default:
4816 break;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004817 }
Michael Ilseman54857292013-02-07 19:26:05 +00004818
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004819 return nullptr;
4820}
Matt Arsenault82606662017-01-11 00:57:54 +00004821
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004822static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
4823 const SimplifyQuery &Q) {
4824 Intrinsic::ID IID = F->getIntrinsicID();
4825 Type *ReturnType = F->getReturnType();
4826 switch (IID) {
4827 case Intrinsic::usub_with_overflow:
4828 case Intrinsic::ssub_with_overflow:
4829 // X - X -> { 0, false }
4830 if (Op0 == Op1)
4831 return Constant::getNullValue(ReturnType);
4832 // X - undef -> undef
4833 // undef - X -> undef
4834 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4835 return UndefValue::get(ReturnType);
4836 break;
4837 case Intrinsic::uadd_with_overflow:
4838 case Intrinsic::sadd_with_overflow:
4839 // X + undef -> undef
4840 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4841 return UndefValue::get(ReturnType);
4842 break;
4843 case Intrinsic::umul_with_overflow:
4844 case Intrinsic::smul_with_overflow:
4845 // 0 * X -> { 0, false }
4846 // X * 0 -> { 0, false }
4847 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
4848 return Constant::getNullValue(ReturnType);
4849 // undef * X -> { 0, false }
4850 // X * undef -> { 0, false }
4851 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4852 return Constant::getNullValue(ReturnType);
4853 break;
Sanjay Pateleea21da2018-11-20 17:20:26 +00004854 case Intrinsic::uadd_sat:
4855 // sat(MAX + X) -> MAX
4856 // sat(X + MAX) -> MAX
4857 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
4858 return Constant::getAllOnesValue(ReturnType);
4859 LLVM_FALLTHROUGH;
4860 case Intrinsic::sadd_sat:
4861 // sat(X + undef) -> -1
4862 // sat(undef + X) -> -1
4863 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
4864 // For signed: Assume undef is ~X, in which case X + ~X = -1.
4865 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4866 return Constant::getAllOnesValue(ReturnType);
4867
4868 // X + 0 -> X
4869 if (match(Op1, m_Zero()))
4870 return Op0;
4871 // 0 + X -> X
4872 if (match(Op0, m_Zero()))
4873 return Op1;
4874 break;
4875 case Intrinsic::usub_sat:
4876 // sat(0 - X) -> 0, sat(X - MAX) -> 0
4877 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
4878 return Constant::getNullValue(ReturnType);
4879 LLVM_FALLTHROUGH;
4880 case Intrinsic::ssub_sat:
4881 // X - X -> 0, X - undef -> 0, undef - X -> 0
4882 if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
4883 return Constant::getNullValue(ReturnType);
4884 // X - 0 -> X
4885 if (match(Op1, m_Zero()))
4886 return Op0;
4887 break;
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004888 case Intrinsic::load_relative:
4889 if (auto *C0 = dyn_cast<Constant>(Op0))
4890 if (auto *C1 = dyn_cast<Constant>(Op1))
Matt Arsenault82606662017-01-11 00:57:54 +00004891 return SimplifyRelativeLoad(C0, C1, Q.DL);
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004892 break;
4893 case Intrinsic::powi:
4894 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
4895 // powi(x, 0) -> 1.0
4896 if (Power->isZero())
4897 return ConstantFP::get(Op0->getType(), 1.0);
4898 // powi(x, 1) -> x
4899 if (Power->isOne())
4900 return Op0;
Matt Arsenault82606662017-01-11 00:57:54 +00004901 }
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004902 break;
4903 case Intrinsic::maxnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00004904 case Intrinsic::minnum:
4905 case Intrinsic::maximum:
4906 case Intrinsic::minimum: {
Sanjay Patel28c7e412018-08-01 23:05:55 +00004907 // If the arguments are the same, this is a no-op.
4908 if (Op0 == Op1) return Op0;
4909
Thomas Livelyc3392502018-10-19 19:01:26 +00004910 // If one argument is undef, return the other argument.
4911 if (match(Op0, m_Undef()))
4912 return Op1;
4913 if (match(Op1, m_Undef()))
4914 return Op0;
4915
4916 // If one argument is NaN, return other or NaN appropriately.
4917 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
4918 if (match(Op0, m_NaN()))
4919 return PropagateNaN ? Op0 : Op1;
4920 if (match(Op1, m_NaN()))
4921 return PropagateNaN ? Op1 : Op0;
Sanjay Patel3f6e9a72018-08-02 14:33:40 +00004922
Sanjay Patel948ff872018-08-07 14:36:27 +00004923 // Min/max of the same operation with common operand:
4924 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
4925 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
4926 if (M0->getIntrinsicID() == IID &&
4927 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
4928 return Op0;
4929 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
4930 if (M1->getIntrinsicID() == IID &&
4931 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
4932 return Op1;
4933
Thomas Livelyc3392502018-10-19 19:01:26 +00004934 // min(X, -Inf) --> -Inf (and commuted variant)
4935 // max(X, +Inf) --> +Inf (and commuted variant)
4936 bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
Sanjay Patelc6944f72018-08-09 22:20:44 +00004937 const APFloat *C;
4938 if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
4939 C->isNegative() == UseNegInf) ||
4940 (match(Op1, m_APFloat(C)) && C->isInfinity() &&
4941 C->isNegative() == UseNegInf))
4942 return ConstantFP::getInfinity(ReturnType, UseNegInf);
4943
4944 // TODO: minnum(nnan x, inf) -> x
4945 // TODO: minnum(nnan ninf x, flt_max) -> x
4946 // TODO: maxnum(nnan x, -inf) -> x
4947 // TODO: maxnum(nnan ninf x, -flt_max) -> x
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004948 break;
Sanjay Patelc6944f72018-08-09 22:20:44 +00004949 }
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004950 default:
4951 break;
Matt Arsenault82606662017-01-11 00:57:54 +00004952 }
4953
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004954 return nullptr;
4955}
4956
4957template <typename IterTy>
4958static Value *simplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
4959 const SimplifyQuery &Q) {
4960 // Intrinsics with no operands have some kind of side effect. Don't simplify.
4961 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4962 if (NumOperands == 0)
4963 return nullptr;
4964
4965 Intrinsic::ID IID = F->getIntrinsicID();
4966 if (NumOperands == 1)
4967 return simplifyUnaryIntrinsic(F, ArgBegin[0], Q);
4968
4969 if (NumOperands == 2)
4970 return simplifyBinaryIntrinsic(F, ArgBegin[0], ArgBegin[1], Q);
4971
4972 // Handle intrinsics with 3 or more arguments.
Matt Arsenault82606662017-01-11 00:57:54 +00004973 switch (IID) {
Philip Reamesd8d9b7b2019-04-22 19:30:01 +00004974 case Intrinsic::masked_load:
4975 case Intrinsic::masked_gather: {
Matt Arsenault82606662017-01-11 00:57:54 +00004976 Value *MaskArg = ArgBegin[2];
4977 Value *PassthruArg = ArgBegin[3];
4978 // If the mask is all zeros or undef, the "passthru" argument is the result.
4979 if (maskIsAllZeroOrUndef(MaskArg))
4980 return PassthruArg;
4981 return nullptr;
4982 }
Sanjay Patel54421ce2018-07-29 16:36:38 +00004983 case Intrinsic::fshl:
4984 case Intrinsic::fshr: {
Sanjay Patel14ab9172018-11-20 17:34:59 +00004985 Value *Op0 = ArgBegin[0], *Op1 = ArgBegin[1], *ShAmtArg = ArgBegin[2];
4986
4987 // If both operands are undef, the result is undef.
4988 if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
4989 return UndefValue::get(F->getReturnType());
4990
4991 // If shift amount is undef, assume it is zero.
4992 if (match(ShAmtArg, m_Undef()))
4993 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
4994
Sanjay Patel54421ce2018-07-29 16:36:38 +00004995 const APInt *ShAmtC;
4996 if (match(ShAmtArg, m_APInt(ShAmtC))) {
4997 // If there's effectively no shift, return the 1st arg or 2nd arg.
Sanjay Patel54421ce2018-07-29 16:36:38 +00004998 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
4999 if (ShAmtC->urem(BitWidth).isNullValue())
5000 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
5001 }
5002 return nullptr;
5003 }
Matt Arsenault82606662017-01-11 00:57:54 +00005004 default:
5005 return nullptr;
5006 }
Michael Ilseman54857292013-02-07 19:26:05 +00005007}
5008
Chandler Carruth9dc35582012-12-28 11:30:55 +00005009template <typename IterTy>
Chandler Carruthdac20a82019-02-11 07:54:10 +00005010static Value *SimplifyCall(CallBase *Call, Value *V, IterTy ArgBegin,
Andrew Kaylor647025f2017-06-09 23:18:11 +00005011 IterTy ArgEnd, const SimplifyQuery &Q,
5012 unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00005013 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00005014 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
5015 Ty = PTy->getElementType();
5016 FunctionType *FTy = cast<FunctionType>(Ty);
5017
Dan Gohman85977e62011-11-04 18:32:42 +00005018 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00005019 // call null -> undef
5020 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00005021 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00005022
Chandler Carruthf6182152012-12-28 14:23:29 +00005023 Function *F = dyn_cast<Function>(V);
5024 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00005025 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005026
David Majnemer15032582015-05-22 03:56:46 +00005027 if (F->isIntrinsic())
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005028 if (Value *Ret = simplifyIntrinsic(F, ArgBegin, ArgEnd, Q))
Michael Ilseman54857292013-02-07 19:26:05 +00005029 return Ret;
5030
Chandler Carruthdac20a82019-02-11 07:54:10 +00005031 if (!canConstantFoldCallTo(Call, F))
Craig Topper9f008862014-04-15 04:59:12 +00005032 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005033
5034 SmallVector<Constant *, 4> ConstantArgs;
5035 ConstantArgs.reserve(ArgEnd - ArgBegin);
5036 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
5037 Constant *C = dyn_cast<Constant>(*I);
5038 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00005039 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005040 ConstantArgs.push_back(C);
5041 }
5042
Chandler Carruthdac20a82019-02-11 07:54:10 +00005043 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00005044}
5045
Chandler Carruthdac20a82019-02-11 07:54:10 +00005046Value *llvm::SimplifyCall(CallBase *Call, Value *V, User::op_iterator ArgBegin,
5047 User::op_iterator ArgEnd, const SimplifyQuery &Q) {
5048 return ::SimplifyCall(Call, V, ArgBegin, ArgEnd, Q, RecursionLimit);
5049}
5050
5051Value *llvm::SimplifyCall(CallBase *Call, Value *V, ArrayRef<Value *> Args,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005052 const SimplifyQuery &Q) {
Chandler Carruthdac20a82019-02-11 07:54:10 +00005053 return ::SimplifyCall(Call, V, Args.begin(), Args.end(), Q, RecursionLimit);
Andrew Kaylor647025f2017-06-09 23:18:11 +00005054}
5055
Chandler Carruthdac20a82019-02-11 07:54:10 +00005056Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5057 return ::SimplifyCall(Call, Call->getCalledValue(), Call->arg_begin(),
5058 Call->arg_end(), Q, RecursionLimit);
Philip Reames7a6db4f2017-12-27 00:16:12 +00005059}
5060
Sanjay Patel472cc782016-01-11 22:14:42 +00005061/// See if we can compute a simplified version of this instruction.
5062/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005063
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005064Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005065 OptimizationRemarkEmitter *ORE) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005066 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005067 Value *Result;
5068
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005069 switch (I->getOpcode()) {
5070 default:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005071 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005072 break;
Cameron McInallyc3167692019-05-06 16:05:10 +00005073 case Instruction::FNeg:
5074 Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q);
5075 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005076 case Instruction::FAdd:
5077 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005078 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005079 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00005080 case Instruction::Add:
Florian Hahn19f9e322018-08-17 14:39:04 +00005081 Result =
5082 SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5083 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5084 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005085 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005086 case Instruction::FSub:
5087 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005088 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005089 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00005090 case Instruction::Sub:
Florian Hahn19f9e322018-08-17 14:39:04 +00005091 Result =
5092 SimplifySubInst(I->getOperand(0), I->getOperand(1),
5093 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5094 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands0a2c41682010-12-15 14:07:39 +00005095 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00005096 case Instruction::FMul:
5097 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005098 I->getFastMathFlags(), Q);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00005099 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00005100 case Instruction::Mul:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005101 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00005102 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00005103 case Instruction::SDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005104 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00005105 break;
5106 case Instruction::UDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005107 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00005108 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00005109 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00005110 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005111 I->getFastMathFlags(), Q);
Frits van Bommelc2549662011-01-29 15:26:31 +00005112 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00005113 case Instruction::SRem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005114 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005115 break;
5116 case Instruction::URem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005117 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005118 break;
5119 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00005120 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005121 I->getFastMathFlags(), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005122 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00005123 case Instruction::Shl:
Florian Hahn19f9e322018-08-17 14:39:04 +00005124 Result =
5125 SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5126 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5127 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005128 break;
5129 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00005130 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Florian Hahn19f9e322018-08-17 14:39:04 +00005131 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005132 break;
5133 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00005134 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Florian Hahn19f9e322018-08-17 14:39:04 +00005135 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005136 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005137 case Instruction::And:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005138 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005139 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005140 case Instruction::Or:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005141 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005142 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00005143 case Instruction::Xor:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005144 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsc89ac072010-11-17 18:52:15 +00005145 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005146 case Instruction::ICmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005147 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5148 I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005149 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005150 case Instruction::FCmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005151 Result =
5152 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5153 I->getOperand(1), I->getFastMathFlags(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005154 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00005155 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00005156 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005157 I->getOperand(2), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005158 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00005159 case Instruction::GetElementPtr: {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005160 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00005161 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005162 Ops, Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005163 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00005164 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00005165 case Instruction::InsertValue: {
5166 InsertValueInst *IV = cast<InsertValueInst>(I);
5167 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5168 IV->getInsertedValueOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005169 IV->getIndices(), Q);
Duncan Sandsfd26a952011-09-05 06:52:48 +00005170 break;
5171 }
Igor Laevskye0edb662017-12-13 11:21:18 +00005172 case Instruction::InsertElement: {
5173 auto *IE = cast<InsertElementInst>(I);
5174 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5175 IE->getOperand(2), Q);
5176 break;
5177 }
David Majnemer25a796e2015-07-13 01:15:46 +00005178 case Instruction::ExtractValue: {
5179 auto *EVI = cast<ExtractValueInst>(I);
5180 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005181 EVI->getIndices(), Q);
David Majnemer25a796e2015-07-13 01:15:46 +00005182 break;
5183 }
David Majnemer599ca442015-07-13 01:15:53 +00005184 case Instruction::ExtractElement: {
5185 auto *EEI = cast<ExtractElementInst>(I);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005186 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5187 EEI->getIndexOperand(), Q);
David Majnemer599ca442015-07-13 01:15:53 +00005188 break;
5189 }
Zvi Rackover8f460652017-04-03 22:05:30 +00005190 case Instruction::ShuffleVector: {
5191 auto *SVI = cast<ShuffleVectorInst>(I);
5192 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005193 SVI->getMask(), SVI->getType(), Q);
Zvi Rackover8f460652017-04-03 22:05:30 +00005194 break;
5195 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00005196 case Instruction::PHI:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005197 Result = SimplifyPHINode(cast<PHINode>(I), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005198 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00005199 case Instruction::Call: {
Chandler Carruthdac20a82019-02-11 07:54:10 +00005200 Result = SimplifyCall(cast<CallInst>(I), Q);
Dan Gohman85977e62011-11-04 18:32:42 +00005201 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00005202 }
David Majnemer6774d612016-07-26 17:58:05 +00005203#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5204#include "llvm/IR/Instruction.def"
5205#undef HANDLE_CAST_INST
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005206 Result =
5207 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
David Majnemera90a6212016-07-26 05:52:29 +00005208 break;
Craig Topper81c03a72017-04-12 22:54:24 +00005209 case Instruction::Alloca:
5210 // No simplifications for Alloca and it can't be constant folded.
5211 Result = nullptr;
5212 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005213 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00005214
Hal Finkelf2199b22015-10-23 20:37:08 +00005215 // In general, it is possible for computeKnownBits to determine all bits in a
5216 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00005217 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00005218 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
Craig Topper8189a872017-05-03 23:12:29 +00005219 if (Known.isConstant())
5220 Result = ConstantInt::get(I->getType(), Known.getConstant());
Hal Finkelf2199b22015-10-23 20:37:08 +00005221 }
5222
Duncan Sands64e41cf2010-11-17 08:35:29 +00005223 /// If called on unreachable code, the above logic may report that the
5224 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00005225 /// detecting that case here, returning a safe value instead.
5226 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005227}
5228
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005229/// Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005230/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00005231///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005232/// This is the common implementation of the recursive simplification routines.
5233/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5234/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5235/// instructions to process and attempt to simplify it using
5236/// InstructionSimplify.
5237///
5238/// This routine returns 'true' only when *it* simplifies something. The passed
5239/// in simplified value does not count toward this.
5240static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005241 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005242 const DominatorTree *DT,
5243 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005244 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005245 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005246 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00005247
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005248 // If we have an explicit value to collapse to, do that round of the
5249 // simplification loop by hand initially.
5250 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005251 for (User *U : I->users())
5252 if (U != I)
5253 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00005254
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005255 // Replace the instruction with its simplified value.
5256 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00005257
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005258 // Gracefully handle edge cases where the instruction is not wired into any
5259 // parent block.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005260 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
David Majnemer909793f2016-08-04 04:24:02 +00005261 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005262 I->eraseFromParent();
5263 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005264 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00005265 }
Duncan Sands7e800d62010-11-14 11:23:23 +00005266
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005267 // Note that we must test the size on each iteration, the worklist can grow.
5268 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5269 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00005270
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005271 // See if this instruction simplifies.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005272 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005273 if (!SimpleV)
5274 continue;
5275
5276 Simplified = true;
5277
5278 // Stash away all the uses of the old instruction so we can check them for
5279 // recursive simplifications after a RAUW. This is cheaper than checking all
5280 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005281 for (User *U : I->users())
5282 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005283
5284 // Replace the instruction with its simplified value.
5285 I->replaceAllUsesWith(SimpleV);
5286
5287 // Gracefully handle edge cases where the instruction is not wired into any
5288 // parent block.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005289 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
David Majnemer909793f2016-08-04 04:24:02 +00005290 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005291 I->eraseFromParent();
5292 }
5293 return Simplified;
5294}
5295
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005296bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005297 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005298 const DominatorTree *DT,
5299 AssumptionCache *AC) {
5300 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005301}
5302
5303bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005304 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005305 const DominatorTree *DT,
5306 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005307 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5308 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005309 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00005310}
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005311
5312namespace llvm {
5313const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5314 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5315 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5316 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5317 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5318 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5319 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5320 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5321}
5322
5323const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5324 const DataLayout &DL) {
5325 return {DL, &AR.TLI, &AR.DT, &AR.AC};
5326}
5327
5328template <class T, class... TArgs>
5329const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5330 Function &F) {
5331 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5332 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5333 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5334 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5335}
5336template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5337 Function &);
5338}