blob: ed857ddbc78b706a22569b55c4cca0bce87bc8ba [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);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000055 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000056static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000057 const SimplifyQuery &, unsigned);
58static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000059 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000060static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000061 const SimplifyQuery &Q, unsigned MaxRecurse);
62static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
63static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000064static Value *SimplifyCastInst(unsigned, Value *, Type *,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000065 const SimplifyQuery &, unsigned);
George Burgess IV8e807bf2018-04-24 00:25:01 +000066static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
67 unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000068
David Bolvanskyf9476082018-07-28 06:55:51 +000069static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
70 Value *FalseVal) {
71 BinaryOperator::BinaryOps BinOpCode;
72 if (auto *BO = dyn_cast<BinaryOperator>(Cond))
73 BinOpCode = BO->getOpcode();
74 else
75 return nullptr;
76
David Bolvansky16d8a692018-07-31 14:17:15 +000077 CmpInst::Predicate ExpectedPred, Pred1, Pred2;
David Bolvanskyf9476082018-07-28 06:55:51 +000078 if (BinOpCode == BinaryOperator::Or) {
79 ExpectedPred = ICmpInst::ICMP_NE;
80 } else if (BinOpCode == BinaryOperator::And) {
81 ExpectedPred = ICmpInst::ICMP_EQ;
82 } else
83 return nullptr;
84
David Bolvansky16d8a692018-07-31 14:17:15 +000085 // %A = icmp eq %TV, %FV
86 // %B = icmp eq %X, %Y (and one of these is a select operand)
87 // %C = and %A, %B
88 // %D = select %C, %TV, %FV
89 // -->
90 // %FV
91
92 // %A = icmp ne %TV, %FV
93 // %B = icmp ne %X, %Y (and one of these is a select operand)
94 // %C = or %A, %B
95 // %D = select %C, %TV, %FV
96 // -->
97 // %TV
98 Value *X, *Y;
99 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
100 m_Specific(FalseVal)),
101 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
David Bolvanskyf9476082018-07-28 06:55:51 +0000102 Pred1 != Pred2 || Pred1 != ExpectedPred)
103 return nullptr;
104
David Bolvansky16d8a692018-07-31 14:17:15 +0000105 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
106 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
107
108 return nullptr;
David Bolvanskyf9476082018-07-28 06:55:51 +0000109}
110
Sanjay Patel35ed2412017-04-16 17:43:11 +0000111/// For a boolean type or a vector of boolean type, return false or a vector
112/// with every element false.
Duncan Sandsc1c92712011-07-26 15:03:53 +0000113static Constant *getFalse(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +0000114 return ConstantInt::getFalse(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +0000115}
116
Sanjay Patel35ed2412017-04-16 17:43:11 +0000117/// For a boolean type or a vector of boolean type, return true or a vector
118/// with every element true.
Duncan Sandsc1c92712011-07-26 15:03:53 +0000119static Constant *getTrue(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +0000120 return ConstantInt::getTrue(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +0000121}
122
Duncan Sands3d5692a2011-10-30 19:56:36 +0000123/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
124static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
125 Value *RHS) {
126 CmpInst *Cmp = dyn_cast<CmpInst>(V);
127 if (!Cmp)
128 return false;
129 CmpInst::Predicate CPred = Cmp->getPredicate();
130 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
131 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
132 return true;
133 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
134 CRHS == LHS;
135}
136
Sanjay Patel472cc782016-01-11 22:14:42 +0000137/// Does the given value dominate the specified phi node?
Sanjay Patel5da361a2018-04-10 18:38:19 +0000138static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
Duncan Sands5ffc2982010-11-16 12:16:38 +0000139 Instruction *I = dyn_cast<Instruction>(V);
140 if (!I)
141 // Arguments and constants dominate all instructions.
142 return true;
143
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000144 // If we are processing instructions (and/or basic blocks) that have not been
145 // fully added to a function, the parent nodes may still be null. Simply
146 // return the conservative answer in these cases.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000147 if (!I->getParent() || !P->getParent() || !I->getFunction())
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000148 return false;
149
Duncan Sands5ffc2982010-11-16 12:16:38 +0000150 // If we have a DominatorTree then do a precise test.
Daniel Berlin71ff6632017-05-31 01:47:24 +0000151 if (DT)
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000152 return DT->dominates(I, P);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000153
David Majnemer8a1c45d2015-12-12 05:38:55 +0000154 // Otherwise, if the instruction is in the entry block and is not an invoke,
155 // then it obviously dominates all phi nodes.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000156 if (I->getParent() == &I->getFunction()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000157 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000158 return true;
159
160 return false;
161}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000162
Sanjay Patel472cc782016-01-11 22:14:42 +0000163/// Simplify "A op (B op' C)" by distributing op over op', turning it into
164/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000165/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
166/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
167/// Returns the simplified value, or null if no simplification was performed.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000168static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
Craig Topper9c913bf2017-05-19 16:56:53 +0000169 Instruction::BinaryOps OpcodeToExpand,
170 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000171 // Recursion is always used, so bail out at once if we already hit the limit.
172 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000173 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000174
175 // Check whether the expression has the form "(A op' B) op C".
176 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
177 if (Op0->getOpcode() == OpcodeToExpand) {
178 // It does! Try turning it into "(A op C) op' (B op C)".
179 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
180 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000181 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
182 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 // They do! Return "L op' R" if it simplifies or is already available.
184 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000185 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
186 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000187 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000188 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000191 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000192 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000193 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000194 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000195 }
196 }
197
198 // Check whether the expression has the form "A op (B op' C)".
199 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
200 if (Op1->getOpcode() == OpcodeToExpand) {
201 // It does! Try turning it into "(A op B) op' (A op C)".
202 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
203 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000204 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
205 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000206 // They do! Return "L op' R" if it simplifies or is already available.
207 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000208 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
209 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000210 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000211 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000212 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000213 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000214 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000215 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000216 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000217 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000218 }
219 }
220
Craig Topper9f008862014-04-15 04:59:12 +0000221 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000222}
223
Sanjay Patel472cc782016-01-11 22:14:42 +0000224/// Generic simplifications for associative binary operations.
225/// Returns the simpler value, or null if none was found.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000226static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
Craig Topper9c913bf2017-05-19 16:56:53 +0000227 Value *LHS, Value *RHS,
228 const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000229 unsigned MaxRecurse) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000230 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
231
232 // Recursion is always used, so bail out at once if we already hit the limit.
233 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000234 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000235
236 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
237 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
238
239 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
240 if (Op0 && Op0->getOpcode() == Opcode) {
241 Value *A = Op0->getOperand(0);
242 Value *B = Op0->getOperand(1);
243 Value *C = RHS;
244
245 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000246 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000247 // It does! Return "A op V" if it simplifies or is already available.
248 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000249 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000250 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000251 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000252 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000253 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000254 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000255 }
256 }
257
258 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
259 if (Op1 && Op1->getOpcode() == Opcode) {
260 Value *A = LHS;
261 Value *B = Op1->getOperand(0);
262 Value *C = Op1->getOperand(1);
263
264 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000265 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000266 // It does! Return "V op C" if it simplifies or is already available.
267 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000268 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000269 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000270 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000271 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000272 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000273 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000274 }
275 }
276
277 // The remaining transforms require commutativity as well as associativity.
278 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000279 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280
281 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
282 if (Op0 && Op0->getOpcode() == Opcode) {
283 Value *A = Op0->getOperand(0);
284 Value *B = Op0->getOperand(1);
285 Value *C = RHS;
286
287 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000288 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000289 // It does! Return "V op B" if it simplifies or is already available.
290 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000291 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000293 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000294 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000295 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000296 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000297 }
298 }
299
300 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
301 if (Op1 && Op1->getOpcode() == Opcode) {
302 Value *A = LHS;
303 Value *B = Op1->getOperand(0);
304 Value *C = Op1->getOperand(1);
305
306 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000307 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000308 // It does! Return "B op V" if it simplifies or is already available.
309 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000310 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000311 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000312 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000313 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000314 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000315 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000316 }
317 }
318
Craig Topper9f008862014-04-15 04:59:12 +0000319 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000320}
321
Sanjay Patel472cc782016-01-11 22:14:42 +0000322/// In the case of a binary operation with a select instruction as an operand,
323/// try to simplify the binop by seeing whether evaluating it on both branches
324/// of the select results in the same value. Returns the common value if so,
325/// otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000326static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000327 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000328 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000329 // Recursion is always used, so bail out at once if we already hit the limit.
330 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000331 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000332
Duncan Sandsb0579e92010-11-10 13:00:08 +0000333 SelectInst *SI;
334 if (isa<SelectInst>(LHS)) {
335 SI = cast<SelectInst>(LHS);
336 } else {
337 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
338 SI = cast<SelectInst>(RHS);
339 }
340
341 // Evaluate the BinOp on the true and false branches of the select.
342 Value *TV;
343 Value *FV;
344 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000345 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
346 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000347 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000348 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
349 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000350 }
351
Duncan Sandse3c53952011-01-01 16:12:09 +0000352 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000353 // If they both failed to simplify then return null.
354 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355 return TV;
356
357 // If one branch simplified to undef, return the other one.
358 if (TV && isa<UndefValue>(TV))
359 return FV;
360 if (FV && isa<UndefValue>(FV))
361 return TV;
362
363 // If applying the operation did not change the true and false select values,
364 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000365 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000366 return SI;
367
368 // If one branch simplified and the other did not, and the simplified
369 // value is equal to the unsimplified one, return the simplified value.
370 // For example, select (cond, X, X & Z) & Z -> X & Z.
371 if ((FV && !TV) || (TV && !FV)) {
372 // Check that the simplified value has the form "X op Y" where "op" is the
373 // same as the original operation.
374 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
Zachary Turner260fe3e2017-12-14 22:07:03 +0000375 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
Duncan Sandsb0579e92010-11-10 13:00:08 +0000376 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
377 // We already know that "op" is the same as for the simplified value. See
378 // if the operands match too. If so, return the simplified value.
379 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
380 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
381 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000382 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
383 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000384 return Simplified;
385 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000386 Simplified->getOperand(1) == UnsimplifiedLHS &&
387 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000388 return Simplified;
389 }
390 }
391
Craig Topper9f008862014-04-15 04:59:12 +0000392 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000393}
394
Sanjay Patel472cc782016-01-11 22:14:42 +0000395/// In the case of a comparison with a select instruction, try to simplify the
396/// comparison by seeing whether both branches of the select result in the same
397/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000398static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000399 Value *RHS, const SimplifyQuery &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000400 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000401 // Recursion is always used, so bail out at once if we already hit the limit.
402 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000403 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000404
Duncan Sandsb0579e92010-11-10 13:00:08 +0000405 // Make sure the select is on the LHS.
406 if (!isa<SelectInst>(LHS)) {
407 std::swap(LHS, RHS);
408 Pred = CmpInst::getSwappedPredicate(Pred);
409 }
410 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
411 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000412 Value *Cond = SI->getCondition();
413 Value *TV = SI->getTrueValue();
414 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000415
Duncan Sands06504022011-02-03 09:37:39 +0000416 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000417 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000418 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000419 if (TCmp == Cond) {
420 // It not only simplified, it simplified to the select condition. Replace
421 // it with 'true'.
422 TCmp = getTrue(Cond->getType());
423 } else if (!TCmp) {
424 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
425 // condition then we can replace it with 'true'. Otherwise give up.
426 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000427 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000429 }
430
Duncan Sands3d5692a2011-10-30 19:56:36 +0000431 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000432 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000433 if (FCmp == Cond) {
434 // It not only simplified, it simplified to the select condition. Replace
435 // it with 'false'.
436 FCmp = getFalse(Cond->getType());
437 } else if (!FCmp) {
438 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
439 // condition then we can replace it with 'false'. Otherwise give up.
440 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000441 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000442 FCmp = getFalse(Cond->getType());
443 }
444
445 // If both sides simplified to the same value, then use it as the result of
446 // the original comparison.
447 if (TCmp == FCmp)
448 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000449
450 // The remaining cases only make sense if the select condition has the same
451 // type as the result of the comparison, so bail out if this is not so.
452 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000453 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000454 // If the false value simplified to false, then the result of the compare
455 // is equal to "Cond && TCmp". This also catches the case when the false
456 // value simplified to false and the true value to true, returning "Cond".
457 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000458 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000459 return V;
460 // If the true value simplified to true, then the result of the compare
461 // is equal to "Cond || FCmp".
462 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000463 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000464 return V;
465 // Finally, if the false value simplified to true and the true value to
466 // false, then the result of the compare is equal to "!Cond".
467 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
468 if (Value *V =
469 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000470 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000471 return V;
472
Craig Topper9f008862014-04-15 04:59:12 +0000473 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000474}
475
Sanjay Patel472cc782016-01-11 22:14:42 +0000476/// In the case of a binary operation with an operand that is a PHI instruction,
477/// try to simplify the binop by seeing whether evaluating it on the incoming
478/// phi values yields the same result for every value. If so returns the common
479/// value, otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000480static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000481 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000482 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000483 // Recursion is always used, so bail out at once if we already hit the limit.
484 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000485 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000486
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000487 PHINode *PI;
488 if (isa<PHINode>(LHS)) {
489 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000490 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000491 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000492 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000493 } else {
494 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
495 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000496 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000497 if (!valueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000498 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000499 }
500
501 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000502 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000503 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000504 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000505 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000506 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000507 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
508 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000509 // If the operation failed to simplify, or simplified to a different value
510 // to previously, then give up.
511 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000512 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000513 CommonValue = V;
514 }
515
516 return CommonValue;
517}
518
Sanjay Patel472cc782016-01-11 22:14:42 +0000519/// In the case of a comparison with a PHI instruction, try to simplify the
520/// comparison by seeing whether comparing with all of the incoming phi values
521/// yields the same result every time. If so returns the common result,
522/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000523static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000524 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000525 // Recursion is always used, so bail out at once if we already hit the limit.
526 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000527 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000528
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000529 // Make sure the phi is on the LHS.
530 if (!isa<PHINode>(LHS)) {
531 std::swap(LHS, RHS);
532 Pred = CmpInst::getSwappedPredicate(Pred);
533 }
534 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
535 PHINode *PI = cast<PHINode>(LHS);
536
Duncan Sands5ffc2982010-11-16 12:16:38 +0000537 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000538 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000539 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000540
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000541 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000542 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000543 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000544 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000545 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000546 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000547 // If the operation failed to simplify, or simplified to a different value
548 // to previously, then give up.
549 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000550 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000551 CommonValue = V;
552 }
553
554 return CommonValue;
555}
556
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000557static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
558 Value *&Op0, Value *&Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000559 const SimplifyQuery &Q) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000560 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
561 if (auto *CRHS = dyn_cast<Constant>(Op1))
562 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
563
564 // Canonicalize the constant to the RHS if this is a commutative operation.
565 if (Instruction::isCommutative(Opcode))
566 std::swap(Op0, Op1);
567 }
568 return nullptr;
569}
570
Sanjay Patel472cc782016-01-11 22:14:42 +0000571/// Given operands for an Add, see if we can fold the result.
572/// If not, this returns null.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000573static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000574 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000575 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
576 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000577
Duncan Sands0a2c41682010-12-15 14:07:39 +0000578 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000579 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000580 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000581
Duncan Sands0a2c41682010-12-15 14:07:39 +0000582 // X + 0 -> X
583 if (match(Op1, m_Zero()))
584 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000585
Chen Zhengfdf13ef2018-07-12 03:06:04 +0000586 // If two operands are negative, return 0.
587 if (isKnownNegation(Op0, Op1))
588 return Constant::getNullValue(Op0->getType());
589
Duncan Sands0a2c41682010-12-15 14:07:39 +0000590 // X + (Y - X) -> Y
591 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000592 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000593 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000594 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
595 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000596 return Y;
597
598 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000599 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000600 if (match(Op0, m_Not(m_Specific(Op1))) ||
601 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000602 return Constant::getAllOnesValue(Ty);
603
Craig Topperbcfd2d12017-04-20 16:56:25 +0000604 // add nsw/nuw (xor Y, signmask), signmask --> Y
Sanjay Patelfe672552017-02-18 21:59:09 +0000605 // The no-wrapping add guarantees that the top bit will be set by the add.
606 // Therefore, the xor must be clearing the already set sign bit of Y.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000607 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
Craig Topperbcfd2d12017-04-20 16:56:25 +0000608 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000609 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000610
Roman Lebedevb060ce42018-06-08 15:44:47 +0000611 // add nuw %x, -1 -> -1, because %x can only be 0.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000612 if (IsNUW && match(Op1, m_AllOnes()))
Roman Lebedevb060ce42018-06-08 15:44:47 +0000613 return Op1; // Which is -1.
614
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000615 /// i1 add -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000616 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000617 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000618 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000619
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000620 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000621 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000622 MaxRecurse))
623 return V;
624
Duncan Sandsb238de02010-11-19 09:20:39 +0000625 // Threading Add over selects and phi nodes is pointless, so don't bother.
626 // Threading over the select in "A + select(cond, B, C)" means evaluating
627 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
628 // only if B and C are equal. If B and C are equal then (since we assume
629 // that operands have already been simplified) "select(cond, B, C)" should
630 // have been simplified to the common value of B and C already. Analysing
631 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
632 // for threading over phi nodes.
633
Craig Topper9f008862014-04-15 04:59:12 +0000634 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000635}
636
Roman Lebedevf87321a2018-06-08 15:44:53 +0000637Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000638 const SimplifyQuery &Query) {
Roman Lebedevf87321a2018-06-08 15:44:53 +0000639 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000640}
641
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000642/// Compute the base pointer and cumulative constant offsets for V.
Chandler Carrutha0796552012-03-12 11:19:31 +0000643///
644/// This strips all constant offsets off of V, leaving it the base pointer, and
645/// accumulates the total constant offset applied in the returned constant. It
646/// returns 0 if V is not a pointer, and returns the constant '0' if there are
647/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000648///
649/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
650/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
651/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000652static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000653 bool AllowNonInbounds = false) {
Craig Topper95d23472017-07-09 07:04:00 +0000654 assert(V->getType()->isPtrOrPtrVectorTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000655
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000656 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000657 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000658
659 // Even though we don't look through PHI nodes, we could be called on an
660 // instruction in an unreachable block, which may be on a cycle.
661 SmallPtrSet<Value *, 4> Visited;
662 Visited.insert(V);
663 do {
664 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000665 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000666 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000667 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000668 V = GEP->getPointerOperand();
669 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000670 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000671 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000672 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000673 break;
674 V = GA->getAliasee();
675 } else {
Chandler Carruthdac20a82019-02-11 07:54:10 +0000676 if (auto *Call = dyn_cast<CallBase>(V))
677 if (Value *RV = Call->getReturnedArgOperand()) {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000678 V = RV;
679 continue;
680 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000681 break;
682 }
Craig Topper95d23472017-07-09 07:04:00 +0000683 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000684 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000685
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000686 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
687 if (V->getType()->isVectorTy())
688 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
689 OffsetIntPtr);
690 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000691}
692
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000693/// Compute the constant difference between two pointer values.
Chandler Carrutha0796552012-03-12 11:19:31 +0000694/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000695static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
696 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000697 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
698 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000699
700 // If LHS and RHS are not related via constant offsets to the same base
701 // value, there is nothing we can do here.
702 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000703 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000704
705 // Otherwise, the difference of LHS - RHS can be computed as:
706 // LHS - RHS
707 // = (LHSOffset + Base) - (RHSOffset + Base)
708 // = LHSOffset - RHSOffset
709 return ConstantExpr::getSub(LHSOffset, RHSOffset);
710}
711
Sanjay Patel472cc782016-01-11 22:14:42 +0000712/// Given operands for a Sub, see if we can fold the result.
713/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000714static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000715 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000716 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
717 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000718
719 // X - undef -> undef
720 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000721 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000722 return UndefValue::get(Op0->getType());
723
724 // X - 0 -> X
725 if (match(Op1, m_Zero()))
726 return Op0;
727
728 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000729 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000730 return Constant::getNullValue(Op0->getType());
731
Sanjay Patelefd88852016-10-19 21:23:45 +0000732 // Is this a negation?
733 if (match(Op0, m_Zero())) {
734 // 0 - X -> 0 if the sub is NUW.
735 if (isNUW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000736 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000737
Craig Topper8205a1a2017-05-24 16:53:07 +0000738 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +0000739 if (Known.Zero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000740 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
741 // Op1 must be 0 because negating the minimum signed value is undefined.
742 if (isNSW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000743 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000744
745 // 0 - X -> X if X is 0 or the minimum signed value.
746 return Op1;
747 }
748 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000749
Duncan Sands99589d02011-01-18 11:50:19 +0000750 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
751 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000752 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000753 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
754 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000756 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000757 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000758 // It does, we successfully reassociated!
759 ++NumReassoc;
760 return W;
761 }
762 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000763 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000764 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000765 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000766 // It does, we successfully reassociated!
767 ++NumReassoc;
768 return W;
769 }
770 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000771
Duncan Sands99589d02011-01-18 11:50:19 +0000772 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
773 // For example, X - (X + 1) -> -1
774 X = Op0;
775 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
776 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000777 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000778 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000779 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000780 // It does, we successfully reassociated!
781 ++NumReassoc;
782 return W;
783 }
784 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000785 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000786 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000787 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000788 // It does, we successfully reassociated!
789 ++NumReassoc;
790 return W;
791 }
792 }
793
794 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
795 // For example, X - (X - Y) -> Y.
796 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000797 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
798 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000799 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000800 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000801 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000802 // It does, we successfully reassociated!
803 ++NumReassoc;
804 return W;
805 }
806
Duncan Sands395ac42d2012-03-13 14:07:05 +0000807 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
808 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
809 match(Op1, m_Trunc(m_Value(Y))))
810 if (X->getType() == Y->getType())
811 // See if "V === X - Y" simplifies.
812 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
813 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000814 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
815 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000816 // It does, return the simplified "trunc V".
817 return W;
818
819 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000820 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000821 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000822 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000823 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
824
Duncan Sands99589d02011-01-18 11:50:19 +0000825 // i1 sub -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000826 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000827 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000828 return V;
829
Duncan Sands0a2c41682010-12-15 14:07:39 +0000830 // Threading Sub over selects and phi nodes is pointless, so don't bother.
831 // Threading over the select in "A - select(cond, B, C)" means evaluating
832 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
833 // only if B and C are equal. If B and C are equal then (since we assume
834 // that operands have already been simplified) "select(cond, B, C)" should
835 // have been simplified to the common value of B and C already. Analysing
836 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
837 // for threading over phi nodes.
838
Craig Topper9f008862014-04-15 04:59:12 +0000839 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000840}
841
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000842Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000843 const SimplifyQuery &Q) {
844 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
845}
846
Sanjay Patel472cc782016-01-11 22:14:42 +0000847/// Given operands for a Mul, see if we can fold the result.
848/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000849static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000850 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000851 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
852 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000853
854 // X * undef -> 0
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000855 // X * 0 -> 0
Sanjay Patel30be6652018-04-22 17:07:44 +0000856 if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
857 return Constant::getNullValue(Op0->getType());
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000858
859 // X * 1 -> X
860 if (match(Op1, m_One()))
861 return Op0;
862
Duncan Sandsb67edc62011-01-30 18:03:50 +0000863 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000864 Value *X = nullptr;
Florian Hahn19f9e322018-08-17 14:39:04 +0000865 if (Q.IIQ.UseInstrInfo &&
866 (match(Op0,
867 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
868 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000869 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000870
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000871 // i1 mul -> and.
Craig Topperfde47232017-07-09 07:04:03 +0000872 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000873 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000874 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000875
876 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000877 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000878 MaxRecurse))
879 return V;
880
Dmitry Venikovd2257be2018-01-02 05:47:42 +0000881 // Mul distributes over Add. Try some generic simplifications based on this.
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000882 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000883 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000884 return V;
885
886 // If the operation is with the result of a select instruction, check whether
887 // operating on either branch of the select always yields the same value.
888 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000889 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000890 MaxRecurse))
891 return V;
892
893 // If the operation is with the result of a phi instruction, check whether
894 // operating on all incoming values of the phi always yields the same value.
895 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000896 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000897 MaxRecurse))
898 return V;
899
Craig Topper9f008862014-04-15 04:59:12 +0000900 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000901}
902
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000903Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
904 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
905}
906
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000907/// Check for common or similar folds of integer division or integer remainder.
Sanjay Patelfa877fd2017-09-11 13:34:27 +0000908/// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000909static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
910 Type *Ty = Op0->getType();
911
912 // X / undef -> undef
913 // X % undef -> undef
914 if (match(Op1, m_Undef()))
915 return Op1;
916
917 // X / 0 -> undef
918 // X % 0 -> undef
919 // We don't need to preserve faults!
920 if (match(Op1, m_Zero()))
921 return UndefValue::get(Ty);
922
Zvi Rackover51f0d642018-01-24 17:22:00 +0000923 // If any element of a constant divisor vector is zero or undef, the whole op
924 // is undef.
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000925 auto *Op1C = dyn_cast<Constant>(Op1);
926 if (Op1C && Ty->isVectorTy()) {
927 unsigned NumElts = Ty->getVectorNumElements();
928 for (unsigned i = 0; i != NumElts; ++i) {
929 Constant *Elt = Op1C->getAggregateElement(i);
Zvi Rackover51f0d642018-01-24 17:22:00 +0000930 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000931 return UndefValue::get(Ty);
932 }
933 }
934
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000935 // undef / X -> 0
936 // undef % X -> 0
937 if (match(Op0, m_Undef()))
938 return Constant::getNullValue(Ty);
939
940 // 0 / X -> 0
941 // 0 % X -> 0
942 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +0000943 return Constant::getNullValue(Op0->getType());
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000944
945 // X / X -> 1
946 // X % X -> 0
947 if (Op0 == Op1)
948 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
949
950 // X / 1 -> X
951 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +0000952 // If this is a boolean op (single-bit element type), we can't have
953 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
Sanjay Patel1e911fa2018-06-25 18:51:21 +0000954 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
955 Value *X;
956 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
957 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000958 return IsDiv ? Op0 : Constant::getNullValue(Ty);
959
960 return nullptr;
961}
962
Sanjay Patelcca8f782017-09-14 14:09:11 +0000963/// Given a predicate and two operands, return true if the comparison is true.
964/// This is a helper for div/rem simplification where we return some other value
965/// when we can prove a relationship between the operands.
966static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
967 const SimplifyQuery &Q, unsigned MaxRecurse) {
968 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
969 Constant *C = dyn_cast_or_null<Constant>(V);
970 return (C && C->isAllOnesValue());
971}
972
973/// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
974/// to simplify X % Y to X.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000975static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
Sanjay Patelcca8f782017-09-14 14:09:11 +0000976 unsigned MaxRecurse, bool IsSigned) {
977 // Recursion is always used, so bail out at once if we already hit the limit.
978 if (!MaxRecurse--)
979 return false;
980
981 if (IsSigned) {
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000982 // |X| / |Y| --> 0
983 //
984 // We require that 1 operand is a simple constant. That could be extended to
985 // 2 variables if we computed the sign bit for each.
986 //
987 // Make sure that a constant is not the minimum signed value because taking
988 // the abs() of that is undefined.
989 Type *Ty = X->getType();
990 const APInt *C;
991 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
992 // Is the variable divisor magnitude always greater than the constant
993 // dividend magnitude?
994 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
995 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
996 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
997 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
998 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
999 return true;
1000 }
1001 if (match(Y, m_APInt(C))) {
1002 // Special-case: we can't take the abs() of a minimum signed value. If
1003 // that's the divisor, then all we have to do is prove that the dividend
1004 // is also not the minimum signed value.
1005 if (C->isMinSignedValue())
1006 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1007
1008 // Is the variable dividend magnitude always less than the constant
1009 // divisor magnitude?
1010 // |X| < |C| --> X > -abs(C) and X < abs(C)
1011 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1012 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1013 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1014 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1015 return true;
1016 }
Sanjay Patelcca8f782017-09-14 14:09:11 +00001017 return false;
1018 }
1019
1020 // IsSigned == false.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +00001021 // Is the dividend unsigned less than the divisor?
1022 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
Sanjay Patelcca8f782017-09-14 14:09:11 +00001023}
1024
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001025/// These are simplifications common to SDiv and UDiv.
1026static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001027 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001028 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1029 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +00001030
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001031 if (Value *V = simplifyDivRem(Op0, Op1, true))
1032 return V;
1033
Sanjay Patelcca8f782017-09-14 14:09:11 +00001034 bool IsSigned = Opcode == Instruction::SDiv;
Duncan Sands65995fa2011-01-28 18:50:50 +00001035
Duncan Sands771e82a2011-01-28 16:51:11 +00001036 // (X * Y) / Y -> X if the multiplication does not overflow.
Sanjay Patel33cb8452018-01-19 16:12:55 +00001037 Value *X;
1038 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1039 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1040 // If the Mul does not overflow, then we are good to go.
Florian Hahn19f9e322018-08-17 14:39:04 +00001041 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1042 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
Duncan Sands5747aba2011-02-02 20:52:00 +00001043 return X;
Sanjay Patel33cb8452018-01-19 16:12:55 +00001044 // If X has the form X = A / Y, then X * Y cannot overflow.
1045 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1046 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1047 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001048 }
1049
Duncan Sands65995fa2011-01-28 18:50:50 +00001050 // (X rem Y) / Y -> 0
Sanjay Patelcca8f782017-09-14 14:09:11 +00001051 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1052 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 return Constant::getNullValue(Op0->getType());
1054
David Majnemercb9d5962014-10-11 10:20:01 +00001055 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1056 ConstantInt *C1, *C2;
Sanjay Patelcca8f782017-09-14 14:09:11 +00001057 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
David Majnemercb9d5962014-10-11 10:20:01 +00001058 match(Op1, m_ConstantInt(C2))) {
1059 bool Overflow;
Craig Topper9b71a402017-04-19 21:09:45 +00001060 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
David Majnemercb9d5962014-10-11 10:20:01 +00001061 if (Overflow)
1062 return Constant::getNullValue(Op0->getType());
1063 }
1064
Duncan Sands65995fa2011-01-28 18:50:50 +00001065 // If the operation is with the result of a select instruction, check whether
1066 // operating on either branch of the select always yields the same value.
1067 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001068 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001069 return V;
1070
1071 // If the operation is with the result of a phi instruction, check whether
1072 // operating on all incoming values of the phi always yields the same value.
1073 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001074 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001075 return V;
1076
Sanjay Patelcca8f782017-09-14 14:09:11 +00001077 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1078 return Constant::getNullValue(Op0->getType());
1079
Craig Topper9f008862014-04-15 04:59:12 +00001080 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001081}
1082
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001083/// These are simplifications common to SRem and URem.
1084static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001085 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001086 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1087 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001088
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001089 if (Value *V = simplifyDivRem(Op0, Op1, false))
1090 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001091
David Majnemerb435a422014-09-17 04:16:35 +00001092 // (X % Y) % Y -> X % Y
1093 if ((Opcode == Instruction::SRem &&
1094 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1095 (Opcode == Instruction::URem &&
1096 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001097 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001098
Anton Bikineev82f61152018-01-23 09:27:47 +00001099 // (X << Y) % X -> 0
Florian Hahn19f9e322018-08-17 14:39:04 +00001100 if (Q.IIQ.UseInstrInfo &&
1101 ((Opcode == Instruction::SRem &&
1102 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1103 (Opcode == Instruction::URem &&
1104 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
Anton Bikineev82f61152018-01-23 09:27:47 +00001105 return Constant::getNullValue(Op0->getType());
1106
Duncan Sandsa3e36992011-05-02 16:27:02 +00001107 // If the operation is with the result of a select instruction, check whether
1108 // operating on either branch of the select always yields the same value.
1109 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001110 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001111 return V;
1112
1113 // If the operation is with the result of a phi instruction, check whether
1114 // operating on all incoming values of the phi always yields the same value.
1115 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001116 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001117 return V;
1118
Sanjay Patelcca8f782017-09-14 14:09:11 +00001119 // If X / Y == 0, then X % Y == X.
1120 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1121 return Op0;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001122
1123 return nullptr;
1124}
1125
1126/// Given operands for an SDiv, see if we can fold the result.
1127/// If not, this returns null.
1128static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1129 unsigned MaxRecurse) {
Chen Zheng69bb0642018-07-21 12:27:54 +00001130 // If two operands are negated and no signed overflow, return -1.
1131 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1132 return Constant::getAllOnesValue(Op0->getType());
1133
Sanjay Patelcca8f782017-09-14 14:09:11 +00001134 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001135}
1136
1137Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1138 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1139}
1140
1141/// Given operands for a UDiv, see if we can fold the result.
1142/// If not, this returns null.
1143static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1144 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001145 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001146}
1147
1148Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1149 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1150}
1151
Sanjay Patel472cc782016-01-11 22:14:42 +00001152/// Given operands for an SRem, see if we can fold the result.
1153/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001154static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001155 unsigned MaxRecurse) {
Sanjay Patel2b7e3102018-06-26 15:32:54 +00001156 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1157 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1158 Value *X;
1159 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1160 return ConstantInt::getNullValue(Op0->getType());
1161
Chen Zhengf801d0f2018-07-20 13:00:47 +00001162 // If the two operands are negated, return 0.
1163 if (isKnownNegation(Op0, Op1))
Chen Zheng69bb0642018-07-21 12:27:54 +00001164 return ConstantInt::getNullValue(Op0->getType());
Chen Zhengf801d0f2018-07-20 13:00:47 +00001165
Sanjay Patelcca8f782017-09-14 14:09:11 +00001166 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001167}
1168
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001169Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1170 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1171}
1172
Sanjay Patel472cc782016-01-11 22:14:42 +00001173/// Given operands for a URem, see if we can fold the result.
1174/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001175static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001176 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001177 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001178}
1179
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001180Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1181 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1182}
1183
Sanjay Patel472cc782016-01-11 22:14:42 +00001184/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001185static bool isUndefShift(Value *Amount) {
1186 Constant *C = dyn_cast<Constant>(Amount);
1187 if (!C)
1188 return false;
1189
1190 // X shift by undef -> undef because it may shift by the bitwidth.
1191 if (isa<UndefValue>(C))
1192 return true;
1193
1194 // Shifting by the bitwidth or more is undefined.
1195 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1196 if (CI->getValue().getLimitedValue() >=
1197 CI->getType()->getScalarSizeInBits())
1198 return true;
1199
1200 // If all lanes of a vector shift are undefined the whole shift is.
1201 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1202 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1203 if (!isUndefShift(C->getAggregateElement(I)))
1204 return false;
1205 return true;
1206 }
1207
1208 return false;
1209}
1210
Sanjay Patel472cc782016-01-11 22:14:42 +00001211/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1212/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001213static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001214 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001215 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1216 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001217
Duncan Sands571fd9a2011-01-14 14:44:12 +00001218 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001219 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001220 return Constant::getNullValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001221
Duncan Sands571fd9a2011-01-14 14:44:12 +00001222 // X shift by 0 -> X
Sanjay Patelad0bfb82018-06-26 17:31:38 +00001223 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1224 // would be poison.
1225 Value *X;
1226 if (match(Op1, m_Zero()) ||
1227 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001228 return Op0;
1229
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001230 // Fold undefined shifts.
1231 if (isUndefShift(Op1))
1232 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001233
Duncan Sands571fd9a2011-01-14 14:44:12 +00001234 // If the operation is with the result of a select instruction, check whether
1235 // operating on either branch of the select always yields the same value.
1236 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001237 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001238 return V;
1239
1240 // If the operation is with the result of a phi instruction, check whether
1241 // operating on all incoming values of the phi always yields the same value.
1242 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001243 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001244 return V;
1245
Sanjay Patel6786bc52016-05-10 20:46:54 +00001246 // If any bits in the shift amount make that value greater than or equal to
1247 // the number of bits in the type, the shift is undefined.
Craig Topper8205a1a2017-05-24 16:53:07 +00001248 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1249 if (Known.One.getLimitedValue() >= Known.getBitWidth())
Sanjay Patel6786bc52016-05-10 20:46:54 +00001250 return UndefValue::get(Op0->getType());
1251
1252 // If all valid bits in the shift amount are known zero, the first operand is
1253 // unchanged.
Craig Topper8205a1a2017-05-24 16:53:07 +00001254 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
Craig Topper8df66c62017-05-12 17:20:30 +00001255 if (Known.countMinTrailingZeros() >= NumValidShiftBits)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001256 return Op0;
1257
Craig Topper9f008862014-04-15 04:59:12 +00001258 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001259}
1260
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001261/// Given operands for an Shl, LShr or AShr, see if we can
David Majnemerbf7550e2014-11-05 00:59:59 +00001262/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001263static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001264 Value *Op1, bool isExact, const SimplifyQuery &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001265 unsigned MaxRecurse) {
1266 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1267 return V;
1268
1269 // X >> X -> 0
1270 if (Op0 == Op1)
1271 return Constant::getNullValue(Op0->getType());
1272
David Majnemer65c52ae2014-12-17 01:54:33 +00001273 // undef >> X -> 0
1274 // undef >> X -> undef (if it's exact)
1275 if (match(Op0, m_Undef()))
1276 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1277
David Majnemerbf7550e2014-11-05 00:59:59 +00001278 // The low bit cannot be shifted out of an exact shift if it is set.
1279 if (isExact) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001280 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +00001281 if (Op0Known.One[0])
David Majnemerbf7550e2014-11-05 00:59:59 +00001282 return Op0;
1283 }
1284
1285 return nullptr;
1286}
1287
Sanjay Patel472cc782016-01-11 22:14:42 +00001288/// Given operands for an Shl, see if we can fold the result.
1289/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001290static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001291 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001292 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001293 return V;
1294
1295 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001296 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001297 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001298 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001299
Chris Lattner9e4aa022011-02-09 17:15:04 +00001300 // (X >> A) << A -> X
1301 Value *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001302 if (Q.IIQ.UseInstrInfo &&
1303 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001304 return X;
Roman Lebedev26838022018-06-07 20:03:45 +00001305
1306 // shl nuw i8 C, %x -> C iff C has sign bit set.
1307 if (isNUW && match(Op0, m_Negative()))
1308 return Op0;
1309 // NOTE: could use computeKnownBits() / LazyValueInfo,
1310 // but the cost-benefit analysis suggests it isn't worth it.
1311
Craig Topper9f008862014-04-15 04:59:12 +00001312 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001313}
1314
Chris Lattner9e4aa022011-02-09 17:15:04 +00001315Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001316 const SimplifyQuery &Q) {
1317 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1318}
1319
Sanjay Patel472cc782016-01-11 22:14:42 +00001320/// Given operands for an LShr, see if we can fold the result.
1321/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001322static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001323 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001324 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1325 MaxRecurse))
1326 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001327
Chris Lattner9e4aa022011-02-09 17:15:04 +00001328 // (X << A) >> A -> X
1329 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001330 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001331 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001332
Hiroshi Inoue02f79ea2018-08-01 04:40:32 +00001333 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1334 // We can return X as we do in the above case since OR alters no bits in X.
1335 // SimplifyDemandedBits in InstCombine can do more general optimization for
1336 // bit manipulation. This pattern aims to provide opportunities for other
1337 // optimizers by supporting a simple but common case in InstSimplify.
1338 Value *Y;
1339 const APInt *ShRAmt, *ShLAmt;
1340 if (match(Op1, m_APInt(ShRAmt)) &&
1341 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1342 *ShRAmt == *ShLAmt) {
1343 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1344 const unsigned Width = Op0->getType()->getScalarSizeInBits();
1345 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
Benjamin Kramerbae6aab2018-08-12 11:43:03 +00001346 if (ShRAmt->uge(EffWidthY))
Hiroshi Inoue02f79ea2018-08-01 04:40:32 +00001347 return X;
1348 }
1349
Craig Topper9f008862014-04-15 04:59:12 +00001350 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001351}
1352
Chris Lattner9e4aa022011-02-09 17:15:04 +00001353Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001354 const SimplifyQuery &Q) {
1355 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1356}
1357
Sanjay Patel472cc782016-01-11 22:14:42 +00001358/// Given operands for an AShr, see if we can fold the result.
1359/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001360static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001361 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001362 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1363 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001364 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001365
Sanjay Pateladf6e882018-02-18 18:05:08 +00001366 // all ones >>a X -> -1
1367 // Do not return Op0 because it may contain undef elements if it's a vector.
Duncan Sands7f60dc12011-01-14 00:37:45 +00001368 if (match(Op0, m_AllOnes()))
Sanjay Pateladf6e882018-02-18 18:05:08 +00001369 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001370
Chris Lattner9e4aa022011-02-09 17:15:04 +00001371 // (X << A) >> A -> X
1372 Value *X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001373 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001374 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001375
Suyog Sarda68862412014-07-17 06:28:15 +00001376 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001377 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001378 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1379 return Op0;
1380
Craig Topper9f008862014-04-15 04:59:12 +00001381 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001382}
1383
Chris Lattner9e4aa022011-02-09 17:15:04 +00001384Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001385 const SimplifyQuery &Q) {
1386 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1387}
1388
Craig Topper348314d2017-05-26 22:42:34 +00001389/// Commuted variants are assumed to be handled by calling this function again
1390/// with the parameters swapped.
David Majnemer1af36e52014-12-06 10:51:40 +00001391static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1392 ICmpInst *UnsignedICmp, bool IsAnd) {
1393 Value *X, *Y;
1394
1395 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001396 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1397 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001398 return nullptr;
1399
1400 ICmpInst::Predicate UnsignedPred;
1401 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1402 ICmpInst::isUnsigned(UnsignedPred))
1403 ;
1404 else if (match(UnsignedICmp,
Sanjay Patel0c57de42018-06-20 14:22:49 +00001405 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
David Majnemer1af36e52014-12-06 10:51:40 +00001406 ICmpInst::isUnsigned(UnsignedPred))
1407 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1408 else
1409 return nullptr;
1410
1411 // X < Y && Y != 0 --> X < Y
1412 // X < Y || Y != 0 --> Y != 0
1413 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1414 return IsAnd ? UnsignedICmp : ZeroICmp;
1415
1416 // X >= Y || Y != 0 --> true
1417 // X >= Y || Y == 0 --> X >= Y
1418 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1419 if (EqPred == ICmpInst::ICMP_NE)
1420 return getTrue(UnsignedICmp->getType());
1421 return UnsignedICmp;
1422 }
1423
David Majnemerd5b3aa42014-12-08 18:30:43 +00001424 // X < Y && Y == 0 --> false
1425 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1426 IsAnd)
1427 return getFalse(UnsignedICmp->getType());
1428
David Majnemer1af36e52014-12-06 10:51:40 +00001429 return nullptr;
1430}
1431
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001432/// Commuted variants are assumed to be handled by calling this function again
1433/// with the parameters swapped.
1434static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1435 ICmpInst::Predicate Pred0, Pred1;
1436 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001437 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1438 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001439 return nullptr;
1440
1441 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1442 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1443 // can eliminate Op1 from this 'and'.
1444 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1445 return Op0;
1446
1447 // Check for any combination of predicates that are guaranteed to be disjoint.
1448 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1449 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1450 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1451 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1452 return getFalse(Op0->getType());
1453
1454 return nullptr;
1455}
1456
1457/// Commuted variants are assumed to be handled by calling this function again
1458/// with the parameters swapped.
Sanjay Patel142cb832017-05-04 18:19:17 +00001459static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1460 ICmpInst::Predicate Pred0, Pred1;
1461 Value *A ,*B;
1462 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1463 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1464 return nullptr;
1465
1466 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1467 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1468 // can eliminate Op0 from this 'or'.
1469 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1470 return Op1;
1471
1472 // Check for any combination of predicates that cover the entire range of
1473 // possibilities.
1474 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1475 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1476 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1477 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1478 return getTrue(Op0->getType());
1479
1480 return nullptr;
1481}
1482
Sanjay Patel599e65b2017-05-07 15:11:40 +00001483/// Test if a pair of compares with a shared operand and 2 constants has an
1484/// empty set intersection, full set union, or if one compare is a superset of
1485/// the other.
1486static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1487 bool IsAnd) {
1488 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1489 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1490 return nullptr;
1491
1492 const APInt *C0, *C1;
1493 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1494 !match(Cmp1->getOperand(1), m_APInt(C1)))
1495 return nullptr;
1496
1497 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1498 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1499
Sanjay Patel67454472017-05-08 16:35:02 +00001500 // For and-of-compares, check if the intersection is empty:
Sanjay Patel599e65b2017-05-07 15:11:40 +00001501 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1502 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1503 return getFalse(Cmp0->getType());
1504
1505 // For or-of-compares, check if the union is full:
1506 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1507 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1508 return getTrue(Cmp0->getType());
1509
1510 // Is one range a superset of the other?
1511 // If this is and-of-compares, take the smaller set:
1512 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1513 // If this is or-of-compares, take the larger set:
1514 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1515 if (Range0.contains(Range1))
1516 return IsAnd ? Cmp1 : Cmp0;
1517 if (Range1.contains(Range0))
1518 return IsAnd ? Cmp0 : Cmp1;
1519
1520 return nullptr;
1521}
1522
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001523static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1524 bool IsAnd) {
1525 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1526 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1527 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1528 return nullptr;
1529
1530 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1531 return nullptr;
1532
Sanjay Patel4158eff2018-01-13 15:44:44 +00001533 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001534 Value *X = Cmp0->getOperand(0);
1535 Value *Y = Cmp1->getOperand(0);
1536
1537 // If one of the compares is a masked version of a (not) null check, then
Sanjay Patel4158eff2018-01-13 15:44:44 +00001538 // that compare implies the other, so we eliminate the other. Optionally, look
1539 // through a pointer-to-int cast to match a null check of a pointer type.
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001540
Sanjay Patel9568f422018-01-14 15:58:18 +00001541 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1542 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1543 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1544 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001545 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1546 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001547 return Cmp1;
1548
Sanjay Patel9568f422018-01-14 15:58:18 +00001549 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1550 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1551 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1552 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001553 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1554 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001555 return Cmp0;
1556
1557 return nullptr;
1558}
1559
Florian Hahn19f9e322018-08-17 14:39:04 +00001560static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1561 const InstrInfoQuery &IIQ) {
Sanjay Patel599e65b2017-05-07 15:11:40 +00001562 // (icmp (add V, C0), C1) & (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001563 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001564 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001565 Value *V;
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001566 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001567 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001568
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001569 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001570 return nullptr;
1571
Florian Hahn19f9e322018-08-17 14:39:04 +00001572 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001573 if (AddInst->getOperand(1) != Op1->getOperand(1))
1574 return nullptr;
1575
Craig Topper9bce1ad2017-05-26 19:04:02 +00001576 Type *ITy = Op0->getType();
Florian Hahn19f9e322018-08-17 14:39:04 +00001577 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1578 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
David Majnemera315bd82014-09-15 08:15:28 +00001579
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001580 const APInt Delta = *C1 - *C0;
1581 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001582 if (Delta == 2) {
1583 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1584 return getFalse(ITy);
1585 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1586 return getFalse(ITy);
1587 }
1588 if (Delta == 1) {
1589 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1590 return getFalse(ITy);
1591 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1592 return getFalse(ITy);
1593 }
1594 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001595 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001596 if (Delta == 2)
1597 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1598 return getFalse(ITy);
1599 if (Delta == 1)
1600 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1601 return getFalse(ITy);
1602 }
1603
1604 return nullptr;
1605}
1606
Florian Hahn19f9e322018-08-17 14:39:04 +00001607static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1608 const InstrInfoQuery &IIQ) {
Craig Topper348314d2017-05-26 22:42:34 +00001609 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1610 return X;
1611 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
Sanjay Patel142cb832017-05-04 18:19:17 +00001612 return X;
1613
Craig Topper348314d2017-05-26 22:42:34 +00001614 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1615 return X;
1616 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
Sanjay Patel142cb832017-05-04 18:19:17 +00001617 return X;
1618
Craig Topper348314d2017-05-26 22:42:34 +00001619 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
Sanjay Patel599e65b2017-05-07 15:11:40 +00001620 return X;
1621
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001622 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1623 return X;
1624
Florian Hahn19f9e322018-08-17 14:39:04 +00001625 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001626 return X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001627 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001628 return X;
1629
1630 return nullptr;
1631}
1632
Florian Hahn19f9e322018-08-17 14:39:04 +00001633static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1634 const InstrInfoQuery &IIQ) {
Sanjay Patel142cb832017-05-04 18:19:17 +00001635 // (icmp (add V, C0), C1) | (icmp V, C0)
1636 ICmpInst::Predicate Pred0, Pred1;
1637 const APInt *C0, *C1;
1638 Value *V;
1639 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1640 return nullptr;
1641
1642 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1643 return nullptr;
1644
1645 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1646 if (AddInst->getOperand(1) != Op1->getOperand(1))
1647 return nullptr;
1648
1649 Type *ITy = Op0->getType();
Florian Hahn19f9e322018-08-17 14:39:04 +00001650 bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1651 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
Sanjay Patel142cb832017-05-04 18:19:17 +00001652
1653 const APInt Delta = *C1 - *C0;
1654 if (C0->isStrictlyPositive()) {
1655 if (Delta == 2) {
1656 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1657 return getTrue(ITy);
1658 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1659 return getTrue(ITy);
1660 }
1661 if (Delta == 1) {
1662 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1663 return getTrue(ITy);
1664 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1665 return getTrue(ITy);
1666 }
1667 }
1668 if (C0->getBoolValue() && isNUW) {
1669 if (Delta == 2)
1670 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1671 return getTrue(ITy);
1672 if (Delta == 1)
1673 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1674 return getTrue(ITy);
1675 }
1676
1677 return nullptr;
1678}
1679
Florian Hahn19f9e322018-08-17 14:39:04 +00001680static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1681 const InstrInfoQuery &IIQ) {
Craig Topper348314d2017-05-26 22:42:34 +00001682 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1683 return X;
1684 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1685 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001686
Craig Topper348314d2017-05-26 22:42:34 +00001687 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1688 return X;
1689 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1690 return X;
1691
1692 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1693 return X;
1694
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001695 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1696 return X;
1697
Florian Hahn19f9e322018-08-17 14:39:04 +00001698 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001699 return X;
Florian Hahn19f9e322018-08-17 14:39:04 +00001700 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, IIQ))
Craig Topper348314d2017-05-26 22:42:34 +00001701 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001702
1703 return nullptr;
1704}
1705
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001706static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI,
1707 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
Sanjay Pateleb731b02017-11-19 15:34:27 +00001708 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1709 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1710 if (LHS0->getType() != RHS0->getType())
1711 return nullptr;
1712
1713 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1714 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1715 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1716 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1717 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1718 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1719 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1720 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1721 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1722 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1723 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001724 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1725 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
Sanjay Pateleb731b02017-11-19 15:34:27 +00001726 return RHS;
1727
1728 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1729 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1730 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1731 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1732 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1733 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1734 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1735 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001736 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1737 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
Sanjay Pateleb731b02017-11-19 15:34:27 +00001738 return LHS;
1739 }
1740
1741 return nullptr;
1742}
1743
Florian Hahn19f9e322018-08-17 14:39:04 +00001744static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q,
Matt Arsenaultd54b7f02018-08-09 22:40:08 +00001745 Value *Op0, Value *Op1, bool IsAnd) {
Sanjay Patele42b4d52017-05-04 19:51:34 +00001746 // Look through casts of the 'and' operands to find compares.
1747 auto *Cast0 = dyn_cast<CastInst>(Op0);
1748 auto *Cast1 = dyn_cast<CastInst>(Op1);
1749 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1750 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1751 Op0 = Cast0->getOperand(0);
1752 Op1 = Cast1->getOperand(0);
1753 }
1754
Sanjay Pateleb731b02017-11-19 15:34:27 +00001755 Value *V = nullptr;
1756 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1757 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1758 if (ICmp0 && ICmp1)
Florian Hahn19f9e322018-08-17 14:39:04 +00001759 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q.IIQ)
1760 : simplifyOrOfICmps(ICmp0, ICmp1, Q.IIQ);
Sanjay Patele42b4d52017-05-04 19:51:34 +00001761
Sanjay Pateleb731b02017-11-19 15:34:27 +00001762 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1763 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1764 if (FCmp0 && FCmp1)
Florian Hahn19f9e322018-08-17 14:39:04 +00001765 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
Sanjay Pateleb731b02017-11-19 15:34:27 +00001766
Craig Topper348314d2017-05-26 22:42:34 +00001767 if (!V)
1768 return nullptr;
1769 if (!Cast0)
Sanjay Patele42b4d52017-05-04 19:51:34 +00001770 return V;
Craig Topper348314d2017-05-26 22:42:34 +00001771
1772 // If we looked through casts, we can only handle a constant simplification
1773 // because we are not allowed to create a cast instruction here.
1774 if (auto *C = dyn_cast<Constant>(V))
1775 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
Sanjay Patele42b4d52017-05-04 19:51:34 +00001776
1777 return nullptr;
1778}
1779
Sanjay Patel472cc782016-01-11 22:14:42 +00001780/// Given operands for an And, see if we can fold the result.
1781/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001782static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001783 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001784 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1785 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001786
Chris Lattnera71e9d62009-11-10 00:55:12 +00001787 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001788 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001789 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001790
Chris Lattnera71e9d62009-11-10 00:55:12 +00001791 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001792 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001793 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001794
Duncan Sandsc89ac072010-11-17 18:52:15 +00001795 // X & 0 = 0
1796 if (match(Op1, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001797 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001798
Duncan Sandsc89ac072010-11-17 18:52:15 +00001799 // X & -1 = X
1800 if (match(Op1, m_AllOnes()))
1801 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001802
Chris Lattnera71e9d62009-11-10 00:55:12 +00001803 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001804 if (match(Op0, m_Not(m_Specific(Op1))) ||
1805 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001806 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001807
Chris Lattnera71e9d62009-11-10 00:55:12 +00001808 // (A | ?) & A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001809 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001810 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001811
Chris Lattnera71e9d62009-11-10 00:55:12 +00001812 // A & (A | ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001813 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001814 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001815
Sanjay Patel877364f2017-05-16 21:51:04 +00001816 // A mask that only clears known zeros of a shifted value is a no-op.
1817 Value *X;
1818 const APInt *Mask;
1819 const APInt *ShAmt;
1820 if (match(Op1, m_APInt(Mask))) {
1821 // If all bits in the inverted and shifted mask are clear:
1822 // and (shl X, ShAmt), Mask --> shl X, ShAmt
1823 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1824 (~(*Mask)).lshr(*ShAmt).isNullValue())
1825 return Op0;
1826
1827 // If all bits in the inverted and shifted mask are clear:
1828 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1829 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1830 (~(*Mask)).shl(*ShAmt).isNullValue())
1831 return Op0;
1832 }
1833
Duncan Sandsba286d72011-10-26 20:55:21 +00001834 // A & (-A) = A if A is a power of two or zero.
1835 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1836 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001837 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1838 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001839 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001840 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1841 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001842 return Op1;
1843 }
1844
Florian Hahn19f9e322018-08-17 14:39:04 +00001845 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001846 return V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001847
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001848 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001849 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1850 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001851 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001852
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001853 // And distributes over Or. Try some generic simplifications based on this.
1854 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001855 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001856 return V;
1857
1858 // And distributes over Xor. Try some generic simplifications based on this.
1859 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001860 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001861 return V;
1862
Duncan Sandsb0579e92010-11-10 13:00:08 +00001863 // If the operation is with the result of a select instruction, check whether
1864 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001865 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001866 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1867 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001868 return V;
1869
1870 // If the operation is with the result of a phi instruction, check whether
1871 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001872 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001873 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001874 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001875 return V;
1876
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001877 // Assuming the effective width of Y is not larger than A, i.e. all bits
1878 // from X and Y are disjoint in (X << A) | Y,
1879 // if the mask of this AND op covers all bits of X or Y, while it covers
1880 // no bits from the other, we can bypass this AND op. E.g.,
1881 // ((X << A) | Y) & Mask -> Y,
1882 // if Mask = ((1 << effective_width_of(Y)) - 1)
1883 // ((X << A) | Y) & Mask -> X << A,
1884 // if Mask = ((1 << effective_width_of(X)) - 1) << A
1885 // SimplifyDemandedBits in InstCombine can optimize the general case.
1886 // This pattern aims to help other passes for a common case.
1887 Value *Y, *XShifted;
1888 if (match(Op1, m_APInt(Mask)) &&
1889 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
1890 m_Value(XShifted)),
1891 m_Value(Y)))) {
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001892 const unsigned Width = Op0->getType()->getScalarSizeInBits();
Benjamin Kramerbae6aab2018-08-12 11:43:03 +00001893 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
1894 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Hiroshi Inoue73f8b252018-08-03 05:39:48 +00001895 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1896 if (EffWidthY <= ShftCnt) {
1897 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
1898 Q.DT);
1899 const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
1900 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
1901 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
1902 // If the mask is extracting all bits from X or Y as is, we can skip
1903 // this AND op.
1904 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
1905 return Y;
1906 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
1907 return XShifted;
1908 }
1909 }
1910
Craig Topper9f008862014-04-15 04:59:12 +00001911 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001912}
1913
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001914Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1915 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1916}
1917
Sanjay Patel472cc782016-01-11 22:14:42 +00001918/// Given operands for an Or, see if we can fold the result.
1919/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001920static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001921 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001922 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1923 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001924
Chris Lattnera71e9d62009-11-10 00:55:12 +00001925 // X | undef -> -1
Sanjay Pateladf6e882018-02-18 18:05:08 +00001926 // X | -1 = -1
1927 // Do not return Op1 because it may contain undef elements if it's a vector.
1928 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001929 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001930
Chris Lattnera71e9d62009-11-10 00:55:12 +00001931 // X | X = X
Duncan Sandsc89ac072010-11-17 18:52:15 +00001932 // X | 0 = X
Sanjay Pateladf6e882018-02-18 18:05:08 +00001933 if (Op0 == Op1 || match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001934 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001935
Chris Lattnera71e9d62009-11-10 00:55:12 +00001936 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001937 if (match(Op0, m_Not(m_Specific(Op1))) ||
1938 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001939 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001940
Chris Lattnera71e9d62009-11-10 00:55:12 +00001941 // (A & ?) | A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001942 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001943 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001944
Chris Lattnera71e9d62009-11-10 00:55:12 +00001945 // A | (A & ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001946 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001947 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001948
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001949 // ~(A & ?) | A = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001950 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001951 return Constant::getAllOnesValue(Op1->getType());
1952
1953 // A | ~(A & ?) = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001954 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001955 return Constant::getAllOnesValue(Op0->getType());
1956
Craig Topperdad7d8d2017-07-16 06:57:41 +00001957 Value *A, *B;
Sanjay Patel08892252017-04-24 18:24:36 +00001958 // (A & ~B) | (A ^ B) -> (A ^ B)
1959 // (~B & A) | (A ^ B) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001960 // (A & ~B) | (B ^ A) -> (B ^ A)
1961 // (~B & A) | (B ^ A) -> (B ^ A)
1962 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1963 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1964 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001965 return Op1;
1966
1967 // Commute the 'or' operands.
1968 // (A ^ B) | (A & ~B) -> (A ^ B)
1969 // (A ^ B) | (~B & A) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001970 // (B ^ A) | (A & ~B) -> (B ^ A)
1971 // (B ^ A) | (~B & A) -> (B ^ A)
1972 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1973 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1974 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001975 return Op0;
1976
Craig Topper479daaf2017-05-14 07:54:43 +00001977 // (A & B) | (~A ^ B) -> (~A ^ B)
1978 // (B & A) | (~A ^ B) -> (~A ^ B)
1979 // (A & B) | (B ^ ~A) -> (B ^ ~A)
1980 // (B & A) | (B ^ ~A) -> (B ^ ~A)
1981 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1982 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1983 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1984 return Op1;
1985
1986 // (~A ^ B) | (A & B) -> (~A ^ B)
1987 // (~A ^ B) | (B & A) -> (~A ^ B)
1988 // (B ^ ~A) | (A & B) -> (B ^ ~A)
1989 // (B ^ ~A) | (B & A) -> (B ^ ~A)
1990 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1991 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1992 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1993 return Op0;
1994
Florian Hahn19f9e322018-08-17 14:39:04 +00001995 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001996 return V;
David Majnemera315bd82014-09-15 08:15:28 +00001997
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001998 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001999 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2000 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002001 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00002002
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00002003 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002004 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
2005 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00002006 return V;
2007
Duncan Sandsb0579e92010-11-10 13:00:08 +00002008 // If the operation is with the result of a select instruction, check whether
2009 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002010 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002011 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00002012 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002013 return V;
2014
Craig Topper50500d52017-05-26 05:16:20 +00002015 // (A & C1)|(B & C2)
Craig Topper1da22c32017-05-26 19:03:53 +00002016 const APInt *C1, *C2;
2017 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2018 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2019 if (*C1 == ~*C2) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002020 // (A & C1)|(B & C2)
2021 // If we have: ((V + N) & C1) | (V & C2)
2022 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2023 // replace with V+N.
Craig Topperc8bebb12017-05-26 19:03:59 +00002024 Value *N;
Craig Topper1da22c32017-05-26 19:03:53 +00002025 if (C2->isMask() && // C2 == 0+1+
Craig Topperc8bebb12017-05-26 19:03:59 +00002026 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002027 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00002028 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00002029 return A;
2030 }
2031 // Or commutes, try both ways.
Craig Topper1da22c32017-05-26 19:03:53 +00002032 if (C1->isMask() &&
Craig Topperc8bebb12017-05-26 19:03:59 +00002033 match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00002034 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00002035 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00002036 return B;
2037 }
2038 }
2039 }
2040
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002041 // If the operation is with the result of a phi instruction, check whether
2042 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002043 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002044 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00002045 return V;
2046
Craig Topper9f008862014-04-15 04:59:12 +00002047 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00002048}
2049
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002050Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2051 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
2052}
2053
Sanjay Patel472cc782016-01-11 22:14:42 +00002054/// Given operands for a Xor, see if we can fold the result.
2055/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002056static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002057 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00002058 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2059 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002060
2061 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00002062 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00002063 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002064
2065 // A ^ 0 = A
2066 if (match(Op1, m_Zero()))
2067 return Op0;
2068
Eli Friedmanad3cfe72011-08-17 19:31:49 +00002069 // A ^ A = 0
2070 if (Op0 == Op1)
2071 return Constant::getNullValue(Op0->getType());
2072
Duncan Sandsc89ac072010-11-17 18:52:15 +00002073 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00002074 if (match(Op0, m_Not(m_Specific(Op1))) ||
2075 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002076 return Constant::getAllOnesValue(Op0->getType());
2077
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002078 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002079 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2080 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002081 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002082
Duncan Sandsb238de02010-11-19 09:20:39 +00002083 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2084 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2085 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2086 // only if B and C are equal. If B and C are equal then (since we assume
2087 // that operands have already been simplified) "select(cond, B, C)" should
2088 // have been simplified to the common value of B and C already. Analysing
2089 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2090 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002091
Craig Topper9f008862014-04-15 04:59:12 +00002092 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002093}
2094
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002095Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2096 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
2097}
2098
2099
Chris Lattner229907c2011-07-18 04:54:35 +00002100static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002101 return CmpInst::makeCmpResultType(Op->getType());
2102}
2103
Sanjay Patel472cc782016-01-11 22:14:42 +00002104/// Rummage around inside V looking for something equivalent to the comparison
2105/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2106/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002107static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2108 Value *LHS, Value *RHS) {
2109 SelectInst *SI = dyn_cast<SelectInst>(V);
2110 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002111 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002112 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2113 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002114 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002115 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2116 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2117 return Cmp;
2118 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2119 LHS == CmpRHS && RHS == CmpLHS)
2120 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002121 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002122}
2123
Dan Gohman9631d902013-02-01 00:49:06 +00002124// A significant optimization not implemented here is assuming that alloca
2125// addresses are not equal to incoming argument values. They don't *alias*,
2126// as we say, but that doesn't mean they aren't equal, so we take a
2127// conservative approach.
2128//
2129// This is inspired in part by C++11 5.10p1:
2130// "Two pointers of the same type compare equal if and only if they are both
2131// null, both point to the same function, or both represent the same
2132// address."
2133//
2134// This is pretty permissive.
2135//
2136// It's also partly due to C11 6.5.9p6:
2137// "Two pointers compare equal if and only if both are null pointers, both are
2138// pointers to the same object (including a pointer to an object and a
2139// subobject at its beginning) or function, both are pointers to one past the
2140// last element of the same array object, or one is a pointer to one past the
2141// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002142// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002143// object in the address space.)
2144//
2145// C11's version is more restrictive, however there's no reason why an argument
2146// couldn't be a one-past-the-end value for a stack object in the caller and be
2147// equal to the beginning of a stack object in the callee.
2148//
2149// If the C and C++ standards are ever made sufficiently restrictive in this
2150// area, it may be possible to update LLVM's semantics accordingly and reinstate
2151// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002152static Constant *
2153computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2154 const DominatorTree *DT, CmpInst::Predicate Pred,
Nuno Lopes404f1062017-09-09 18:23:11 +00002155 AssumptionCache *AC, const Instruction *CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +00002156 const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002157 // First, skip past any trivial no-ops.
2158 LHS = LHS->stripPointerCasts();
2159 RHS = RHS->stripPointerCasts();
2160
2161 // A non-null pointer is not equal to a null pointer.
Florian Hahn19f9e322018-08-17 14:39:04 +00002162 if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2163 IIQ.UseInstrInfo) &&
2164 isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002165 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2166 return ConstantInt::get(GetCompareTy(LHS),
2167 !CmpInst::isTrueWhenEqual(Pred));
2168
Chandler Carruth8059c842012-03-25 21:28:14 +00002169 // We can only fold certain predicates on pointer comparisons.
2170 switch (Pred) {
2171 default:
Craig Topper9f008862014-04-15 04:59:12 +00002172 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002173
2174 // Equality comaprisons are easy to fold.
2175 case CmpInst::ICMP_EQ:
2176 case CmpInst::ICMP_NE:
2177 break;
2178
2179 // We can only handle unsigned relational comparisons because 'inbounds' on
2180 // a GEP only protects against unsigned wrapping.
2181 case CmpInst::ICMP_UGT:
2182 case CmpInst::ICMP_UGE:
2183 case CmpInst::ICMP_ULT:
2184 case CmpInst::ICMP_ULE:
2185 // However, we have to switch them to their signed variants to handle
2186 // negative indices from the base pointer.
2187 Pred = ICmpInst::getSignedPredicate(Pred);
2188 break;
2189 }
2190
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002191 // Strip off any constant offsets so that we can reason about them.
2192 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2193 // here and compare base addresses like AliasAnalysis does, however there are
2194 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2195 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2196 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002197 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2198 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002199
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002200 // If LHS and RHS are related via constant offsets to the same base
2201 // value, we can replace it with an icmp which just compares the offsets.
2202 if (LHS == RHS)
2203 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002204
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002205 // Various optimizations for (in)equality comparisons.
2206 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2207 // Different non-empty allocations that exist at the same time have
2208 // different addresses (if the program can tell). Global variables always
2209 // exist, so they always exist during the lifetime of each other and all
2210 // allocas. Two different allocas usually have different addresses...
2211 //
2212 // However, if there's an @llvm.stackrestore dynamically in between two
2213 // allocas, they may have the same address. It's tempting to reduce the
2214 // scope of the problem by only looking at *static* allocas here. That would
2215 // cover the majority of allocas while significantly reducing the likelihood
2216 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2217 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2218 // an entry block. Also, if we have a block that's not attached to a
2219 // function, we can't tell if it's "static" under the current definition.
2220 // Theoretically, this problem could be fixed by creating a new kind of
2221 // instruction kind specifically for static allocas. Such a new instruction
2222 // could be required to be at the top of the entry block, thus preventing it
2223 // from being subject to a @llvm.stackrestore. Instcombine could even
2224 // convert regular allocas into these special allocas. It'd be nifty.
2225 // However, until then, this problem remains open.
2226 //
2227 // So, we'll assume that two non-empty allocas have different addresses
2228 // for now.
2229 //
2230 // With all that, if the offsets are within the bounds of their allocations
2231 // (and not one-past-the-end! so we can't use inbounds!), and their
2232 // allocations aren't the same, the pointers are not equal.
2233 //
2234 // Note that it's not necessary to check for LHS being a global variable
2235 // address, due to canonicalization and constant folding.
2236 if (isa<AllocaInst>(LHS) &&
2237 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002238 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2239 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002240 uint64_t LHSSize, RHSSize;
Manoj Gupta77eeac32018-07-09 22:27:23 +00002241 ObjectSizeOpts Opts;
2242 Opts.NullIsUnknownSize =
2243 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002244 if (LHSOffsetCI && RHSOffsetCI &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002245 getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2246 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002247 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2248 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002249 if (!LHSOffsetValue.isNegative() &&
2250 !RHSOffsetValue.isNegative() &&
2251 LHSOffsetValue.ult(LHSSize) &&
2252 RHSOffsetValue.ult(RHSSize)) {
2253 return ConstantInt::get(GetCompareTy(LHS),
2254 !CmpInst::isTrueWhenEqual(Pred));
2255 }
2256 }
2257
2258 // Repeat the above check but this time without depending on DataLayout
2259 // or being able to compute a precise size.
2260 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2261 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2262 LHSOffset->isNullValue() &&
2263 RHSOffset->isNullValue())
2264 return ConstantInt::get(GetCompareTy(LHS),
2265 !CmpInst::isTrueWhenEqual(Pred));
2266 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002267
2268 // Even if an non-inbounds GEP occurs along the path we can still optimize
2269 // equality comparisons concerning the result. We avoid walking the whole
2270 // chain again by starting where the last calls to
2271 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002272 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2273 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002274 if (LHS == RHS)
2275 return ConstantExpr::getICmp(Pred,
2276 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2277 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002278
2279 // If one side of the equality comparison must come from a noalias call
2280 // (meaning a system memory allocation function), and the other side must
2281 // come from a pointer that cannot overlap with dynamically-allocated
2282 // memory within the lifetime of the current function (allocas, byval
2283 // arguments, globals), then determine the comparison result here.
2284 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2285 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2286 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2287
2288 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002289 auto IsNAC = [](ArrayRef<Value *> Objects) {
2290 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002291 };
2292
2293 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002294 // noalias calls. For allocas, we consider only static ones (dynamic
2295 // allocas might be transformed into calls to malloc not simultaneously
2296 // live with the compared-to allocation). For globals, we exclude symbols
2297 // that might be resolve lazily to symbols in another dynamically-loaded
2298 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002299 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2300 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002301 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2302 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2303 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2304 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002305 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002306 !GV->isThreadLocal();
2307 if (const Argument *A = dyn_cast<Argument>(V))
2308 return A->hasByValAttr();
2309 return false;
2310 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002311 };
2312
2313 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2314 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2315 return ConstantInt::get(GetCompareTy(LHS),
2316 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002317
2318 // Fold comparisons for non-escaping pointer even if the allocation call
2319 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2320 // dynamic allocation call could be either of the operands.
2321 Value *MI = nullptr;
Nuno Lopes404f1062017-09-09 18:23:11 +00002322 if (isAllocLikeFn(LHS, TLI) &&
2323 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002324 MI = LHS;
Nuno Lopes404f1062017-09-09 18:23:11 +00002325 else if (isAllocLikeFn(RHS, TLI) &&
2326 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002327 MI = RHS;
2328 // FIXME: We should also fold the compare when the pointer escapes, but the
2329 // compare dominates the pointer escape
2330 if (MI && !PointerMayBeCaptured(MI, true, true))
2331 return ConstantInt::get(GetCompareTy(LHS),
2332 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002333 }
2334
2335 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002336 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002337}
Chris Lattner01990f02012-02-24 19:01:58 +00002338
Sanjay Pateldc65a272016-12-03 17:30:22 +00002339/// Fold an icmp when its operands have i1 scalar type.
2340static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002341 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002342 Type *ITy = GetCompareTy(LHS); // The return type.
2343 Type *OpTy = LHS->getType(); // The operand type.
Craig Topperfde47232017-07-09 07:04:03 +00002344 if (!OpTy->isIntOrIntVectorTy(1))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002345 return nullptr;
2346
Sanjay Patele2787b92017-05-17 20:27:55 +00002347 // A boolean compared to true/false can be simplified in 14 out of the 20
2348 // (10 predicates * 2 constants) possible combinations. Cases not handled here
2349 // require a 'not' of the LHS, so those must be transformed in InstCombine.
2350 if (match(RHS, m_Zero())) {
2351 switch (Pred) {
2352 case CmpInst::ICMP_NE: // X != 0 -> X
2353 case CmpInst::ICMP_UGT: // X >u 0 -> X
2354 case CmpInst::ICMP_SLT: // X <s 0 -> X
2355 return LHS;
2356
2357 case CmpInst::ICMP_ULT: // X <u 0 -> false
2358 case CmpInst::ICMP_SGT: // X >s 0 -> false
2359 return getFalse(ITy);
2360
2361 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2362 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2363 return getTrue(ITy);
2364
2365 default: break;
2366 }
2367 } else if (match(RHS, m_One())) {
2368 switch (Pred) {
2369 case CmpInst::ICMP_EQ: // X == 1 -> X
2370 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2371 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2372 return LHS;
2373
2374 case CmpInst::ICMP_UGT: // X >u 1 -> false
2375 case CmpInst::ICMP_SLT: // X <s -1 -> false
2376 return getFalse(ITy);
2377
2378 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2379 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2380 return getTrue(ITy);
2381
2382 default: break;
2383 }
2384 }
2385
Sanjay Pateldc65a272016-12-03 17:30:22 +00002386 switch (Pred) {
2387 default:
2388 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002389 case ICmpInst::ICMP_UGE:
Sanjay Pateldc65a272016-12-03 17:30:22 +00002390 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2391 return getTrue(ITy);
2392 break;
2393 case ICmpInst::ICMP_SGE:
2394 /// For signed comparison, the values for an i1 are 0 and -1
2395 /// respectively. This maps into a truth table of:
2396 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2397 /// 0 | 0 | 1 (0 >= 0) | 1
2398 /// 0 | 1 | 1 (0 >= -1) | 1
2399 /// 1 | 0 | 0 (-1 >= 0) | 0
2400 /// 1 | 1 | 1 (-1 >= -1) | 1
2401 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2402 return getTrue(ITy);
2403 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002404 case ICmpInst::ICMP_ULE:
2405 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2406 return getTrue(ITy);
2407 break;
2408 }
2409
2410 return nullptr;
2411}
2412
2413/// Try hard to fold icmp with zero RHS because this is a common case.
2414static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002415 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002416 if (!match(RHS, m_Zero()))
2417 return nullptr;
2418
2419 Type *ITy = GetCompareTy(LHS); // The return type.
Sanjay Pateldc65a272016-12-03 17:30:22 +00002420 switch (Pred) {
2421 default:
2422 llvm_unreachable("Unknown ICmp predicate!");
2423 case ICmpInst::ICMP_ULT:
2424 return getFalse(ITy);
2425 case ICmpInst::ICMP_UGE:
2426 return getTrue(ITy);
2427 case ICmpInst::ICMP_EQ:
2428 case ICmpInst::ICMP_ULE:
Florian Hahn19f9e322018-08-17 14:39:04 +00002429 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002430 return getFalse(ITy);
2431 break;
2432 case ICmpInst::ICMP_NE:
2433 case ICmpInst::ICMP_UGT:
Florian Hahn19f9e322018-08-17 14:39:04 +00002434 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002435 return getTrue(ITy);
2436 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002437 case ICmpInst::ICMP_SLT: {
2438 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2439 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002440 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002441 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002442 return getFalse(ITy);
2443 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002444 }
2445 case ICmpInst::ICMP_SLE: {
2446 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2447 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002448 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002449 if (LHSKnown.isNonNegative() &&
2450 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002451 return getFalse(ITy);
2452 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002453 }
2454 case ICmpInst::ICMP_SGE: {
2455 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2456 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002457 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002458 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002459 return getTrue(ITy);
2460 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002461 }
2462 case ICmpInst::ICMP_SGT: {
2463 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2464 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002465 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002466 if (LHSKnown.isNonNegative() &&
2467 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002468 return getTrue(ITy);
2469 break;
2470 }
Craig Topper1a36b7d2017-05-15 06:39:41 +00002471 }
Sanjay Pateldc65a272016-12-03 17:30:22 +00002472
2473 return nullptr;
2474}
2475
Sanjay Patelbe332132017-01-23 18:22:26 +00002476/// Many binary operators with a constant operand have an easy-to-compute
2477/// range of outputs. This can be used to fold a comparison to always true or
2478/// always false.
Florian Hahn19f9e322018-08-17 14:39:04 +00002479static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper,
2480 const InstrInfoQuery &IIQ) {
Sanjay Patelbe332132017-01-23 18:22:26 +00002481 unsigned Width = Lower.getBitWidth();
2482 const APInt *C;
2483 switch (BO.getOpcode()) {
2484 case Instruction::Add:
Craig Topper73ba1c82017-06-07 07:40:37 +00002485 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
Sanjay Patel56227252017-01-24 17:03:24 +00002486 // FIXME: If we have both nuw and nsw, we should reduce the range further.
Florian Hahn19f9e322018-08-17 14:39:04 +00002487 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
Sanjay Patel56227252017-01-24 17:03:24 +00002488 // 'add nuw x, C' produces [C, UINT_MAX].
2489 Lower = *C;
Florian Hahn19f9e322018-08-17 14:39:04 +00002490 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) {
Sanjay Patel56227252017-01-24 17:03:24 +00002491 if (C->isNegative()) {
2492 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2493 Lower = APInt::getSignedMinValue(Width);
2494 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2495 } else {
2496 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2497 Lower = APInt::getSignedMinValue(Width) + *C;
2498 Upper = APInt::getSignedMaxValue(Width) + 1;
2499 }
2500 }
2501 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002502 break;
2503
2504 case Instruction::And:
2505 if (match(BO.getOperand(1), m_APInt(C)))
2506 // 'and x, C' produces [0, C].
2507 Upper = *C + 1;
2508 break;
2509
2510 case Instruction::Or:
2511 if (match(BO.getOperand(1), m_APInt(C)))
2512 // 'or x, C' produces [C, UINT_MAX].
2513 Lower = *C;
2514 break;
2515
2516 case Instruction::AShr:
2517 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2518 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2519 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2520 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2521 } else if (match(BO.getOperand(0), m_APInt(C))) {
2522 unsigned ShiftAmount = Width - 1;
Florian Hahn19f9e322018-08-17 14:39:04 +00002523 if (!C->isNullValue() && IIQ.isExact(&BO))
Sanjay Patelbe332132017-01-23 18:22:26 +00002524 ShiftAmount = C->countTrailingZeros();
2525 if (C->isNegative()) {
2526 // 'ashr C, x' produces [C, C >> (Width-1)]
2527 Lower = *C;
2528 Upper = C->ashr(ShiftAmount) + 1;
2529 } else {
2530 // 'ashr C, x' produces [C >> (Width-1), C]
2531 Lower = C->ashr(ShiftAmount);
2532 Upper = *C + 1;
2533 }
2534 }
2535 break;
2536
2537 case Instruction::LShr:
2538 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2539 // 'lshr x, C' produces [0, UINT_MAX >> C].
2540 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2541 } else if (match(BO.getOperand(0), m_APInt(C))) {
2542 // 'lshr C, x' produces [C >> (Width-1), C].
2543 unsigned ShiftAmount = Width - 1;
Florian Hahn19f9e322018-08-17 14:39:04 +00002544 if (!C->isNullValue() && IIQ.isExact(&BO))
Sanjay Patelbe332132017-01-23 18:22:26 +00002545 ShiftAmount = C->countTrailingZeros();
2546 Lower = C->lshr(ShiftAmount);
2547 Upper = *C + 1;
2548 }
2549 break;
2550
2551 case Instruction::Shl:
2552 if (match(BO.getOperand(0), m_APInt(C))) {
Florian Hahn19f9e322018-08-17 14:39:04 +00002553 if (IIQ.hasNoUnsignedWrap(&BO)) {
Sanjay Patelbe332132017-01-23 18:22:26 +00002554 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2555 Lower = *C;
2556 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2557 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2558 if (C->isNegative()) {
2559 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2560 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2561 Lower = C->shl(ShiftAmount);
2562 Upper = *C + 1;
2563 } else {
2564 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2565 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2566 Lower = *C;
2567 Upper = C->shl(ShiftAmount) + 1;
2568 }
2569 }
2570 }
2571 break;
2572
2573 case Instruction::SDiv:
2574 if (match(BO.getOperand(1), m_APInt(C))) {
2575 APInt IntMin = APInt::getSignedMinValue(Width);
2576 APInt IntMax = APInt::getSignedMaxValue(Width);
2577 if (C->isAllOnesValue()) {
2578 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2579 // where C != -1 and C != 0 and C != 1
2580 Lower = IntMin + 1;
2581 Upper = IntMax + 1;
2582 } else if (C->countLeadingZeros() < Width - 1) {
2583 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2584 // where C != -1 and C != 0 and C != 1
2585 Lower = IntMin.sdiv(*C);
2586 Upper = IntMax.sdiv(*C);
2587 if (Lower.sgt(Upper))
2588 std::swap(Lower, Upper);
2589 Upper = Upper + 1;
2590 assert(Upper != Lower && "Upper part of range has wrapped!");
2591 }
2592 } else if (match(BO.getOperand(0), m_APInt(C))) {
2593 if (C->isMinSignedValue()) {
2594 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2595 Lower = *C;
2596 Upper = Lower.lshr(1) + 1;
2597 } else {
2598 // 'sdiv C, x' produces [-|C|, |C|].
2599 Upper = C->abs() + 1;
2600 Lower = (-Upper) + 1;
2601 }
2602 }
2603 break;
2604
2605 case Instruction::UDiv:
Craig Topper73ba1c82017-06-07 07:40:37 +00002606 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
Sanjay Patelbe332132017-01-23 18:22:26 +00002607 // 'udiv x, C' produces [0, UINT_MAX / C].
2608 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2609 } else if (match(BO.getOperand(0), m_APInt(C))) {
2610 // 'udiv C, x' produces [0, C].
2611 Upper = *C + 1;
2612 }
2613 break;
2614
2615 case Instruction::SRem:
2616 if (match(BO.getOperand(1), m_APInt(C))) {
2617 // 'srem x, C' produces (-|C|, |C|).
2618 Upper = C->abs();
2619 Lower = (-Upper) + 1;
2620 }
2621 break;
2622
2623 case Instruction::URem:
2624 if (match(BO.getOperand(1), m_APInt(C)))
2625 // 'urem x, C' produces [0, C).
2626 Upper = *C;
2627 break;
2628
2629 default:
2630 break;
2631 }
2632}
2633
Nikita Popov221f3fc2018-12-17 17:45:18 +00002634/// Some intrinsics with a constant operand have an easy-to-compute range of
2635/// outputs. This can be used to fold a comparison to always true or always
2636/// false.
2637static void setLimitsForIntrinsic(IntrinsicInst &II, APInt &Lower,
2638 APInt &Upper) {
2639 unsigned Width = Lower.getBitWidth();
2640 const APInt *C;
2641 switch (II.getIntrinsicID()) {
2642 case Intrinsic::uadd_sat:
2643 // uadd.sat(x, C) produces [C, UINT_MAX].
2644 if (match(II.getOperand(0), m_APInt(C)) ||
2645 match(II.getOperand(1), m_APInt(C)))
2646 Lower = *C;
2647 break;
2648 case Intrinsic::sadd_sat:
2649 if (match(II.getOperand(0), m_APInt(C)) ||
2650 match(II.getOperand(1), m_APInt(C))) {
2651 if (C->isNegative()) {
2652 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
2653 Lower = APInt::getSignedMinValue(Width);
2654 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2655 } else {
2656 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
2657 Lower = APInt::getSignedMinValue(Width) + *C;
2658 Upper = APInt::getSignedMaxValue(Width) + 1;
2659 }
2660 }
2661 break;
2662 case Intrinsic::usub_sat:
2663 // usub.sat(C, x) produces [0, C].
2664 if (match(II.getOperand(0), m_APInt(C)))
2665 Upper = *C + 1;
2666 // usub.sat(x, C) produces [0, UINT_MAX - C].
2667 else if (match(II.getOperand(1), m_APInt(C)))
2668 Upper = APInt::getMaxValue(Width) - *C + 1;
2669 break;
2670 case Intrinsic::ssub_sat:
2671 if (match(II.getOperand(0), m_APInt(C))) {
2672 if (C->isNegative()) {
2673 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
2674 Lower = APInt::getSignedMinValue(Width);
2675 Upper = *C - APInt::getSignedMinValue(Width) + 1;
2676 } else {
2677 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
2678 Lower = *C - APInt::getSignedMaxValue(Width);
2679 Upper = APInt::getSignedMaxValue(Width) + 1;
2680 }
2681 } else if (match(II.getOperand(1), m_APInt(C))) {
2682 if (C->isNegative()) {
2683 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
2684 Lower = APInt::getSignedMinValue(Width) - *C;
2685 Upper = APInt::getSignedMaxValue(Width) + 1;
2686 } else {
2687 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
2688 Lower = APInt::getSignedMinValue(Width);
2689 Upper = APInt::getSignedMaxValue(Width) - *C + 1;
2690 }
2691 }
2692 break;
2693 default:
2694 break;
2695 }
2696}
2697
Sanjay Patel67bde282016-08-22 23:12:02 +00002698static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
Florian Hahn19f9e322018-08-17 14:39:04 +00002699 Value *RHS, const InstrInfoQuery &IIQ) {
Roman Lebedev0c43d722018-03-15 16:17:40 +00002700 Type *ITy = GetCompareTy(RHS); // The return type.
2701
Roman Lebedev6aca3352018-03-15 16:17:46 +00002702 Value *X;
2703 // Sign-bit checks can be optimized to true/false after unsigned
2704 // floating-point casts:
2705 // icmp slt (bitcast (uitofp X)), 0 --> false
2706 // icmp sgt (bitcast (uitofp X)), -1 --> true
2707 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2708 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2709 return ConstantInt::getFalse(ITy);
2710 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2711 return ConstantInt::getTrue(ITy);
2712 }
2713
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002714 const APInt *C;
2715 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002716 return nullptr;
2717
2718 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002719 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002720 if (RHS_CR.isEmptySet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002721 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002722 if (RHS_CR.isFullSet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002723 return ConstantInt::getTrue(ITy);
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002724
Sanjay Patelbe332132017-01-23 18:22:26 +00002725 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002726 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002727 APInt Lower = APInt(Width, 0);
2728 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002729 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
Florian Hahn19f9e322018-08-17 14:39:04 +00002730 setLimitsForBinOp(*BO, Lower, Upper, IIQ);
Nikita Popov221f3fc2018-12-17 17:45:18 +00002731 else if (auto *II = dyn_cast<IntrinsicInst>(LHS))
2732 setLimitsForIntrinsic(*II, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002733
2734 ConstantRange LHS_CR =
2735 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2736
2737 if (auto *I = dyn_cast<Instruction>(LHS))
Florian Hahn19f9e322018-08-17 14:39:04 +00002738 if (auto *Ranges = IIQ.getMetadata(I, LLVMContext::MD_range))
Sanjay Patel67bde282016-08-22 23:12:02 +00002739 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2740
2741 if (!LHS_CR.isFullSet()) {
2742 if (RHS_CR.contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002743 return ConstantInt::getTrue(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002744 if (RHS_CR.inverse().contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002745 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002746 }
2747
2748 return nullptr;
2749}
2750
Sanjay Patel2df38a82017-05-08 16:21:55 +00002751/// TODO: A large part of this logic is duplicated in InstCombine's
2752/// foldICmpBinOp(). We should be able to share that and avoid the code
2753/// duplication.
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002754static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002755 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002756 unsigned MaxRecurse) {
2757 Type *ITy = GetCompareTy(LHS); // The return type.
2758
2759 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2760 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2761 if (MaxRecurse && (LBO || RBO)) {
2762 // Analyze the case when either LHS or RHS is an add instruction.
2763 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2764 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2765 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2766 if (LBO && LBO->getOpcode() == Instruction::Add) {
2767 A = LBO->getOperand(0);
2768 B = LBO->getOperand(1);
2769 NoLHSWrapProblem =
2770 ICmpInst::isEquality(Pred) ||
Florian Hahn19f9e322018-08-17 14:39:04 +00002771 (CmpInst::isUnsigned(Pred) &&
2772 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2773 (CmpInst::isSigned(Pred) &&
2774 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002775 }
2776 if (RBO && RBO->getOpcode() == Instruction::Add) {
2777 C = RBO->getOperand(0);
2778 D = RBO->getOperand(1);
2779 NoRHSWrapProblem =
2780 ICmpInst::isEquality(Pred) ||
Florian Hahn19f9e322018-08-17 14:39:04 +00002781 (CmpInst::isUnsigned(Pred) &&
2782 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2783 (CmpInst::isSigned(Pred) &&
2784 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002785 }
2786
2787 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2788 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2789 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2790 Constant::getNullValue(RHS->getType()), Q,
2791 MaxRecurse - 1))
2792 return V;
2793
2794 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2795 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2796 if (Value *V =
2797 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2798 C == LHS ? D : C, Q, MaxRecurse - 1))
2799 return V;
2800
2801 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2802 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2803 NoRHSWrapProblem) {
2804 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2805 Value *Y, *Z;
2806 if (A == C) {
2807 // C + B == C + D -> B == D
2808 Y = B;
2809 Z = D;
2810 } else if (A == D) {
2811 // D + B == C + D -> B == C
2812 Y = B;
2813 Z = C;
2814 } else if (B == C) {
2815 // A + C == C + D -> A == D
2816 Y = A;
2817 Z = D;
2818 } else {
2819 assert(B == D);
2820 // A + D == C + D -> A == C
2821 Y = A;
2822 Z = C;
2823 }
2824 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2825 return V;
2826 }
2827 }
2828
2829 {
2830 Value *Y = nullptr;
2831 // icmp pred (or X, Y), X
2832 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2833 if (Pred == ICmpInst::ICMP_ULT)
2834 return getFalse(ITy);
2835 if (Pred == ICmpInst::ICMP_UGE)
2836 return getTrue(ITy);
2837
2838 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002839 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2840 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2841 if (RHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002842 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002843 if (RHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002844 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2845 }
2846 }
2847 // icmp pred X, (or X, Y)
2848 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2849 if (Pred == ICmpInst::ICMP_ULE)
2850 return getTrue(ITy);
2851 if (Pred == ICmpInst::ICMP_UGT)
2852 return getFalse(ITy);
2853
2854 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002855 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2856 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2857 if (LHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002858 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002859 if (LHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002860 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2861 }
2862 }
2863 }
2864
2865 // icmp pred (and X, Y), X
Craig Topper72ee6942017-06-24 06:24:01 +00002866 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002867 if (Pred == ICmpInst::ICMP_UGT)
2868 return getFalse(ITy);
2869 if (Pred == ICmpInst::ICMP_ULE)
2870 return getTrue(ITy);
2871 }
2872 // icmp pred X, (and X, Y)
Craig Topper72ee6942017-06-24 06:24:01 +00002873 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002874 if (Pred == ICmpInst::ICMP_UGE)
2875 return getTrue(ITy);
2876 if (Pred == ICmpInst::ICMP_ULT)
2877 return getFalse(ITy);
2878 }
2879
2880 // 0 - (zext X) pred C
2881 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2882 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2883 if (RHSC->getValue().isStrictlyPositive()) {
2884 if (Pred == ICmpInst::ICMP_SLT)
2885 return ConstantInt::getTrue(RHSC->getContext());
2886 if (Pred == ICmpInst::ICMP_SGE)
2887 return ConstantInt::getFalse(RHSC->getContext());
2888 if (Pred == ICmpInst::ICMP_EQ)
2889 return ConstantInt::getFalse(RHSC->getContext());
2890 if (Pred == ICmpInst::ICMP_NE)
2891 return ConstantInt::getTrue(RHSC->getContext());
2892 }
2893 if (RHSC->getValue().isNonNegative()) {
2894 if (Pred == ICmpInst::ICMP_SLE)
2895 return ConstantInt::getTrue(RHSC->getContext());
2896 if (Pred == ICmpInst::ICMP_SGT)
2897 return ConstantInt::getFalse(RHSC->getContext());
2898 }
2899 }
2900 }
2901
2902 // icmp pred (urem X, Y), Y
2903 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002904 switch (Pred) {
2905 default:
2906 break;
2907 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002908 case ICmpInst::ICMP_SGE: {
2909 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2910 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002911 break;
2912 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002913 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002914 case ICmpInst::ICMP_EQ:
2915 case ICmpInst::ICMP_UGT:
2916 case ICmpInst::ICMP_UGE:
2917 return getFalse(ITy);
2918 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002919 case ICmpInst::ICMP_SLE: {
2920 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2921 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002922 break;
2923 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002924 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002925 case ICmpInst::ICMP_NE:
2926 case ICmpInst::ICMP_ULT:
2927 case ICmpInst::ICMP_ULE:
2928 return getTrue(ITy);
2929 }
2930 }
2931
2932 // icmp pred X, (urem Y, X)
2933 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002934 switch (Pred) {
2935 default:
2936 break;
2937 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002938 case ICmpInst::ICMP_SGE: {
2939 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2940 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002941 break;
2942 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002943 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002944 case ICmpInst::ICMP_NE:
2945 case ICmpInst::ICMP_UGT:
2946 case ICmpInst::ICMP_UGE:
2947 return getTrue(ITy);
2948 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002949 case ICmpInst::ICMP_SLE: {
2950 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2951 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002952 break;
2953 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002954 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002955 case ICmpInst::ICMP_EQ:
2956 case ICmpInst::ICMP_ULT:
2957 case ICmpInst::ICMP_ULE:
2958 return getFalse(ITy);
2959 }
2960 }
2961
2962 // x >> y <=u x
2963 // x udiv y <=u x.
2964 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2965 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2966 // icmp pred (X op Y), X
2967 if (Pred == ICmpInst::ICMP_UGT)
2968 return getFalse(ITy);
2969 if (Pred == ICmpInst::ICMP_ULE)
2970 return getTrue(ITy);
2971 }
2972
2973 // x >=u x >> y
2974 // x >=u x udiv y.
2975 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2976 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2977 // icmp pred X, (X op Y)
2978 if (Pred == ICmpInst::ICMP_ULT)
2979 return getFalse(ITy);
2980 if (Pred == ICmpInst::ICMP_UGE)
2981 return getTrue(ITy);
2982 }
2983
2984 // handle:
2985 // CI2 << X == CI
2986 // CI2 << X != CI
2987 //
2988 // where CI2 is a power of 2 and CI isn't
2989 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2990 const APInt *CI2Val, *CIVal = &CI->getValue();
2991 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2992 CI2Val->isPowerOf2()) {
2993 if (!CIVal->isPowerOf2()) {
2994 // CI2 << X can equal zero in some circumstances,
2995 // this simplification is unsafe if CI is zero.
2996 //
2997 // We know it is safe if:
2998 // - The shift is nsw, we can't shift out the one bit.
2999 // - The shift is nuw, we can't shift out the one bit.
3000 // - CI2 is one
3001 // - CI isn't zero
Florian Hahn19f9e322018-08-17 14:39:04 +00003002 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3003 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
Craig Topper73ba1c82017-06-07 07:40:37 +00003004 CI2Val->isOneValue() || !CI->isZero()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003005 if (Pred == ICmpInst::ICMP_EQ)
3006 return ConstantInt::getFalse(RHS->getContext());
3007 if (Pred == ICmpInst::ICMP_NE)
3008 return ConstantInt::getTrue(RHS->getContext());
3009 }
3010 }
Craig Topper73ba1c82017-06-07 07:40:37 +00003011 if (CIVal->isSignMask() && CI2Val->isOneValue()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003012 if (Pred == ICmpInst::ICMP_UGT)
3013 return ConstantInt::getFalse(RHS->getContext());
3014 if (Pred == ICmpInst::ICMP_ULE)
3015 return ConstantInt::getTrue(RHS->getContext());
3016 }
3017 }
3018 }
3019
3020 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
3021 LBO->getOperand(1) == RBO->getOperand(1)) {
3022 switch (LBO->getOpcode()) {
3023 default:
3024 break;
3025 case Instruction::UDiv:
3026 case Instruction::LShr:
Florian Hahn19f9e322018-08-17 14:39:04 +00003027 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3028 !Q.IIQ.isExact(RBO))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003029 break;
Sanjay Patela23b1412017-05-15 19:16:49 +00003030 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3031 RBO->getOperand(0), Q, MaxRecurse - 1))
3032 return V;
3033 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003034 case Instruction::SDiv:
Florian Hahn19f9e322018-08-17 14:39:04 +00003035 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3036 !Q.IIQ.isExact(RBO))
Sanjay Patela23b1412017-05-15 19:16:49 +00003037 break;
3038 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3039 RBO->getOperand(0), Q, MaxRecurse - 1))
3040 return V;
3041 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003042 case Instruction::AShr:
Florian Hahn19f9e322018-08-17 14:39:04 +00003043 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003044 break;
3045 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3046 RBO->getOperand(0), Q, MaxRecurse - 1))
3047 return V;
3048 break;
3049 case Instruction::Shl: {
Florian Hahn19f9e322018-08-17 14:39:04 +00003050 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3051 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003052 if (!NUW && !NSW)
3053 break;
3054 if (!NSW && ICmpInst::isSigned(Pred))
3055 break;
3056 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
3057 RBO->getOperand(0), Q, MaxRecurse - 1))
3058 return V;
3059 break;
3060 }
3061 }
3062 }
3063 return nullptr;
3064}
3065
Sanjay Patel746ebb42018-11-01 14:07:39 +00003066static Value *simplifyICmpWithAbsNabs(CmpInst::Predicate Pred, Value *Op0,
3067 Value *Op1) {
3068 // We need a comparison with a constant.
3069 const APInt *C;
3070 if (!match(Op1, m_APInt(C)))
3071 return nullptr;
3072
3073 // matchSelectPattern returns the negation part of an abs pattern in SP1.
3074 // If the negate has an NSW flag, abs(INT_MIN) is undefined. Without that
3075 // constraint, we can't make a contiguous range for the result of abs.
3076 ICmpInst::Predicate AbsPred = ICmpInst::BAD_ICMP_PREDICATE;
3077 Value *SP0, *SP1;
3078 SelectPatternFlavor SPF = matchSelectPattern(Op0, SP0, SP1).Flavor;
3079 if (SPF == SelectPatternFlavor::SPF_ABS &&
3080 cast<Instruction>(SP1)->hasNoSignedWrap())
3081 // The result of abs(X) is >= 0 (with nsw).
3082 AbsPred = ICmpInst::ICMP_SGE;
3083 if (SPF == SelectPatternFlavor::SPF_NABS)
3084 // The result of -abs(X) is <= 0.
3085 AbsPred = ICmpInst::ICMP_SLE;
3086
3087 if (AbsPred == ICmpInst::BAD_ICMP_PREDICATE)
3088 return nullptr;
3089
3090 // If there is no intersection between abs/nabs and the range of this icmp,
3091 // the icmp must be false. If the abs/nabs range is a subset of the icmp
3092 // range, the icmp must be true.
3093 APInt Zero = APInt::getNullValue(C->getBitWidth());
3094 ConstantRange AbsRange = ConstantRange::makeExactICmpRegion(AbsPred, Zero);
3095 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(Pred, *C);
3096 if (AbsRange.intersectWith(CmpRange).isEmptySet())
3097 return getFalse(GetCompareTy(Op0));
3098 if (CmpRange.contains(AbsRange))
3099 return getTrue(GetCompareTy(Op0));
3100
3101 return nullptr;
3102}
3103
Sanjay Patel35289c62016-12-10 17:40:47 +00003104/// Simplify integer comparisons where at least one operand of the compare
3105/// matches an integer min/max idiom.
3106static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003107 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel35289c62016-12-10 17:40:47 +00003108 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003109 Type *ITy = GetCompareTy(LHS); // The return type.
3110 Value *A, *B;
3111 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3112 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3113
3114 // Signed variants on "max(a,b)>=a -> true".
3115 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3116 if (A != RHS)
3117 std::swap(A, B); // smax(A, B) pred A.
3118 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3119 // We analyze this as smax(A, B) pred A.
3120 P = Pred;
3121 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3122 (A == LHS || B == LHS)) {
3123 if (A != LHS)
3124 std::swap(A, B); // A pred smax(A, B).
3125 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3126 // We analyze this as smax(A, B) swapped-pred A.
3127 P = CmpInst::getSwappedPredicate(Pred);
3128 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3129 (A == RHS || B == RHS)) {
3130 if (A != RHS)
3131 std::swap(A, B); // smin(A, B) pred A.
3132 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3133 // We analyze this as smax(-A, -B) swapped-pred -A.
3134 // Note that we do not need to actually form -A or -B thanks to EqP.
3135 P = CmpInst::getSwappedPredicate(Pred);
3136 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3137 (A == LHS || B == LHS)) {
3138 if (A != LHS)
3139 std::swap(A, B); // A pred smin(A, B).
3140 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3141 // We analyze this as smax(-A, -B) pred -A.
3142 // Note that we do not need to actually form -A or -B thanks to EqP.
3143 P = Pred;
3144 }
3145 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3146 // Cases correspond to "max(A, B) p A".
3147 switch (P) {
3148 default:
3149 break;
3150 case CmpInst::ICMP_EQ:
3151 case CmpInst::ICMP_SLE:
3152 // Equivalent to "A EqP B". This may be the same as the condition tested
3153 // in the max/min; if so, we can just return that.
3154 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3155 return V;
3156 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3157 return V;
3158 // Otherwise, see if "A EqP B" simplifies.
3159 if (MaxRecurse)
3160 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3161 return V;
3162 break;
3163 case CmpInst::ICMP_NE:
3164 case CmpInst::ICMP_SGT: {
3165 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3166 // Equivalent to "A InvEqP B". This may be the same as the condition
3167 // tested in the max/min; if so, we can just return that.
3168 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3169 return V;
3170 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3171 return V;
3172 // Otherwise, see if "A InvEqP B" simplifies.
3173 if (MaxRecurse)
3174 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3175 return V;
3176 break;
3177 }
3178 case CmpInst::ICMP_SGE:
3179 // Always true.
3180 return getTrue(ITy);
3181 case CmpInst::ICMP_SLT:
3182 // Always false.
3183 return getFalse(ITy);
3184 }
3185 }
3186
3187 // Unsigned variants on "max(a,b)>=a -> true".
3188 P = CmpInst::BAD_ICMP_PREDICATE;
3189 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3190 if (A != RHS)
3191 std::swap(A, B); // umax(A, B) pred A.
3192 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3193 // We analyze this as umax(A, B) pred A.
3194 P = Pred;
3195 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3196 (A == LHS || B == LHS)) {
3197 if (A != LHS)
3198 std::swap(A, B); // A pred umax(A, B).
3199 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3200 // We analyze this as umax(A, B) swapped-pred A.
3201 P = CmpInst::getSwappedPredicate(Pred);
3202 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3203 (A == RHS || B == RHS)) {
3204 if (A != RHS)
3205 std::swap(A, B); // umin(A, B) pred A.
3206 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3207 // We analyze this as umax(-A, -B) swapped-pred -A.
3208 // Note that we do not need to actually form -A or -B thanks to EqP.
3209 P = CmpInst::getSwappedPredicate(Pred);
3210 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3211 (A == LHS || B == LHS)) {
3212 if (A != LHS)
3213 std::swap(A, B); // A pred umin(A, B).
3214 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3215 // We analyze this as umax(-A, -B) pred -A.
3216 // Note that we do not need to actually form -A or -B thanks to EqP.
3217 P = Pred;
3218 }
3219 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3220 // Cases correspond to "max(A, B) p A".
3221 switch (P) {
3222 default:
3223 break;
3224 case CmpInst::ICMP_EQ:
3225 case CmpInst::ICMP_ULE:
3226 // Equivalent to "A EqP B". This may be the same as the condition tested
3227 // in the max/min; if so, we can just return that.
3228 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3229 return V;
3230 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3231 return V;
3232 // Otherwise, see if "A EqP B" simplifies.
3233 if (MaxRecurse)
3234 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3235 return V;
3236 break;
3237 case CmpInst::ICMP_NE:
3238 case CmpInst::ICMP_UGT: {
3239 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3240 // Equivalent to "A InvEqP B". This may be the same as the condition
3241 // tested in the max/min; if so, we can just return that.
3242 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3243 return V;
3244 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3245 return V;
3246 // Otherwise, see if "A InvEqP B" simplifies.
3247 if (MaxRecurse)
3248 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3249 return V;
3250 break;
3251 }
3252 case CmpInst::ICMP_UGE:
3253 // Always true.
3254 return getTrue(ITy);
3255 case CmpInst::ICMP_ULT:
3256 // Always false.
3257 return getFalse(ITy);
3258 }
3259 }
3260
3261 // Variants on "max(x,y) >= min(x,z)".
3262 Value *C, *D;
3263 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3264 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3265 (A == C || A == D || B == C || B == D)) {
3266 // max(x, ?) pred min(x, ?).
3267 if (Pred == CmpInst::ICMP_SGE)
3268 // Always true.
3269 return getTrue(ITy);
3270 if (Pred == CmpInst::ICMP_SLT)
3271 // Always false.
3272 return getFalse(ITy);
3273 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3274 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3275 (A == C || A == D || B == C || B == D)) {
3276 // min(x, ?) pred max(x, ?).
3277 if (Pred == CmpInst::ICMP_SLE)
3278 // Always true.
3279 return getTrue(ITy);
3280 if (Pred == CmpInst::ICMP_SGT)
3281 // Always false.
3282 return getFalse(ITy);
3283 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3284 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3285 (A == C || A == D || B == C || B == D)) {
3286 // max(x, ?) pred min(x, ?).
3287 if (Pred == CmpInst::ICMP_UGE)
3288 // Always true.
3289 return getTrue(ITy);
3290 if (Pred == CmpInst::ICMP_ULT)
3291 // Always false.
3292 return getFalse(ITy);
3293 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3294 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3295 (A == C || A == D || B == C || B == D)) {
3296 // min(x, ?) pred max(x, ?).
3297 if (Pred == CmpInst::ICMP_ULE)
3298 // Always true.
3299 return getTrue(ITy);
3300 if (Pred == CmpInst::ICMP_UGT)
3301 // Always false.
3302 return getFalse(ITy);
3303 }
3304
3305 return nullptr;
3306}
3307
Sanjay Patel472cc782016-01-11 22:14:42 +00003308/// Given operands for an ICmpInst, see if we can fold the result.
3309/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003310static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003311 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003312 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003313 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003314
Chris Lattnera71e9d62009-11-10 00:55:12 +00003315 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003316 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003317 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003318
3319 // If we have a constant, make sure it is on the RHS.
3320 std::swap(LHS, RHS);
3321 Pred = CmpInst::getSwappedPredicate(Pred);
3322 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003323
Chris Lattner229907c2011-07-18 04:54:35 +00003324 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003325
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003326 // icmp X, X -> true/false
Sanjay Patel30be6652018-04-22 17:07:44 +00003327 // icmp X, undef -> true/false because undef could be X.
Duncan Sands772749a2011-01-01 20:08:02 +00003328 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003329 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003330
Sanjay Pateldc65a272016-12-03 17:30:22 +00003331 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3332 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003333
Sanjay Pateldc65a272016-12-03 17:30:22 +00003334 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3335 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003336
Florian Hahn19f9e322018-08-17 14:39:04 +00003337 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
Sanjay Patel67bde282016-08-22 23:12:02 +00003338 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003339
Chen Li7452d952015-09-26 03:26:47 +00003340 // If both operands have range metadata, use the metadata
3341 // to simplify the comparison.
3342 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
Craig Topper0c198612017-04-10 19:37:10 +00003343 auto RHS_Instr = cast<Instruction>(RHS);
3344 auto LHS_Instr = cast<Instruction>(LHS);
Chen Li7452d952015-09-26 03:26:47 +00003345
Florian Hahn19f9e322018-08-17 14:39:04 +00003346 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3347 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003348 auto RHS_CR = getConstantRangeFromMetadata(
3349 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3350 auto LHS_CR = getConstantRangeFromMetadata(
3351 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003352
3353 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3354 if (Satisfied_CR.contains(LHS_CR))
3355 return ConstantInt::getTrue(RHS->getContext());
3356
3357 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3358 CmpInst::getInversePredicate(Pred), RHS_CR);
3359 if (InversedSatisfied_CR.contains(LHS_CR))
3360 return ConstantInt::getFalse(RHS->getContext());
3361 }
3362 }
3363
Duncan Sands8fb2c382011-01-20 13:21:55 +00003364 // Compare of cast, for example (zext X) != 0 -> X != 0
3365 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3366 Instruction *LI = cast<CastInst>(LHS);
3367 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003368 Type *SrcTy = SrcOp->getType();
3369 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003370
3371 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3372 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003373 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3374 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003375 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3376 // Transfer the cast to the constant.
3377 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3378 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003379 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003380 return V;
3381 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3382 if (RI->getOperand(0)->getType() == SrcTy)
3383 // Compare without the cast.
3384 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003385 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003386 return V;
3387 }
3388 }
3389
3390 if (isa<ZExtInst>(LHS)) {
3391 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3392 // same type.
3393 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3394 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3395 // Compare X and Y. Note that signed predicates become unsigned.
3396 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003397 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003398 MaxRecurse-1))
3399 return V;
3400 }
3401 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3402 // too. If not, then try to deduce the result of the comparison.
3403 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3404 // Compute the constant that would happen if we truncated to SrcTy then
3405 // reextended to DstTy.
3406 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3407 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3408
3409 // If the re-extended constant didn't change then this is effectively
3410 // also a case of comparing two zero-extended values.
3411 if (RExt == CI && MaxRecurse)
3412 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003413 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003414 return V;
3415
3416 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3417 // there. Use this to work out the result of the comparison.
3418 if (RExt != CI) {
3419 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003420 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003421 // LHS <u RHS.
3422 case ICmpInst::ICMP_EQ:
3423 case ICmpInst::ICMP_UGT:
3424 case ICmpInst::ICMP_UGE:
3425 return ConstantInt::getFalse(CI->getContext());
3426
3427 case ICmpInst::ICMP_NE:
3428 case ICmpInst::ICMP_ULT:
3429 case ICmpInst::ICMP_ULE:
3430 return ConstantInt::getTrue(CI->getContext());
3431
3432 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3433 // is non-negative then LHS <s RHS.
3434 case ICmpInst::ICMP_SGT:
3435 case ICmpInst::ICMP_SGE:
3436 return CI->getValue().isNegative() ?
3437 ConstantInt::getTrue(CI->getContext()) :
3438 ConstantInt::getFalse(CI->getContext());
3439
3440 case ICmpInst::ICMP_SLT:
3441 case ICmpInst::ICMP_SLE:
3442 return CI->getValue().isNegative() ?
3443 ConstantInt::getFalse(CI->getContext()) :
3444 ConstantInt::getTrue(CI->getContext());
3445 }
3446 }
3447 }
3448 }
3449
3450 if (isa<SExtInst>(LHS)) {
3451 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3452 // same type.
3453 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3454 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3455 // Compare X and Y. Note that the predicate does not change.
3456 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003457 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003458 return V;
3459 }
3460 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3461 // too. If not, then try to deduce the result of the comparison.
3462 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3463 // Compute the constant that would happen if we truncated to SrcTy then
3464 // reextended to DstTy.
3465 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3466 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3467
3468 // If the re-extended constant didn't change then this is effectively
3469 // also a case of comparing two sign-extended values.
3470 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003471 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003472 return V;
3473
3474 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3475 // bits there. Use this to work out the result of the comparison.
3476 if (RExt != CI) {
3477 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003478 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003479 case ICmpInst::ICMP_EQ:
3480 return ConstantInt::getFalse(CI->getContext());
3481 case ICmpInst::ICMP_NE:
3482 return ConstantInt::getTrue(CI->getContext());
3483
3484 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3485 // LHS >s RHS.
3486 case ICmpInst::ICMP_SGT:
3487 case ICmpInst::ICMP_SGE:
3488 return CI->getValue().isNegative() ?
3489 ConstantInt::getTrue(CI->getContext()) :
3490 ConstantInt::getFalse(CI->getContext());
3491 case ICmpInst::ICMP_SLT:
3492 case ICmpInst::ICMP_SLE:
3493 return CI->getValue().isNegative() ?
3494 ConstantInt::getFalse(CI->getContext()) :
3495 ConstantInt::getTrue(CI->getContext());
3496
3497 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3498 // LHS >u RHS.
3499 case ICmpInst::ICMP_UGT:
3500 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003501 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003502 if (MaxRecurse)
3503 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3504 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003505 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003506 return V;
3507 break;
3508 case ICmpInst::ICMP_ULT:
3509 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003510 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003511 if (MaxRecurse)
3512 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3513 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003514 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003515 return V;
3516 break;
3517 }
3518 }
3519 }
3520 }
3521 }
3522
James Molloy1d88d6f2015-10-22 13:18:42 +00003523 // icmp eq|ne X, Y -> false|true if X != Y
Craig Topperc2790ec2017-06-06 07:13:04 +00003524 if (ICmpInst::isEquality(Pred) &&
Florian Hahn19f9e322018-08-17 14:39:04 +00003525 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
Craig Topper2dfb4802017-06-06 07:13:13 +00003526 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
James Molloy1d88d6f2015-10-22 13:18:42 +00003527 }
Junmo Park53470fc2016-04-05 21:14:31 +00003528
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003529 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3530 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003531
Sanjay Patel35289c62016-12-10 17:40:47 +00003532 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003533 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003534
Sanjay Patel746ebb42018-11-01 14:07:39 +00003535 if (Value *V = simplifyICmpWithAbsNabs(Pred, LHS, RHS))
3536 return V;
3537
Chandler Carruth8059c842012-03-25 21:28:14 +00003538 // Simplify comparisons of related pointers using a powerful, recursive
3539 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003540 if (LHS->getType()->isPointerTy())
Florian Hahn19f9e322018-08-17 14:39:04 +00003541 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3542 Q.IIQ, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003543 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003544 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3545 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3546 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3547 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3548 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3549 Q.DL.getTypeSizeInBits(CRHS->getType()))
Nuno Lopes404f1062017-09-09 18:23:11 +00003550 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
Florian Hahn19f9e322018-08-17 14:39:04 +00003551 Q.IIQ, CLHS->getPointerOperand(),
David Majnemerdc8767a2016-08-07 07:58:10 +00003552 CRHS->getPointerOperand()))
3553 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003554
Nick Lewycky3db143e2012-02-26 02:09:49 +00003555 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3556 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3557 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3558 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3559 (ICmpInst::isEquality(Pred) ||
3560 (GLHS->isInBounds() && GRHS->isInBounds() &&
3561 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3562 // The bases are equal and the indices are constant. Build a constant
3563 // expression GEP with the same indices and a null base pointer to see
3564 // what constant folding can make out of it.
3565 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3566 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003567 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3568 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003569
3570 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003571 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3572 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003573 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3574 }
3575 }
3576 }
3577
Duncan Sandsf532d312010-11-07 16:12:23 +00003578 // If the comparison is with the result of a select instruction, check whether
3579 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003580 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003581 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003582 return V;
3583
3584 // If the comparison is with the result of a phi instruction, check whether
3585 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003586 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003587 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003588 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003589
Craig Topper9f008862014-04-15 04:59:12 +00003590 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003591}
3592
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003593Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003594 const SimplifyQuery &Q) {
3595 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3596}
3597
Sanjay Patel472cc782016-01-11 22:14:42 +00003598/// Given operands for an FCmpInst, see if we can fold the result.
3599/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003600static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003601 FastMathFlags FMF, const SimplifyQuery &Q,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003602 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003603 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3604 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3605
Chris Lattnera71e9d62009-11-10 00:55:12 +00003606 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003607 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003608 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003609
Chris Lattnera71e9d62009-11-10 00:55:12 +00003610 // If we have a constant, make sure it is on the RHS.
3611 std::swap(LHS, RHS);
3612 Pred = CmpInst::getSwappedPredicate(Pred);
3613 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003614
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003615 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003616 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003617 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003618 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003619 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003620 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003621
Sanjay Patelf3ae9cc2018-08-21 14:45:13 +00003622 // Fold (un)ordered comparison if we can determine there are no NaNs.
3623 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3624 if (FMF.noNaNs() ||
3625 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3626 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003627
Sanjay Patel46b083e2018-03-02 18:36:08 +00003628 // NaN is unordered; NaN is not ordered.
3629 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3630 "Comparison must be either ordered or unordered");
3631 if (match(RHS, m_NaN()))
3632 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3633
Mehdi Aminieb242a52015-03-09 03:20:25 +00003634 // fcmp pred x, undef and fcmp pred undef, x
3635 // fold to true if unordered, false if ordered
3636 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3637 // Choosing NaN for the undef will always make unordered comparison succeed
3638 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003639 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003640 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003641
3642 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003643 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003644 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003645 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003646 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003647 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003648 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003649
Sanjay Patel4ca99682017-11-27 16:37:09 +00003650 // Handle fcmp with constant RHS.
Sanjay Patel68171e32019-02-20 14:34:00 +00003651 // TODO: Use match with a specific FP value, so these work with vectors with
3652 // undef lanes.
Sanjay Patel4ca99682017-11-27 16:37:09 +00003653 const APFloat *C;
3654 if (match(RHS, m_APFloat(C))) {
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003655 // Check whether the constant is an infinity.
Sanjay Patel4ca99682017-11-27 16:37:09 +00003656 if (C->isInfinity()) {
3657 if (C->isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003658 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003659 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003660 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003661 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003662 case FCmpInst::FCMP_UGE:
3663 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003664 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003665 default:
3666 break;
3667 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003668 } else {
3669 switch (Pred) {
3670 case FCmpInst::FCMP_OGT:
3671 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003672 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003673 case FCmpInst::FCMP_ULE:
3674 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003675 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003676 default:
3677 break;
3678 }
3679 }
Sanjay Patel49f97392019-02-20 00:20:38 +00003680 }
Sanjay Patel68171e32019-02-20 14:34:00 +00003681 if (C->isNegative() && !C->isNegZero()) {
Florian Hahn30932a32017-12-01 12:34:16 +00003682 assert(!C->isNaN() && "Unexpected NaN constant!");
3683 // TODO: We can catch more cases by using a range check rather than
3684 // relying on CannotBeOrderedLessThanZero.
3685 switch (Pred) {
3686 case FCmpInst::FCMP_UGE:
3687 case FCmpInst::FCMP_UGT:
3688 case FCmpInst::FCMP_UNE:
3689 // (X >= 0) implies (X > C) when (C < 0)
3690 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3691 return getTrue(RetTy);
3692 break;
3693 case FCmpInst::FCMP_OEQ:
3694 case FCmpInst::FCMP_OLE:
3695 case FCmpInst::FCMP_OLT:
3696 // (X >= 0) implies !(X < C) when (C < 0)
3697 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3698 return getFalse(RetTy);
3699 break;
3700 default:
3701 break;
3702 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003703 }
3704 }
Sanjay Patel68171e32019-02-20 14:34:00 +00003705 if (match(RHS, m_AnyZeroFP())) {
3706 switch (Pred) {
3707 case FCmpInst::FCMP_OGE:
3708 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3709 return getTrue(RetTy);
3710 break;
3711 case FCmpInst::FCMP_UGE:
3712 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3713 return getTrue(RetTy);
3714 break;
3715 case FCmpInst::FCMP_ULT:
3716 if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI))
3717 return getFalse(RetTy);
3718 break;
3719 case FCmpInst::FCMP_OLT:
3720 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3721 return getFalse(RetTy);
3722 break;
3723 default:
3724 break;
3725 }
3726 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003727
Duncan Sandsa620bd12010-11-07 16:46:25 +00003728 // If the comparison is with the result of a select instruction, check whether
3729 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003730 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003731 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003732 return V;
3733
3734 // If the comparison is with the result of a phi instruction, check whether
3735 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003736 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003737 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003738 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003739
Craig Topper9f008862014-04-15 04:59:12 +00003740 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003741}
3742
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003743Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003744 FastMathFlags FMF, const SimplifyQuery &Q) {
3745 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003746}
3747
Sanjay Patel472cc782016-01-11 22:14:42 +00003748/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003749static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003750 const SimplifyQuery &Q,
David Majnemer3f0fb982015-06-06 22:40:21 +00003751 unsigned MaxRecurse) {
3752 // Trivial replacement.
3753 if (V == Op)
3754 return RepOp;
3755
Tim Northover997f5f12017-05-22 21:28:08 +00003756 // We cannot replace a constant, and shouldn't even try.
3757 if (isa<Constant>(Op))
3758 return nullptr;
3759
David Majnemer3f0fb982015-06-06 22:40:21 +00003760 auto *I = dyn_cast<Instruction>(V);
3761 if (!I)
3762 return nullptr;
3763
3764 // If this is a binary operator, try to simplify it with the replaced op.
3765 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3766 // Consider:
3767 // %cmp = icmp eq i32 %x, 2147483647
3768 // %add = add nsw i32 %x, 1
3769 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3770 //
3771 // We can't replace %sel with %add unless we strip away the flags.
3772 if (isa<OverflowingBinaryOperator>(B))
Florian Hahn19f9e322018-08-17 14:39:04 +00003773 if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
David Majnemer3f0fb982015-06-06 22:40:21 +00003774 return nullptr;
Florian Hahn19f9e322018-08-17 14:39:04 +00003775 if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3776 return nullptr;
David Majnemer3f0fb982015-06-06 22:40:21 +00003777
3778 if (MaxRecurse) {
3779 if (B->getOperand(0) == Op)
3780 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3781 MaxRecurse - 1);
3782 if (B->getOperand(1) == Op)
3783 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3784 MaxRecurse - 1);
3785 }
3786 }
3787
3788 // Same for CmpInsts.
3789 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3790 if (MaxRecurse) {
3791 if (C->getOperand(0) == Op)
3792 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3793 MaxRecurse - 1);
3794 if (C->getOperand(1) == Op)
3795 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3796 MaxRecurse - 1);
3797 }
3798 }
3799
George Burgess IV8e807bf2018-04-24 00:25:01 +00003800 // Same for GEPs.
3801 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3802 if (MaxRecurse) {
3803 SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3804 transform(GEP->operands(), NewOps.begin(),
3805 [&](Value *V) { return V == Op ? RepOp : V; });
3806 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3807 MaxRecurse - 1);
3808 }
3809 }
3810
David Majnemer3f0fb982015-06-06 22:40:21 +00003811 // TODO: We could hand off more cases to instsimplify here.
3812
3813 // If all operands are constant after substituting Op for RepOp then we can
3814 // constant fold the instruction.
3815 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3816 // Build a list of all constant operands.
3817 SmallVector<Constant *, 8> ConstOps;
3818 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3819 if (I->getOperand(i) == Op)
3820 ConstOps.push_back(CRepOp);
3821 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3822 ConstOps.push_back(COp);
3823 else
3824 break;
3825 }
3826
3827 // All operands were constants, fold it.
3828 if (ConstOps.size() == I->getNumOperands()) {
3829 if (CmpInst *C = dyn_cast<CmpInst>(I))
3830 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3831 ConstOps[1], Q.DL, Q.TLI);
3832
3833 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3834 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003835 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003836
Manuel Jacobe9024592016-01-21 06:33:22 +00003837 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003838 }
3839 }
3840
3841 return nullptr;
3842}
3843
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003844/// Try to simplify a select instruction when its condition operand is an
3845/// integer comparison where one operand of the compare is a constant.
3846static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3847 const APInt *Y, bool TrueWhenUnset) {
3848 const APInt *C;
3849
3850 // (X & Y) == 0 ? X & ~Y : X --> X
3851 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3852 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3853 *Y == ~*C)
3854 return TrueWhenUnset ? FalseVal : TrueVal;
3855
3856 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3857 // (X & Y) != 0 ? X : X & ~Y --> X
3858 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3859 *Y == ~*C)
3860 return TrueWhenUnset ? FalseVal : TrueVal;
3861
3862 if (Y->isPowerOf2()) {
3863 // (X & Y) == 0 ? X | Y : X --> X | Y
3864 // (X & Y) != 0 ? X | Y : X --> X
3865 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3866 *Y == *C)
3867 return TrueWhenUnset ? TrueVal : FalseVal;
3868
3869 // (X & Y) == 0 ? X : X | Y --> X
3870 // (X & Y) != 0 ? X : X | Y --> X | Y
3871 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3872 *Y == *C)
3873 return TrueWhenUnset ? TrueVal : FalseVal;
3874 }
Matt Arsenault82606662017-01-11 00:57:54 +00003875
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003876 return nullptr;
3877}
3878
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003879/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3880/// eq/ne.
Craig Topper0aa3a192017-08-14 21:39:51 +00003881static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3882 ICmpInst::Predicate Pred,
3883 Value *TrueVal, Value *FalseVal) {
3884 Value *X;
3885 APInt Mask;
3886 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3887 return nullptr;
3888
Craig Topper0aa3a192017-08-14 21:39:51 +00003889 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3890 Pred == ICmpInst::ICMP_EQ);
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003891}
3892
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003893/// Try to simplify a select instruction when its condition operand is an
3894/// integer comparison.
3895static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003896 Value *FalseVal, const SimplifyQuery &Q,
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003897 unsigned MaxRecurse) {
3898 ICmpInst::Predicate Pred;
3899 Value *CmpLHS, *CmpRHS;
3900 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3901 return nullptr;
3902
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003903 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3904 Value *X;
3905 const APInt *Y;
3906 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3907 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3908 Pred == ICmpInst::ICMP_EQ))
3909 return V;
Sanjay Patele98ec772018-11-15 14:53:37 +00003910
3911 // Test for zero-shift-guard-ops around funnel shifts. These are used to
3912 // avoid UB from oversized shifts in raw IR rotate patterns, but the
3913 // intrinsics do not have that problem.
3914 Value *ShAmt;
3915 auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3916 m_Value(ShAmt)),
3917 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3918 m_Value(ShAmt)));
3919 // (ShAmt != 0) ? fshl(X, *, ShAmt) : X --> fshl(X, *, ShAmt)
3920 // (ShAmt != 0) ? fshr(*, X, ShAmt) : X --> fshr(*, X, ShAmt)
3921 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3922 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3923 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
3924 return Pred == ICmpInst::ICMP_NE ? TrueVal : X;
3925
3926 // (ShAmt == 0) ? X : fshl(X, *, ShAmt) --> fshl(X, *, ShAmt)
3927 // (ShAmt == 0) ? X : fshr(*, X, ShAmt) --> fshr(*, X, ShAmt)
3928 // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3929 // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3930 if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt)
3931 return Pred == ICmpInst::ICMP_EQ ? FalseVal : X;
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003932 }
3933
Craig Topper0aa3a192017-08-14 21:39:51 +00003934 // Check for other compares that behave like bit test.
3935 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3936 TrueVal, FalseVal))
3937 return V;
3938
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003939 // If we have an equality comparison, then we know the value in one of the
3940 // arms of the select. See if substituting this value into the arm and
3941 // simplifying the result yields the same value as the other arm.
3942 if (Pred == ICmpInst::ICMP_EQ) {
3943 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3944 TrueVal ||
3945 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3946 TrueVal)
3947 return FalseVal;
3948 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3949 FalseVal ||
3950 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3951 FalseVal)
3952 return FalseVal;
3953 } else if (Pred == ICmpInst::ICMP_NE) {
3954 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3955 FalseVal ||
3956 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3957 FalseVal)
3958 return TrueVal;
3959 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3960 TrueVal ||
3961 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3962 TrueVal)
3963 return TrueVal;
3964 }
3965
3966 return nullptr;
3967}
3968
Sanjay Patel14401072018-11-05 21:51:39 +00003969/// Try to simplify a select instruction when its condition operand is a
3970/// floating-point comparison.
3971static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) {
3972 FCmpInst::Predicate Pred;
3973 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3974 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3975 return nullptr;
3976
3977 // TODO: The transform may not be valid with -0.0. An incomplete way of
3978 // testing for that possibility is to check if at least one operand is a
3979 // non-zero constant.
3980 const APFloat *C;
3981 if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3982 (match(F, m_APFloat(C)) && C->isNonZero())) {
3983 // (T == F) ? T : F --> F
3984 // (F == T) ? T : F --> F
3985 if (Pred == FCmpInst::FCMP_OEQ)
3986 return F;
3987
3988 // (T != F) ? T : F --> T
3989 // (F != T) ? T : F --> T
3990 if (Pred == FCmpInst::FCMP_UNE)
3991 return T;
3992 }
3993
3994 return nullptr;
3995}
3996
Sanjay Patel472cc782016-01-11 22:14:42 +00003997/// Given operands for a SelectInst, see if we can fold the result.
3998/// If not, this returns null.
Sanjay Patelac395202018-02-17 14:50:13 +00003999static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4000 const SimplifyQuery &Q, unsigned MaxRecurse) {
4001 if (auto *CondC = dyn_cast<Constant>(Cond)) {
4002 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4003 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4004 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
4005
4006 // select undef, X, Y -> X or Y
4007 if (isa<UndefValue>(CondC))
4008 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4009
4010 // TODO: Vector constants with undef elements don't simplify.
4011
4012 // select true, X, Y -> X
4013 if (CondC->isAllOnesValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00004014 return TrueVal;
Sanjay Patelac395202018-02-17 14:50:13 +00004015 // select false, X, Y -> Y
4016 if (CondC->isNullValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00004017 return FalseVal;
4018 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004019
Sanjay Patelac395202018-02-17 14:50:13 +00004020 // select ?, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00004021 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00004022 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00004023
Sanjay Patelac395202018-02-17 14:50:13 +00004024 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00004025 return FalseVal;
Sanjay Patelac395202018-02-17 14:50:13 +00004026 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00004027 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00004028
Sanjay Patel5f5eb582016-07-18 20:56:53 +00004029 if (Value *V =
Sanjay Patelac395202018-02-17 14:50:13 +00004030 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00004031 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00004032
Sanjay Patel14401072018-11-05 21:51:39 +00004033 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
4034 return V;
4035
David Bolvanskyf9476082018-07-28 06:55:51 +00004036 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4037 return V;
4038
Sanjay Patel7d82d372018-12-02 13:26:03 +00004039 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4040 if (Imp)
4041 return *Imp ? TrueVal : FalseVal;
Sanjay Pateld8022702018-11-29 18:44:39 +00004042
Craig Topper9f008862014-04-15 04:59:12 +00004043 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004044}
4045
Duncan Sandsb8cee002012-03-13 11:42:19 +00004046Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004047 const SimplifyQuery &Q) {
4048 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004049}
4050
Sanjay Patel472cc782016-01-11 22:14:42 +00004051/// Given operands for an GetElementPtrInst, see if we can fold the result.
4052/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00004053static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004054 const SimplifyQuery &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00004055 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00004056 unsigned AS =
4057 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00004058
Chris Lattner8574aba2009-11-27 00:29:05 +00004059 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00004060 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00004061 return Ops[0];
4062
Nico Weber48c82402014-08-27 20:06:19 +00004063 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00004064 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00004065 Type *GEPTy = PointerType::get(LastType, AS);
4066 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
4067 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Davide Italianoa9f047a2017-04-19 14:23:42 +00004068 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
4069 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Nico Weber48c82402014-08-27 20:06:19 +00004070
4071 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00004072 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00004073
Jay Foadb992a632011-07-19 15:07:52 +00004074 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00004075 // getelementptr P, 0 -> P.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00004076 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00004077 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00004078
David Blaikie4a2e73b2015-04-02 18:55:32 +00004079 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004080 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00004081 Value *P;
4082 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004083 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00004084 // getelementptr P, N -> P if P points to a type of zero size.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00004085 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00004086 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00004087
4088 // The following transforms are only safe if the ptrtoint cast
4089 // doesn't truncate the pointers.
4090 if (Ops[1]->getType()->getScalarSizeInBits() ==
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004091 Q.DL.getIndexSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00004092 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
4093 if (match(P, m_Zero()))
4094 return Constant::getNullValue(GEPTy);
4095 Value *Temp;
4096 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00004097 if (Temp->getType() == GEPTy)
4098 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00004099 return nullptr;
4100 };
4101
4102 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4103 if (TyAllocSize == 1 &&
4104 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4105 if (Value *R = PtrToIntOrZero(P))
4106 return R;
4107
4108 // getelementptr V, (ashr (sub P, V), C) -> Q
4109 // if P points to a type of size 1 << C.
4110 if (match(Ops[1],
4111 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4112 m_ConstantInt(C))) &&
4113 TyAllocSize == 1ULL << C)
4114 if (Value *R = PtrToIntOrZero(P))
4115 return R;
4116
4117 // getelementptr V, (sdiv (sub P, V), C) -> Q
4118 // if P points to a type of size C.
4119 if (match(Ops[1],
4120 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4121 m_SpecificInt(TyAllocSize))))
4122 if (Value *R = PtrToIntOrZero(P))
4123 return R;
4124 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00004125 }
4126 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004127
David Majnemerd1501372016-08-07 07:58:12 +00004128 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
4129 all_of(Ops.slice(1).drop_back(1),
4130 [](Value *Idx) { return match(Idx, m_Zero()); })) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004131 unsigned IdxWidth =
4132 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4133 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4134 APInt BasePtrOffset(IdxWidth, 0);
David Majnemerd1501372016-08-07 07:58:12 +00004135 Value *StrippedBasePtr =
4136 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4137 BasePtrOffset);
4138
David Majnemer5c5df622016-08-16 06:13:46 +00004139 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00004140 if (match(Ops.back(),
4141 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
4142 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4143 return ConstantExpr::getIntToPtr(CI, GEPTy);
4144 }
David Majnemer5c5df622016-08-16 06:13:46 +00004145 // gep (gep V, C), (xor V, -1) -> C-1
4146 if (match(Ops.back(),
4147 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
4148 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4149 return ConstantExpr::getIntToPtr(CI, GEPTy);
4150 }
David Majnemerd1501372016-08-07 07:58:12 +00004151 }
4152 }
4153
Chris Lattner8574aba2009-11-27 00:29:05 +00004154 // Check to see if this is constant foldable.
Craig Topperda8037f2017-06-04 22:41:56 +00004155 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4156 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00004157
Joey Gouly61eaa632017-06-06 10:17:14 +00004158 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4159 Ops.slice(1));
4160 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
4161 return CEFolded;
4162 return CE;
Chris Lattner8574aba2009-11-27 00:29:05 +00004163}
4164
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004165Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004166 const SimplifyQuery &Q) {
4167 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004168}
4169
Sanjay Patel472cc782016-01-11 22:14:42 +00004170/// Given operands for an InsertValueInst, see if we can fold the result.
4171/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004172static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004173 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004174 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00004175 if (Constant *CAgg = dyn_cast<Constant>(Agg))
4176 if (Constant *CVal = dyn_cast<Constant>(Val))
4177 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4178
4179 // insertvalue x, undef, n -> x
4180 if (match(Val, m_Undef()))
4181 return Agg;
4182
4183 // insertvalue x, (extractvalue y, n), n
4184 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00004185 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4186 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00004187 // insertvalue undef, (extractvalue y, n), n -> y
4188 if (match(Agg, m_Undef()))
4189 return EV->getAggregateOperand();
4190
4191 // insertvalue y, (extractvalue y, n), n -> y
4192 if (Agg == EV->getAggregateOperand())
4193 return Agg;
4194 }
4195
Craig Topper9f008862014-04-15 04:59:12 +00004196 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00004197}
4198
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004199Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
4200 ArrayRef<unsigned> Idxs,
4201 const SimplifyQuery &Q) {
4202 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
4203}
4204
Igor Laevskye0edb662017-12-13 11:21:18 +00004205Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
4206 const SimplifyQuery &Q) {
4207 // Try to constant fold.
4208 auto *VecC = dyn_cast<Constant>(Vec);
4209 auto *ValC = dyn_cast<Constant>(Val);
4210 auto *IdxC = dyn_cast<Constant>(Idx);
4211 if (VecC && ValC && IdxC)
4212 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4213
4214 // Fold into undef if index is out of bounds.
4215 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4216 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
Igor Laevskye0edb662017-12-13 11:21:18 +00004217 if (CI->uge(NumElements))
4218 return UndefValue::get(Vec->getType());
4219 }
4220
Philip Reamese499bc32017-12-30 05:54:22 +00004221 // If index is undef, it might be out of bounds (see above case)
4222 if (isa<UndefValue>(Idx))
4223 return UndefValue::get(Vec->getType());
Igor Laevskye0edb662017-12-13 11:21:18 +00004224
4225 return nullptr;
4226}
4227
Sanjay Patel472cc782016-01-11 22:14:42 +00004228/// Given operands for an ExtractValueInst, see if we can fold the result.
4229/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00004230static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004231 const SimplifyQuery &, unsigned) {
David Majnemer25a796e2015-07-13 01:15:46 +00004232 if (auto *CAgg = dyn_cast<Constant>(Agg))
4233 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4234
4235 // extractvalue x, (insertvalue y, elt, n), n -> elt
4236 unsigned NumIdxs = Idxs.size();
4237 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4238 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4239 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4240 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4241 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4242 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4243 Idxs.slice(0, NumCommonIdxs)) {
4244 if (NumIdxs == NumInsertValueIdxs)
4245 return IVI->getInsertedValueOperand();
4246 break;
4247 }
4248 }
4249
4250 return nullptr;
4251}
4252
4253Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004254 const SimplifyQuery &Q) {
4255 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
4256}
4257
Sanjay Patel472cc782016-01-11 22:14:42 +00004258/// Given operands for an ExtractElementInst, see if we can fold the result.
4259/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004260static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
David Majnemer599ca442015-07-13 01:15:53 +00004261 unsigned) {
4262 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4263 if (auto *CIdx = dyn_cast<Constant>(Idx))
4264 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4265
4266 // The index is not relevant if our vector is a splat.
4267 if (auto *Splat = CVec->getSplatValue())
4268 return Splat;
4269
4270 if (isa<UndefValue>(Vec))
4271 return UndefValue::get(Vec->getType()->getVectorElementType());
4272 }
4273
4274 // If extracting a specified index from the vector, see if we can recursively
4275 // find a previously computed scalar that was inserted into the vector.
Philip Reamese499bc32017-12-30 05:54:22 +00004276 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4277 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4278 // definitely out of bounds, thus undefined result
4279 return UndefValue::get(Vec->getType()->getVectorElementType());
4280 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4281 return Elt;
4282 }
David Majnemer599ca442015-07-13 01:15:53 +00004283
Zvi Rackover2e6e88f2017-12-06 17:51:46 +00004284 // An undef extract index can be arbitrarily chosen to be an out-of-range
4285 // index value, which would result in the instruction being undef.
4286 if (isa<UndefValue>(Idx))
4287 return UndefValue::get(Vec->getType()->getVectorElementType());
4288
David Majnemer599ca442015-07-13 01:15:53 +00004289 return nullptr;
4290}
4291
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004292Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4293 const SimplifyQuery &Q) {
4294 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4295}
4296
Sanjay Patel472cc782016-01-11 22:14:42 +00004297/// See if we can fold the given phi. If not, returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004298static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004299 // If all of the PHI's incoming values are the same then replace the PHI node
4300 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004301 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004302 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004303 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004304 // If the incoming value is the phi node itself, it can safely be skipped.
4305 if (Incoming == PN) continue;
4306 if (isa<UndefValue>(Incoming)) {
4307 // Remember that we saw an undef value, but otherwise ignore them.
4308 HasUndefInput = true;
4309 continue;
4310 }
4311 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004312 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004313 CommonValue = Incoming;
4314 }
4315
4316 // If CommonValue is null then all of the incoming values were either undef or
4317 // equal to the phi node itself.
4318 if (!CommonValue)
4319 return UndefValue::get(PN->getType());
4320
4321 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4322 // instruction, we cannot return X as the result of the PHI node unless it
4323 // dominates the PHI block.
4324 if (HasUndefInput)
Sanjay Patel5da361a2018-04-10 18:38:19 +00004325 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004326
4327 return CommonValue;
4328}
4329
David Majnemer6774d612016-07-26 17:58:05 +00004330static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004331 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004332 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004333 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004334
David Majnemer6774d612016-07-26 17:58:05 +00004335 if (auto *CI = dyn_cast<CastInst>(Op)) {
4336 auto *Src = CI->getOperand(0);
4337 Type *SrcTy = Src->getType();
4338 Type *MidTy = CI->getType();
4339 Type *DstTy = Ty;
4340 if (Src->getType() == Ty) {
4341 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4342 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4343 Type *SrcIntPtrTy =
4344 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4345 Type *MidIntPtrTy =
4346 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4347 Type *DstIntPtrTy =
4348 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4349 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4350 SrcIntPtrTy, MidIntPtrTy,
4351 DstIntPtrTy) == Instruction::BitCast)
4352 return Src;
4353 }
4354 }
David Majnemera90a6212016-07-26 05:52:29 +00004355
4356 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004357 if (CastOpc == Instruction::BitCast)
4358 if (Op->getType() == Ty)
4359 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004360
4361 return nullptr;
4362}
4363
David Majnemer6774d612016-07-26 17:58:05 +00004364Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004365 const SimplifyQuery &Q) {
4366 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4367}
4368
Sanjay Patela3c297d2017-04-19 16:48:22 +00004369/// For the given destination element of a shuffle, peek through shuffles to
4370/// match a root vector source operand that contains that element in the same
4371/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4372static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
Zvi Rackover558f86b2017-05-08 15:46:58 +00004373 int MaskVal, Value *RootVec,
Sanjay Patela3c297d2017-04-19 16:48:22 +00004374 unsigned MaxRecurse) {
4375 if (!MaxRecurse--)
4376 return nullptr;
4377
4378 // Bail out if any mask value is undefined. That kind of shuffle may be
4379 // simplified further based on demanded bits or other folds.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004380 if (MaskVal == -1)
4381 return nullptr;
4382
4383 // The mask value chooses which source operand we need to look at next.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004384 int InVecNumElts = Op0->getType()->getVectorNumElements();
Zvi Rackover558f86b2017-05-08 15:46:58 +00004385 int RootElt = MaskVal;
4386 Value *SourceOp = Op0;
4387 if (MaskVal >= InVecNumElts) {
Sanjay Patela3c297d2017-04-19 16:48:22 +00004388 RootElt = MaskVal - InVecNumElts;
4389 SourceOp = Op1;
4390 }
4391
4392 // If the source operand is a shuffle itself, look through it to find the
4393 // matching root vector.
4394 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4395 return foldIdentityShuffles(
4396 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
Zvi Rackover558f86b2017-05-08 15:46:58 +00004397 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004398 }
4399
4400 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4401 // size?
4402
4403 // The source operand is not a shuffle. Initialize the root vector value for
4404 // this shuffle if that has not been done yet.
4405 if (!RootVec)
4406 RootVec = SourceOp;
4407
4408 // Give up as soon as a source operand does not match the existing root value.
4409 if (RootVec != SourceOp)
4410 return nullptr;
4411
4412 // The element must be coming from the same lane in the source vector
4413 // (although it may have crossed lanes in intermediate shuffles).
4414 if (RootElt != DestElt)
4415 return nullptr;
4416
4417 return RootVec;
4418}
4419
Zvi Rackover8f460652017-04-03 22:05:30 +00004420static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004421 Type *RetTy, const SimplifyQuery &Q,
Zvi Rackover8f460652017-04-03 22:05:30 +00004422 unsigned MaxRecurse) {
Zvi Rackover4086e132017-04-30 06:06:26 +00004423 if (isa<UndefValue>(Mask))
4424 return UndefValue::get(RetTy);
4425
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004426 Type *InVecTy = Op0->getType();
Zvi Rackover8f460652017-04-03 22:05:30 +00004427 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004428 unsigned InVecNumElts = InVecTy->getVectorNumElements();
Zvi Rackover8f460652017-04-03 22:05:30 +00004429
Zvi Rackover0411e462017-04-30 06:10:54 +00004430 SmallVector<int, 32> Indices;
4431 ShuffleVectorInst::getShuffleMask(Mask, Indices);
4432 assert(MaskNumElts == Indices.size() &&
4433 "Size of Indices not same as number of mask elements?");
4434
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004435 // Canonicalization: If mask does not select elements from an input vector,
4436 // replace that input vector with undef.
Zvi Rackover8f460652017-04-03 22:05:30 +00004437 bool MaskSelects0 = false, MaskSelects1 = false;
4438 for (unsigned i = 0; i != MaskNumElts; ++i) {
Zvi Rackover0411e462017-04-30 06:10:54 +00004439 if (Indices[i] == -1)
Zvi Rackover8f460652017-04-03 22:05:30 +00004440 continue;
Zvi Rackover0411e462017-04-30 06:10:54 +00004441 if ((unsigned)Indices[i] < InVecNumElts)
Zvi Rackover8f460652017-04-03 22:05:30 +00004442 MaskSelects0 = true;
4443 else
4444 MaskSelects1 = true;
4445 }
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004446 if (!MaskSelects0)
4447 Op0 = UndefValue::get(InVecTy);
4448 if (!MaskSelects1)
4449 Op1 = UndefValue::get(InVecTy);
4450
4451 auto *Op0Const = dyn_cast<Constant>(Op0);
4452 auto *Op1Const = dyn_cast<Constant>(Op1);
4453
4454 // If all operands are constant, constant fold the shuffle.
4455 if (Op0Const && Op1Const)
4456 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4457
4458 // Canonicalization: if only one input vector is constant, it shall be the
4459 // second one.
4460 if (Op0Const && !Op1Const) {
4461 std::swap(Op0, Op1);
Zvi Rackoverdfbd3d72017-05-08 12:40:18 +00004462 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004463 }
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004464
4465 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4466 // value type is same as the input vectors' type.
4467 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004468 if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004469 OpShuf->getMask()->getSplatValue())
4470 return Op0;
Zvi Rackover8f460652017-04-03 22:05:30 +00004471
Sanjay Patela3c297d2017-04-19 16:48:22 +00004472 // Don't fold a shuffle with undef mask elements. This may get folded in a
4473 // better way using demanded bits or other analysis.
4474 // TODO: Should we allow this?
Zvi Rackover0411e462017-04-30 06:10:54 +00004475 if (find(Indices, -1) != Indices.end())
4476 return nullptr;
Sanjay Patela3c297d2017-04-19 16:48:22 +00004477
4478 // Check if every element of this shuffle can be mapped back to the
4479 // corresponding element of a single root vector. If so, we don't need this
4480 // shuffle. This handles simple identity shuffles as well as chains of
4481 // shuffles that may widen/narrow and/or move elements across lanes and back.
4482 Value *RootVec = nullptr;
4483 for (unsigned i = 0; i != MaskNumElts; ++i) {
4484 // Note that recursion is limited for each vector element, so if any element
4485 // exceeds the limit, this will fail to simplify.
Zvi Rackover558f86b2017-05-08 15:46:58 +00004486 RootVec =
4487 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004488
4489 // We can't replace a widening/narrowing shuffle with one of its operands.
4490 if (!RootVec || RootVec->getType() != RetTy)
4491 return nullptr;
4492 }
4493 return RootVec;
Zvi Rackover8f460652017-04-03 22:05:30 +00004494}
4495
4496/// Given operands for a ShuffleVectorInst, fold the result or return null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004497Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4498 Type *RetTy, const SimplifyQuery &Q) {
4499 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
Zvi Rackover8f460652017-04-03 22:05:30 +00004500}
4501
Sanjay Patele2359422018-03-21 19:31:53 +00004502static Constant *propagateNaN(Constant *In) {
4503 // If the input is a vector with undef elements, just return a default NaN.
4504 if (!In->isNaN())
4505 return ConstantFP::getNaN(In->getType());
4506
4507 // Propagate the existing NaN constant when possible.
4508 // TODO: Should we quiet a signaling NaN?
4509 return In;
4510}
4511
4512static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4513 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4514 return ConstantFP::getNaN(Op0->getType());
4515
4516 if (match(Op0, m_NaN()))
4517 return propagateNaN(cast<Constant>(Op0));
4518 if (match(Op1, m_NaN()))
4519 return propagateNaN(cast<Constant>(Op1));
4520
4521 return nullptr;
4522}
4523
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004524/// Given operands for an FAdd, see if we can fold the result. If not, this
4525/// returns null.
4526static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4527 const SimplifyQuery &Q, unsigned MaxRecurse) {
4528 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4529 return C;
4530
Sanjay Patele2359422018-03-21 19:31:53 +00004531 if (Constant *C = simplifyFPBinop(Op0, Op1))
4532 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004533
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004534 // fadd X, -0 ==> X
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004535 if (match(Op1, m_NegZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004536 return Op0;
4537
4538 // fadd X, 0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004539 if (match(Op1, m_PosZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004540 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4541 return Op0;
4542
Sanjay Patel11f7f992018-03-14 21:23:27 +00004543 // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
4544 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4545 // Negative zeros are allowed because we always end up with positive zero:
4546 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4547 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4548 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4549 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
Sanjay Patela4f42f22018-03-15 14:29:27 +00004550 if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4551 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
Sanjay Patel11f7f992018-03-14 21:23:27 +00004552 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004553
Sanjay Patel9b073472018-08-07 20:32:55 +00004554 // (X - Y) + Y --> X
4555 // Y + (X - Y) --> X
4556 Value *X;
4557 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4558 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4559 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4560 return X;
4561
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004562 return nullptr;
4563}
4564
4565/// Given operands for an FSub, see if we can fold the result. If not, this
4566/// returns null.
4567static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4568 const SimplifyQuery &Q, unsigned MaxRecurse) {
4569 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4570 return C;
4571
Sanjay Patele2359422018-03-21 19:31:53 +00004572 if (Constant *C = simplifyFPBinop(Op0, Op1))
4573 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004574
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004575 // fsub X, +0 ==> X
4576 if (match(Op1, m_PosZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004577 return Op0;
4578
4579 // fsub X, -0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004580 if (match(Op1, m_NegZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004581 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4582 return Op0;
4583
4584 // fsub -0.0, (fsub -0.0, X) ==> X
4585 Value *X;
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004586 if (match(Op0, m_NegZeroFP()) &&
4587 match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004588 return X;
4589
4590 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Sanjay Patela4f42f22018-03-15 14:29:27 +00004591 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4592 match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004593 return X;
4594
4595 // fsub nnan x, x ==> 0.0
4596 if (FMF.noNaNs() && Op0 == Op1)
4597 return Constant::getNullValue(Op0->getType());
4598
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004599 // Y - (Y - X) --> X
Sanjay Patel4364d602018-08-07 20:23:49 +00004600 // (X + Y) - Y --> X
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004601 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
Sanjay Patel4364d602018-08-07 20:23:49 +00004602 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4603 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
Sanjay Patelf7a8fb22018-08-07 20:14:27 +00004604 return X;
4605
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004606 return nullptr;
4607}
4608
4609/// Given the operands for an FMul, see if we can fold the result
4610static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4611 const SimplifyQuery &Q, unsigned MaxRecurse) {
4612 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4613 return C;
4614
Sanjay Patele2359422018-03-21 19:31:53 +00004615 if (Constant *C = simplifyFPBinop(Op0, Op1))
4616 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004617
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004618 // fmul X, 1.0 ==> X
4619 if (match(Op1, m_FPOne()))
4620 return Op0;
4621
4622 // fmul nnan nsz X, 0 ==> 0
Sanjay Patela4f42f22018-03-15 14:29:27 +00004623 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4624 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004625
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004626 // sqrt(X) * sqrt(X) --> X, if we can:
4627 // 1. Remove the intermediate rounding (reassociate).
4628 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4629 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
Sanjay Pateldb53d182018-02-23 22:20:13 +00004630 Value *X;
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004631 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4632 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
Sanjay Pateldb53d182018-02-23 22:20:13 +00004633 return X;
4634
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004635 return nullptr;
4636}
4637
4638Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4639 const SimplifyQuery &Q) {
4640 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4641}
4642
4643
4644Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4645 const SimplifyQuery &Q) {
4646 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4647}
4648
4649Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4650 const SimplifyQuery &Q) {
4651 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4652}
4653
4654static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4655 const SimplifyQuery &Q, unsigned) {
4656 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4657 return C;
4658
Sanjay Patele2359422018-03-21 19:31:53 +00004659 if (Constant *C = simplifyFPBinop(Op0, Op1))
4660 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004661
4662 // X / 1.0 -> X
4663 if (match(Op1, m_FPOne()))
4664 return Op0;
4665
4666 // 0 / X -> 0
4667 // Requires that NaNs are off (X could be zero) and signed zeroes are
4668 // ignored (X could be positive or negative, so the output sign is unknown).
Sanjay Patela4f42f22018-03-15 14:29:27 +00004669 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4670 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004671
4672 if (FMF.noNaNs()) {
4673 // X / X -> 1.0 is legal when NaNs are ignored.
Sanjay Patel83f05662018-01-30 00:18:37 +00004674 // We can ignore infinities because INF/INF is NaN.
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004675 if (Op0 == Op1)
4676 return ConstantFP::get(Op0->getType(), 1.0);
4677
Sanjay Patel83f05662018-01-30 00:18:37 +00004678 // (X * Y) / Y --> X if we can reassociate to the above form.
4679 Value *X;
4680 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4681 return X;
4682
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004683 // -X / X -> -1.0 and
4684 // X / -X -> -1.0 are legal when NaNs are ignored.
4685 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
Cameron McInallybea59672018-10-09 21:48:00 +00004686 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4687 match(Op1, m_FNegNSZ(m_Specific(Op0))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004688 return ConstantFP::get(Op0->getType(), -1.0);
4689 }
4690
4691 return nullptr;
4692}
4693
4694Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4695 const SimplifyQuery &Q) {
4696 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4697}
4698
4699static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4700 const SimplifyQuery &Q, unsigned) {
4701 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4702 return C;
4703
Sanjay Patele2359422018-03-21 19:31:53 +00004704 if (Constant *C = simplifyFPBinop(Op0, Op1))
4705 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004706
Sanjay Patel8f063d02018-03-15 14:04:31 +00004707 // Unlike fdiv, the result of frem always matches the sign of the dividend.
4708 // The constant match may include undef elements in a vector, so return a full
4709 // zero constant as the result.
4710 if (FMF.noNaNs()) {
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004711 // +0 % X -> 0
4712 if (match(Op0, m_PosZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004713 return ConstantFP::getNullValue(Op0->getType());
4714 // -0 % X -> -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004715 if (match(Op0, m_NegZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004716 return ConstantFP::getNegativeZero(Op0->getType());
4717 }
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004718
4719 return nullptr;
4720}
4721
4722Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4723 const SimplifyQuery &Q) {
4724 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4725}
4726
Chris Lattnera71e9d62009-11-10 00:55:12 +00004727//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004728
Sanjay Patel472cc782016-01-11 22:14:42 +00004729/// Given operands for a BinaryOperator, see if we can fold the result.
4730/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004731static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004732 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004733 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004734 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004735 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004736 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004737 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004738 case Instruction::Mul:
4739 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004740 case Instruction::SDiv:
4741 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4742 case Instruction::UDiv:
4743 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004744 case Instruction::SRem:
4745 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4746 case Instruction::URem:
4747 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004748 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004749 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004750 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004751 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004752 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004753 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4754 case Instruction::And:
4755 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4756 case Instruction::Or:
4757 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4758 case Instruction::Xor:
4759 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004760 case Instruction::FAdd:
4761 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4762 case Instruction::FSub:
4763 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4764 case Instruction::FMul:
4765 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4766 case Instruction::FDiv:
4767 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4768 case Instruction::FRem:
4769 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004770 default:
Craig Topper8ef20ea2017-04-06 18:59:08 +00004771 llvm_unreachable("Unexpected opcode");
Chris Lattnera71e9d62009-11-10 00:55:12 +00004772 }
4773}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004774
Sanjay Patel472cc782016-01-11 22:14:42 +00004775/// Given operands for a BinaryOperator, see if we can fold the result.
4776/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004777/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4778/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4779static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004780 const FastMathFlags &FMF, const SimplifyQuery &Q,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004781 unsigned MaxRecurse) {
4782 switch (Opcode) {
4783 case Instruction::FAdd:
4784 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4785 case Instruction::FSub:
4786 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4787 case Instruction::FMul:
4788 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004789 case Instruction::FDiv:
4790 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004791 default:
4792 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4793 }
4794}
4795
Duncan Sands7e800d62010-11-14 11:23:23 +00004796Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004797 const SimplifyQuery &Q) {
4798 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4799}
4800
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004801Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berline8d74dc2017-04-26 04:10:00 +00004802 FastMathFlags FMF, const SimplifyQuery &Q) {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004803 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4804}
4805
Sanjay Patel472cc782016-01-11 22:14:42 +00004806/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004807static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004808 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004809 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004810 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004811 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004812}
4813
4814Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004815 const SimplifyQuery &Q) {
4816 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4817}
4818
Michael Ilseman54857292013-02-07 19:26:05 +00004819static bool IsIdempotent(Intrinsic::ID ID) {
4820 switch (ID) {
4821 default: return false;
4822
4823 // Unary idempotent: f(f(x)) = f(x)
4824 case Intrinsic::fabs:
4825 case Intrinsic::floor:
4826 case Intrinsic::ceil:
4827 case Intrinsic::trunc:
4828 case Intrinsic::rint:
4829 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004830 case Intrinsic::round:
Matt Arsenault3ced3d92017-09-07 01:21:43 +00004831 case Intrinsic::canonicalize:
Michael Ilseman54857292013-02-07 19:26:05 +00004832 return true;
4833 }
4834}
4835
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004836static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4837 const DataLayout &DL) {
4838 GlobalValue *PtrSym;
4839 APInt PtrOffset;
4840 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4841 return nullptr;
4842
4843 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4844 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4845 Type *Int32PtrTy = Int32Ty->getPointerTo();
4846 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4847
4848 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4849 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4850 return nullptr;
4851
4852 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4853 if (OffsetInt % 4 != 0)
4854 return nullptr;
4855
4856 Constant *C = ConstantExpr::getGetElementPtr(
4857 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4858 ConstantInt::get(Int64Ty, OffsetInt / 4));
4859 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4860 if (!Loaded)
4861 return nullptr;
4862
4863 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4864 if (!LoadedCE)
4865 return nullptr;
4866
4867 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4868 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4869 if (!LoadedCE)
4870 return nullptr;
4871 }
4872
4873 if (LoadedCE->getOpcode() != Instruction::Sub)
4874 return nullptr;
4875
4876 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4877 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4878 return nullptr;
4879 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4880
4881 Constant *LoadedRHS = LoadedCE->getOperand(1);
4882 GlobalValue *LoadedRHSSym;
4883 APInt LoadedRHSOffset;
4884 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4885 DL) ||
4886 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4887 return nullptr;
4888
4889 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4890}
4891
David Majnemer17a95aa2016-07-14 06:58:37 +00004892static bool maskIsAllZeroOrUndef(Value *Mask) {
4893 auto *ConstMask = dyn_cast<Constant>(Mask);
4894 if (!ConstMask)
4895 return false;
4896 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4897 return true;
4898 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4899 ++I) {
4900 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4901 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4902 continue;
4903 return false;
4904 }
4905 return true;
4906}
4907
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004908static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
4909 const SimplifyQuery &Q) {
4910 // Idempotent functions return the same result when called repeatedly.
David Majnemer15032582015-05-22 03:56:46 +00004911 Intrinsic::ID IID = F->getIntrinsicID();
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004912 if (IsIdempotent(IID))
4913 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
4914 if (II->getIntrinsicID() == IID)
4915 return II;
Michael Ilseman54857292013-02-07 19:26:05 +00004916
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004917 Value *X;
4918 switch (IID) {
4919 case Intrinsic::fabs:
4920 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0;
4921 break;
4922 case Intrinsic::bswap:
4923 // bswap(bswap(x)) -> x
4924 if (match(Op0, m_BSwap(m_Value(X)))) return X;
4925 break;
4926 case Intrinsic::bitreverse:
4927 // bitreverse(bitreverse(x)) -> x
4928 if (match(Op0, m_BitReverse(m_Value(X)))) return X;
4929 break;
4930 case Intrinsic::exp:
4931 // exp(log(x)) -> x
4932 if (Q.CxtI->hasAllowReassoc() &&
4933 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X;
4934 break;
4935 case Intrinsic::exp2:
4936 // exp2(log2(x)) -> x
4937 if (Q.CxtI->hasAllowReassoc() &&
4938 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X;
4939 break;
4940 case Intrinsic::log:
4941 // log(exp(x)) -> x
4942 if (Q.CxtI->hasAllowReassoc() &&
4943 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X;
4944 break;
4945 case Intrinsic::log2:
4946 // log2(exp2(x)) -> x
4947 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikovaaa709f2019-02-03 03:48:30 +00004948 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
4949 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0),
4950 m_Value(X))))) return X;
4951 break;
4952 case Intrinsic::log10:
4953 // log10(pow(10.0, x)) -> x
4954 if (Q.CxtI->hasAllowReassoc() &&
4955 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0),
4956 m_Value(X)))) return X;
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004957 break;
4958 default:
4959 break;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004960 }
Michael Ilseman54857292013-02-07 19:26:05 +00004961
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004962 return nullptr;
4963}
Matt Arsenault82606662017-01-11 00:57:54 +00004964
Sanjay Patelf52eeb12018-07-29 14:42:08 +00004965static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
4966 const SimplifyQuery &Q) {
4967 Intrinsic::ID IID = F->getIntrinsicID();
4968 Type *ReturnType = F->getReturnType();
4969 switch (IID) {
4970 case Intrinsic::usub_with_overflow:
4971 case Intrinsic::ssub_with_overflow:
4972 // X - X -> { 0, false }
4973 if (Op0 == Op1)
4974 return Constant::getNullValue(ReturnType);
4975 // X - undef -> undef
4976 // undef - X -> undef
4977 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4978 return UndefValue::get(ReturnType);
4979 break;
4980 case Intrinsic::uadd_with_overflow:
4981 case Intrinsic::sadd_with_overflow:
4982 // X + undef -> undef
4983 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4984 return UndefValue::get(ReturnType);
4985 break;
4986 case Intrinsic::umul_with_overflow:
4987 case Intrinsic::smul_with_overflow:
4988 // 0 * X -> { 0, false }
4989 // X * 0 -> { 0, false }
4990 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
4991 return Constant::getNullValue(ReturnType);
4992 // undef * X -> { 0, false }
4993 // X * undef -> { 0, false }
4994 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
4995 return Constant::getNullValue(ReturnType);
4996 break;
Sanjay Pateleea21da2018-11-20 17:20:26 +00004997 case Intrinsic::uadd_sat:
4998 // sat(MAX + X) -> MAX
4999 // sat(X + MAX) -> MAX
5000 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
5001 return Constant::getAllOnesValue(ReturnType);
5002 LLVM_FALLTHROUGH;
5003 case Intrinsic::sadd_sat:
5004 // sat(X + undef) -> -1
5005 // sat(undef + X) -> -1
5006 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
5007 // For signed: Assume undef is ~X, in which case X + ~X = -1.
5008 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
5009 return Constant::getAllOnesValue(ReturnType);
5010
5011 // X + 0 -> X
5012 if (match(Op1, m_Zero()))
5013 return Op0;
5014 // 0 + X -> X
5015 if (match(Op0, m_Zero()))
5016 return Op1;
5017 break;
5018 case Intrinsic::usub_sat:
5019 // sat(0 - X) -> 0, sat(X - MAX) -> 0
5020 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
5021 return Constant::getNullValue(ReturnType);
5022 LLVM_FALLTHROUGH;
5023 case Intrinsic::ssub_sat:
5024 // X - X -> 0, X - undef -> 0, undef - X -> 0
5025 if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef()))
5026 return Constant::getNullValue(ReturnType);
5027 // X - 0 -> X
5028 if (match(Op1, m_Zero()))
5029 return Op0;
5030 break;
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005031 case Intrinsic::load_relative:
5032 if (auto *C0 = dyn_cast<Constant>(Op0))
5033 if (auto *C1 = dyn_cast<Constant>(Op1))
Matt Arsenault82606662017-01-11 00:57:54 +00005034 return SimplifyRelativeLoad(C0, C1, Q.DL);
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005035 break;
5036 case Intrinsic::powi:
5037 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
5038 // powi(x, 0) -> 1.0
5039 if (Power->isZero())
5040 return ConstantFP::get(Op0->getType(), 1.0);
5041 // powi(x, 1) -> x
5042 if (Power->isOne())
5043 return Op0;
Matt Arsenault82606662017-01-11 00:57:54 +00005044 }
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005045 break;
5046 case Intrinsic::maxnum:
Thomas Livelyc3392502018-10-19 19:01:26 +00005047 case Intrinsic::minnum:
5048 case Intrinsic::maximum:
5049 case Intrinsic::minimum: {
Sanjay Patel28c7e412018-08-01 23:05:55 +00005050 // If the arguments are the same, this is a no-op.
5051 if (Op0 == Op1) return Op0;
5052
Thomas Livelyc3392502018-10-19 19:01:26 +00005053 // If one argument is undef, return the other argument.
5054 if (match(Op0, m_Undef()))
5055 return Op1;
5056 if (match(Op1, m_Undef()))
5057 return Op0;
5058
5059 // If one argument is NaN, return other or NaN appropriately.
5060 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
5061 if (match(Op0, m_NaN()))
5062 return PropagateNaN ? Op0 : Op1;
5063 if (match(Op1, m_NaN()))
5064 return PropagateNaN ? Op1 : Op0;
Sanjay Patel3f6e9a72018-08-02 14:33:40 +00005065
Sanjay Patel948ff872018-08-07 14:36:27 +00005066 // Min/max of the same operation with common operand:
5067 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
5068 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
5069 if (M0->getIntrinsicID() == IID &&
5070 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
5071 return Op0;
5072 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
5073 if (M1->getIntrinsicID() == IID &&
5074 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
5075 return Op1;
5076
Thomas Livelyc3392502018-10-19 19:01:26 +00005077 // min(X, -Inf) --> -Inf (and commuted variant)
5078 // max(X, +Inf) --> +Inf (and commuted variant)
5079 bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum;
Sanjay Patelc6944f72018-08-09 22:20:44 +00005080 const APFloat *C;
5081 if ((match(Op0, m_APFloat(C)) && C->isInfinity() &&
5082 C->isNegative() == UseNegInf) ||
5083 (match(Op1, m_APFloat(C)) && C->isInfinity() &&
5084 C->isNegative() == UseNegInf))
5085 return ConstantFP::getInfinity(ReturnType, UseNegInf);
5086
5087 // TODO: minnum(nnan x, inf) -> x
5088 // TODO: minnum(nnan ninf x, flt_max) -> x
5089 // TODO: maxnum(nnan x, -inf) -> x
5090 // TODO: maxnum(nnan ninf x, -flt_max) -> x
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005091 break;
Sanjay Patelc6944f72018-08-09 22:20:44 +00005092 }
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005093 default:
5094 break;
Matt Arsenault82606662017-01-11 00:57:54 +00005095 }
5096
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005097 return nullptr;
5098}
5099
5100template <typename IterTy>
5101static Value *simplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
5102 const SimplifyQuery &Q) {
5103 // Intrinsics with no operands have some kind of side effect. Don't simplify.
5104 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
5105 if (NumOperands == 0)
5106 return nullptr;
5107
5108 Intrinsic::ID IID = F->getIntrinsicID();
5109 if (NumOperands == 1)
5110 return simplifyUnaryIntrinsic(F, ArgBegin[0], Q);
5111
5112 if (NumOperands == 2)
5113 return simplifyBinaryIntrinsic(F, ArgBegin[0], ArgBegin[1], Q);
5114
5115 // Handle intrinsics with 3 or more arguments.
Matt Arsenault82606662017-01-11 00:57:54 +00005116 switch (IID) {
5117 case Intrinsic::masked_load: {
5118 Value *MaskArg = ArgBegin[2];
5119 Value *PassthruArg = ArgBegin[3];
5120 // If the mask is all zeros or undef, the "passthru" argument is the result.
5121 if (maskIsAllZeroOrUndef(MaskArg))
5122 return PassthruArg;
5123 return nullptr;
5124 }
Sanjay Patel54421ce2018-07-29 16:36:38 +00005125 case Intrinsic::fshl:
5126 case Intrinsic::fshr: {
Sanjay Patel14ab9172018-11-20 17:34:59 +00005127 Value *Op0 = ArgBegin[0], *Op1 = ArgBegin[1], *ShAmtArg = ArgBegin[2];
5128
5129 // If both operands are undef, the result is undef.
5130 if (match(Op0, m_Undef()) && match(Op1, m_Undef()))
5131 return UndefValue::get(F->getReturnType());
5132
5133 // If shift amount is undef, assume it is zero.
5134 if (match(ShAmtArg, m_Undef()))
5135 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
5136
Sanjay Patel54421ce2018-07-29 16:36:38 +00005137 const APInt *ShAmtC;
5138 if (match(ShAmtArg, m_APInt(ShAmtC))) {
5139 // If there's effectively no shift, return the 1st arg or 2nd arg.
5140 // TODO: For vectors, we could check each element of a non-splat constant.
5141 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
5142 if (ShAmtC->urem(BitWidth).isNullValue())
5143 return ArgBegin[IID == Intrinsic::fshl ? 0 : 1];
5144 }
5145 return nullptr;
5146 }
Matt Arsenault82606662017-01-11 00:57:54 +00005147 default:
5148 return nullptr;
5149 }
Michael Ilseman54857292013-02-07 19:26:05 +00005150}
5151
Chandler Carruth9dc35582012-12-28 11:30:55 +00005152template <typename IterTy>
Chandler Carruthdac20a82019-02-11 07:54:10 +00005153static Value *SimplifyCall(CallBase *Call, Value *V, IterTy ArgBegin,
Andrew Kaylor647025f2017-06-09 23:18:11 +00005154 IterTy ArgEnd, const SimplifyQuery &Q,
5155 unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00005156 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00005157 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
5158 Ty = PTy->getElementType();
5159 FunctionType *FTy = cast<FunctionType>(Ty);
5160
Dan Gohman85977e62011-11-04 18:32:42 +00005161 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00005162 // call null -> undef
5163 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00005164 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00005165
Chandler Carruthf6182152012-12-28 14:23:29 +00005166 Function *F = dyn_cast<Function>(V);
5167 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00005168 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005169
David Majnemer15032582015-05-22 03:56:46 +00005170 if (F->isIntrinsic())
Sanjay Patelf52eeb12018-07-29 14:42:08 +00005171 if (Value *Ret = simplifyIntrinsic(F, ArgBegin, ArgEnd, Q))
Michael Ilseman54857292013-02-07 19:26:05 +00005172 return Ret;
5173
Chandler Carruthdac20a82019-02-11 07:54:10 +00005174 if (!canConstantFoldCallTo(Call, F))
Craig Topper9f008862014-04-15 04:59:12 +00005175 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005176
5177 SmallVector<Constant *, 4> ConstantArgs;
5178 ConstantArgs.reserve(ArgEnd - ArgBegin);
5179 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
5180 Constant *C = dyn_cast<Constant>(*I);
5181 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00005182 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00005183 ConstantArgs.push_back(C);
5184 }
5185
Chandler Carruthdac20a82019-02-11 07:54:10 +00005186 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00005187}
5188
Chandler Carruthdac20a82019-02-11 07:54:10 +00005189Value *llvm::SimplifyCall(CallBase *Call, Value *V, User::op_iterator ArgBegin,
5190 User::op_iterator ArgEnd, const SimplifyQuery &Q) {
5191 return ::SimplifyCall(Call, V, ArgBegin, ArgEnd, Q, RecursionLimit);
5192}
5193
5194Value *llvm::SimplifyCall(CallBase *Call, Value *V, ArrayRef<Value *> Args,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005195 const SimplifyQuery &Q) {
Chandler Carruthdac20a82019-02-11 07:54:10 +00005196 return ::SimplifyCall(Call, V, Args.begin(), Args.end(), Q, RecursionLimit);
Andrew Kaylor647025f2017-06-09 23:18:11 +00005197}
5198
Chandler Carruthdac20a82019-02-11 07:54:10 +00005199Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) {
5200 return ::SimplifyCall(Call, Call->getCalledValue(), Call->arg_begin(),
5201 Call->arg_end(), Q, RecursionLimit);
Philip Reames7a6db4f2017-12-27 00:16:12 +00005202}
5203
Sanjay Patel472cc782016-01-11 22:14:42 +00005204/// See if we can compute a simplified version of this instruction.
5205/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005206
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005207Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005208 OptimizationRemarkEmitter *ORE) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005209 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005210 Value *Result;
5211
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005212 switch (I->getOpcode()) {
5213 default:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005214 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005215 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005216 case Instruction::FAdd:
5217 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005218 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005219 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00005220 case Instruction::Add:
Florian Hahn19f9e322018-08-17 14:39:04 +00005221 Result =
5222 SimplifyAddInst(I->getOperand(0), I->getOperand(1),
5223 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5224 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005225 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005226 case Instruction::FSub:
5227 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005228 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00005229 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00005230 case Instruction::Sub:
Florian Hahn19f9e322018-08-17 14:39:04 +00005231 Result =
5232 SimplifySubInst(I->getOperand(0), I->getOperand(1),
5233 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5234 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands0a2c41682010-12-15 14:07:39 +00005235 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00005236 case Instruction::FMul:
5237 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005238 I->getFastMathFlags(), Q);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00005239 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00005240 case Instruction::Mul:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005241 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00005242 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00005243 case Instruction::SDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005244 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00005245 break;
5246 case Instruction::UDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005247 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00005248 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00005249 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00005250 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005251 I->getFastMathFlags(), Q);
Frits van Bommelc2549662011-01-29 15:26:31 +00005252 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00005253 case Instruction::SRem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005254 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005255 break;
5256 case Instruction::URem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005257 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005258 break;
5259 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00005260 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005261 I->getFastMathFlags(), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00005262 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00005263 case Instruction::Shl:
Florian Hahn19f9e322018-08-17 14:39:04 +00005264 Result =
5265 SimplifyShlInst(I->getOperand(0), I->getOperand(1),
5266 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
5267 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005268 break;
5269 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00005270 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Florian Hahn19f9e322018-08-17 14:39:04 +00005271 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005272 break;
5273 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00005274 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Florian Hahn19f9e322018-08-17 14:39:04 +00005275 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00005276 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005277 case Instruction::And:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005278 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005279 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005280 case Instruction::Or:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005281 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005282 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00005283 case Instruction::Xor:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005284 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsc89ac072010-11-17 18:52:15 +00005285 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005286 case Instruction::ICmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005287 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
5288 I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005289 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005290 case Instruction::FCmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005291 Result =
5292 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
5293 I->getOperand(1), I->getFastMathFlags(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005294 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00005295 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00005296 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005297 I->getOperand(2), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005298 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00005299 case Instruction::GetElementPtr: {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005300 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00005301 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005302 Ops, Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005303 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00005304 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00005305 case Instruction::InsertValue: {
5306 InsertValueInst *IV = cast<InsertValueInst>(I);
5307 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
5308 IV->getInsertedValueOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005309 IV->getIndices(), Q);
Duncan Sandsfd26a952011-09-05 06:52:48 +00005310 break;
5311 }
Igor Laevskye0edb662017-12-13 11:21:18 +00005312 case Instruction::InsertElement: {
5313 auto *IE = cast<InsertElementInst>(I);
5314 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
5315 IE->getOperand(2), Q);
5316 break;
5317 }
David Majnemer25a796e2015-07-13 01:15:46 +00005318 case Instruction::ExtractValue: {
5319 auto *EVI = cast<ExtractValueInst>(I);
5320 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005321 EVI->getIndices(), Q);
David Majnemer25a796e2015-07-13 01:15:46 +00005322 break;
5323 }
David Majnemer599ca442015-07-13 01:15:53 +00005324 case Instruction::ExtractElement: {
5325 auto *EEI = cast<ExtractElementInst>(I);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005326 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
5327 EEI->getIndexOperand(), Q);
David Majnemer599ca442015-07-13 01:15:53 +00005328 break;
5329 }
Zvi Rackover8f460652017-04-03 22:05:30 +00005330 case Instruction::ShuffleVector: {
5331 auto *SVI = cast<ShuffleVectorInst>(I);
5332 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005333 SVI->getMask(), SVI->getType(), Q);
Zvi Rackover8f460652017-04-03 22:05:30 +00005334 break;
5335 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00005336 case Instruction::PHI:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005337 Result = SimplifyPHINode(cast<PHINode>(I), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00005338 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00005339 case Instruction::Call: {
Chandler Carruthdac20a82019-02-11 07:54:10 +00005340 Result = SimplifyCall(cast<CallInst>(I), Q);
Dan Gohman85977e62011-11-04 18:32:42 +00005341 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00005342 }
David Majnemer6774d612016-07-26 17:58:05 +00005343#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
5344#include "llvm/IR/Instruction.def"
5345#undef HANDLE_CAST_INST
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00005346 Result =
5347 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
David Majnemera90a6212016-07-26 05:52:29 +00005348 break;
Craig Topper81c03a72017-04-12 22:54:24 +00005349 case Instruction::Alloca:
5350 // No simplifications for Alloca and it can't be constant folded.
5351 Result = nullptr;
5352 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005353 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00005354
Hal Finkelf2199b22015-10-23 20:37:08 +00005355 // In general, it is possible for computeKnownBits to determine all bits in a
5356 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00005357 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00005358 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
Craig Topper8189a872017-05-03 23:12:29 +00005359 if (Known.isConstant())
5360 Result = ConstantInt::get(I->getType(), Known.getConstant());
Hal Finkelf2199b22015-10-23 20:37:08 +00005361 }
5362
Duncan Sands64e41cf2010-11-17 08:35:29 +00005363 /// If called on unreachable code, the above logic may report that the
5364 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00005365 /// detecting that case here, returning a safe value instead.
5366 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00005367}
5368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005369/// Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005370/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00005371///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005372/// This is the common implementation of the recursive simplification routines.
5373/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
5374/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
5375/// instructions to process and attempt to simplify it using
5376/// InstructionSimplify.
5377///
5378/// This routine returns 'true' only when *it* simplifies something. The passed
5379/// in simplified value does not count toward this.
5380static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005381 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005382 const DominatorTree *DT,
5383 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005384 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005385 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005386 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00005387
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005388 // If we have an explicit value to collapse to, do that round of the
5389 // simplification loop by hand initially.
5390 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005391 for (User *U : I->users())
5392 if (U != I)
5393 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00005394
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005395 // Replace the instruction with its simplified value.
5396 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00005397
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005398 // Gracefully handle edge cases where the instruction is not wired into any
5399 // parent block.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005400 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
David Majnemer909793f2016-08-04 04:24:02 +00005401 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005402 I->eraseFromParent();
5403 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005404 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00005405 }
Duncan Sands7e800d62010-11-14 11:23:23 +00005406
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005407 // Note that we must test the size on each iteration, the worklist can grow.
5408 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5409 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00005410
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005411 // See if this instruction simplifies.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005412 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005413 if (!SimpleV)
5414 continue;
5415
5416 Simplified = true;
5417
5418 // Stash away all the uses of the old instruction so we can check them for
5419 // recursive simplifications after a RAUW. This is cheaper than checking all
5420 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005421 for (User *U : I->users())
5422 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005423
5424 // Replace the instruction with its simplified value.
5425 I->replaceAllUsesWith(SimpleV);
5426
5427 // Gracefully handle edge cases where the instruction is not wired into any
5428 // parent block.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00005429 if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
David Majnemer909793f2016-08-04 04:24:02 +00005430 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005431 I->eraseFromParent();
5432 }
5433 return Simplified;
5434}
5435
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005436bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005437 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005438 const DominatorTree *DT,
5439 AssumptionCache *AC) {
5440 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005441}
5442
5443bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005444 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005445 const DominatorTree *DT,
5446 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005447 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5448 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005449 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00005450}
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005451
5452namespace llvm {
5453const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5454 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5455 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5456 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5457 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5458 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5459 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5460 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5461}
5462
5463const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5464 const DataLayout &DL) {
5465 return {DL, &AR.TLI, &AR.DT, &AR.AC};
5466}
5467
5468template <class T, class... TArgs>
5469const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5470 Function &F) {
5471 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5472 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5473 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5474 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5475}
5476template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5477 Function &);
5478}