blob: 5670746284eb625cf31a02dd47448f71cc94859c [file] [log] [blame]
Chris Lattner084a1b52009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sandsa0219882010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsed6d6c32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner084a1b52009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/Statistic.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000023#include "llvm/Analysis/AliasAnalysis.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000024#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Sanjay Patel54656ca2017-02-06 18:26:06 +000027#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000029#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000030#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/GlobalAlias.h"
35#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000038#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000039using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000040using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "instsimplify"
43
Chris Lattner9e4aa022011-02-09 17:15:04 +000044enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000045
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000047STATISTIC(NumReassoc, "Number of reassociations");
48
Benjamin Kramercfd8d902014-09-12 08:56:53 +000049namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000050struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000051 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000052 const TargetLibraryInfo *TLI;
53 const DominatorTree *DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000054 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000055 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000056
Mehdi Aminia28d91d2015-03-10 02:37:25 +000057 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 const DominatorTree *dt, AssumptionCache *ac = nullptr,
59 const Instruction *cxti = nullptr)
60 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000061};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000062} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000063
64static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
65static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000066 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000067static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
68 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000069static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000070 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000071static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
72 const Query &Q, unsigned MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +000073static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
74static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000075static Value *SimplifyCastInst(unsigned, Value *, Type *,
76 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000077
Sanjay Patel35ed2412017-04-16 17:43:11 +000078/// For a boolean type or a vector of boolean type, return false or a vector
79/// with every element false.
Duncan Sandsc1c92712011-07-26 15:03:53 +000080static Constant *getFalse(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000081 return ConstantInt::getFalse(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000082}
83
Sanjay Patel35ed2412017-04-16 17:43:11 +000084/// For a boolean type or a vector of boolean type, return true or a vector
85/// with every element true.
Duncan Sandsc1c92712011-07-26 15:03:53 +000086static Constant *getTrue(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000087 return ConstantInt::getTrue(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000088}
89
Duncan Sands3d5692a2011-10-30 19:56:36 +000090/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
91static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
92 Value *RHS) {
93 CmpInst *Cmp = dyn_cast<CmpInst>(V);
94 if (!Cmp)
95 return false;
96 CmpInst::Predicate CPred = Cmp->getPredicate();
97 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
99 return true;
100 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
101 CRHS == LHS;
102}
103
Sanjay Patel472cc782016-01-11 22:14:42 +0000104/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000105static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106 Instruction *I = dyn_cast<Instruction>(V);
107 if (!I)
108 // Arguments and constants dominate all instructions.
109 return true;
110
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000111 // If we are processing instructions (and/or basic blocks) that have not been
112 // fully added to a function, the parent nodes may still be null. Simply
113 // return the conservative answer in these cases.
114 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
115 return false;
116
Duncan Sands5ffc2982010-11-16 12:16:38 +0000117 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000118 if (DT) {
119 if (!DT->isReachableFromEntry(P->getParent()))
120 return true;
121 if (!DT->isReachableFromEntry(I->getParent()))
122 return false;
123 return DT->dominates(I, P);
124 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000125
David Majnemer8a1c45d2015-12-12 05:38:55 +0000126 // Otherwise, if the instruction is in the entry block and is not an invoke,
127 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000128 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000129 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000130 return true;
131
132 return false;
133}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000134
Sanjay Patel472cc782016-01-11 22:14:42 +0000135/// Simplify "A op (B op' C)" by distributing op over op', turning it into
136/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000137/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139/// Returns the simplified value, or null if no simplification was performed.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000140static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
141 Instruction::BinaryOps OpcodeToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000142 unsigned MaxRecurse) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000143 // Recursion is always used, so bail out at once if we already hit the limit.
144 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000145 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000146
147 // Check whether the expression has the form "(A op' B) op C".
148 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
149 if (Op0->getOpcode() == OpcodeToExpand) {
150 // It does! Try turning it into "(A op C) op' (B op C)".
151 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
152 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000153 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
154 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000155 // They do! Return "L op' R" if it simplifies or is already available.
156 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000157 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
158 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000159 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000160 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000161 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000162 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000163 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000164 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000165 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000166 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 }
168 }
169
170 // Check whether the expression has the form "A op (B op' C)".
171 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
172 if (Op1->getOpcode() == OpcodeToExpand) {
173 // It does! Try turning it into "(A op B) op' (A op C)".
174 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
175 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000176 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
177 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000178 // They do! Return "L op' R" if it simplifies or is already available.
179 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000180 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
181 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000182 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000184 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000185 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000186 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000187 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000188 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 }
191 }
192
Craig Topper9f008862014-04-15 04:59:12 +0000193 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000194}
195
Sanjay Patel472cc782016-01-11 22:14:42 +0000196/// Generic simplifications for associative binary operations.
197/// Returns the simpler value, or null if none was found.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000198static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
199 Value *LHS, Value *RHS, const Query &Q,
200 unsigned MaxRecurse) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000201 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
202
203 // Recursion is always used, so bail out at once if we already hit the limit.
204 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000205 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000206
207 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
208 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
209
210 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
211 if (Op0 && Op0->getOpcode() == Opcode) {
212 Value *A = Op0->getOperand(0);
213 Value *B = Op0->getOperand(1);
214 Value *C = RHS;
215
216 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000217 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000218 // It does! Return "A op V" if it simplifies or is already available.
219 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000220 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000221 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000222 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000223 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000224 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000225 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 }
227 }
228
229 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
230 if (Op1 && Op1->getOpcode() == Opcode) {
231 Value *A = LHS;
232 Value *B = Op1->getOperand(0);
233 Value *C = Op1->getOperand(1);
234
235 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000236 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000237 // It does! Return "V op C" if it simplifies or is already available.
238 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000239 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000240 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000241 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000242 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000243 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000244 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000245 }
246 }
247
248 // The remaining transforms require commutativity as well as associativity.
249 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000250 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000251
252 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
253 if (Op0 && Op0->getOpcode() == Opcode) {
254 Value *A = Op0->getOperand(0);
255 Value *B = Op0->getOperand(1);
256 Value *C = RHS;
257
258 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000259 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000260 // It does! Return "V op B" if it simplifies or is already available.
261 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000262 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000263 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000264 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000265 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000266 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000267 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 }
269 }
270
271 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
272 if (Op1 && Op1->getOpcode() == Opcode) {
273 Value *A = LHS;
274 Value *B = Op1->getOperand(0);
275 Value *C = Op1->getOperand(1);
276
277 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000278 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000279 // It does! Return "B op V" if it simplifies or is already available.
280 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000281 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000282 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000283 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000284 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000285 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000286 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 }
288 }
289
Craig Topper9f008862014-04-15 04:59:12 +0000290 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000291}
292
Sanjay Patel472cc782016-01-11 22:14:42 +0000293/// In the case of a binary operation with a select instruction as an operand,
294/// try to simplify the binop by seeing whether evaluating it on both branches
295/// of the select results in the same value. Returns the common value if so,
296/// otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000297static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
298 Value *RHS, const Query &Q,
299 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000300 // Recursion is always used, so bail out at once if we already hit the limit.
301 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000302 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000303
Duncan Sandsb0579e92010-11-10 13:00:08 +0000304 SelectInst *SI;
305 if (isa<SelectInst>(LHS)) {
306 SI = cast<SelectInst>(LHS);
307 } else {
308 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309 SI = cast<SelectInst>(RHS);
310 }
311
312 // Evaluate the BinOp on the true and false branches of the select.
313 Value *TV;
314 Value *FV;
315 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000316 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000318 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000319 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000321 }
322
Duncan Sandse3c53952011-01-01 16:12:09 +0000323 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000324 // If they both failed to simplify then return null.
325 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000326 return TV;
327
328 // If one branch simplified to undef, return the other one.
329 if (TV && isa<UndefValue>(TV))
330 return FV;
331 if (FV && isa<UndefValue>(FV))
332 return TV;
333
334 // If applying the operation did not change the true and false select values,
335 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000336 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000337 return SI;
338
339 // If one branch simplified and the other did not, and the simplified
340 // value is equal to the unsimplified one, return the simplified value.
341 // For example, select (cond, X, X & Z) & Z -> X & Z.
342 if ((FV && !TV) || (TV && !FV)) {
343 // Check that the simplified value has the form "X op Y" where "op" is the
344 // same as the original operation.
345 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346 if (Simplified && Simplified->getOpcode() == Opcode) {
347 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348 // We already know that "op" is the same as for the simplified value. See
349 // if the operands match too. If so, return the simplified value.
350 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000353 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355 return Simplified;
356 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000357 Simplified->getOperand(1) == UnsimplifiedLHS &&
358 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000359 return Simplified;
360 }
361 }
362
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000364}
365
Sanjay Patel472cc782016-01-11 22:14:42 +0000366/// In the case of a comparison with a select instruction, try to simplify the
367/// comparison by seeing whether both branches of the select result in the same
368/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000369static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000370 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000371 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000372 // Recursion is always used, so bail out at once if we already hit the limit.
373 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000374 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000375
Duncan Sandsb0579e92010-11-10 13:00:08 +0000376 // Make sure the select is on the LHS.
377 if (!isa<SelectInst>(LHS)) {
378 std::swap(LHS, RHS);
379 Pred = CmpInst::getSwappedPredicate(Pred);
380 }
381 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000383 Value *Cond = SI->getCondition();
384 Value *TV = SI->getTrueValue();
385 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000386
Duncan Sands06504022011-02-03 09:37:39 +0000387 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000388 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000389 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000390 if (TCmp == Cond) {
391 // It not only simplified, it simplified to the select condition. Replace
392 // it with 'true'.
393 TCmp = getTrue(Cond->getType());
394 } else if (!TCmp) {
395 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
396 // condition then we can replace it with 'true'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000398 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000400 }
401
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000403 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000404 if (FCmp == Cond) {
405 // It not only simplified, it simplified to the select condition. Replace
406 // it with 'false'.
407 FCmp = getFalse(Cond->getType());
408 } else if (!FCmp) {
409 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
410 // condition then we can replace it with 'false'. Otherwise give up.
411 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000412 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000413 FCmp = getFalse(Cond->getType());
414 }
415
416 // If both sides simplified to the same value, then use it as the result of
417 // the original comparison.
418 if (TCmp == FCmp)
419 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000420
421 // The remaining cases only make sense if the select condition has the same
422 // type as the result of the comparison, so bail out if this is not so.
423 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000424 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000425 // If the false value simplified to false, then the result of the compare
426 // is equal to "Cond && TCmp". This also catches the case when the false
427 // value simplified to false and the true value to true, returning "Cond".
428 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000429 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000430 return V;
431 // If the true value simplified to true, then the result of the compare
432 // is equal to "Cond || FCmp".
433 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000434 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000435 return V;
436 // Finally, if the false value simplified to true and the true value to
437 // false, then the result of the compare is equal to "!Cond".
438 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
439 if (Value *V =
440 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000441 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000442 return V;
443
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000445}
446
Sanjay Patel472cc782016-01-11 22:14:42 +0000447/// In the case of a binary operation with an operand that is a PHI instruction,
448/// try to simplify the binop by seeing whether evaluating it on the incoming
449/// phi values yields the same result for every value. If so returns the common
450/// value, otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000451static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
452 Value *RHS, const Query &Q,
453 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000454 // Recursion is always used, so bail out at once if we already hit the limit.
455 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000456 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000457
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000458 PHINode *PI;
459 if (isa<PHINode>(LHS)) {
460 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000461 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000462 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000463 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000464 } else {
465 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
466 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000467 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000468 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000469 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 }
471
472 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000473 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000474 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000475 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000476 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000477 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000478 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
479 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480 // If the operation failed to simplify, or simplified to a different value
481 // to previously, then give up.
482 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000483 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000484 CommonValue = V;
485 }
486
487 return CommonValue;
488}
489
Sanjay Patel472cc782016-01-11 22:14:42 +0000490/// In the case of a comparison with a PHI instruction, try to simplify the
491/// comparison by seeing whether comparing with all of the incoming phi values
492/// yields the same result every time. If so returns the common result,
493/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000494static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000495 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000496 // Recursion is always used, so bail out at once if we already hit the limit.
497 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000498 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000499
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000500 // Make sure the phi is on the LHS.
501 if (!isa<PHINode>(LHS)) {
502 std::swap(LHS, RHS);
503 Pred = CmpInst::getSwappedPredicate(Pred);
504 }
505 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
506 PHINode *PI = cast<PHINode>(LHS);
507
Duncan Sands5ffc2982010-11-16 12:16:38 +0000508 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000509 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000510 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000511
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000513 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000514 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000515 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000516 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000517 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000518 // If the operation failed to simplify, or simplified to a different value
519 // to previously, then give up.
520 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000521 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000522 CommonValue = V;
523 }
524
525 return CommonValue;
526}
527
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000528static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
529 Value *&Op0, Value *&Op1,
530 const Query &Q) {
531 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
532 if (auto *CRHS = dyn_cast<Constant>(Op1))
533 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
534
535 // Canonicalize the constant to the RHS if this is a commutative operation.
536 if (Instruction::isCommutative(Opcode))
537 std::swap(Op0, Op1);
538 }
539 return nullptr;
540}
541
Sanjay Patel472cc782016-01-11 22:14:42 +0000542/// Given operands for an Add, see if we can fold the result.
543/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000544static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000545 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000546 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
547 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000548
Duncan Sands0a2c41682010-12-15 14:07:39 +0000549 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000550 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000551 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000552
Duncan Sands0a2c41682010-12-15 14:07:39 +0000553 // X + 0 -> X
554 if (match(Op1, m_Zero()))
555 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000556
Duncan Sands0a2c41682010-12-15 14:07:39 +0000557 // X + (Y - X) -> Y
558 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000559 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000560 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000561 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
562 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000563 return Y;
564
565 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000566 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000567 if (match(Op0, m_Not(m_Specific(Op1))) ||
568 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000569 return Constant::getAllOnesValue(Ty);
570
Craig Topperbcfd2d12017-04-20 16:56:25 +0000571 // add nsw/nuw (xor Y, signmask), signmask --> Y
Sanjay Patelfe672552017-02-18 21:59:09 +0000572 // The no-wrapping add guarantees that the top bit will be set by the add.
573 // Therefore, the xor must be clearing the already set sign bit of Y.
Craig Topperbcfd2d12017-04-20 16:56:25 +0000574 if ((isNSW || isNUW) && match(Op1, m_SignMask()) &&
575 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000576 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000577
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000578 /// i1 add -> xor.
Craig Topperaa5f5242017-04-06 05:28:41 +0000579 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000580 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000581 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000582
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000583 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000584 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000585 MaxRecurse))
586 return V;
587
Duncan Sandsb238de02010-11-19 09:20:39 +0000588 // Threading Add over selects and phi nodes is pointless, so don't bother.
589 // Threading over the select in "A + select(cond, B, C)" means evaluating
590 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
591 // only if B and C are equal. If B and C are equal then (since we assume
592 // that operands have already been simplified) "select(cond, B, C)" should
593 // have been simplified to the common value of B and C already. Analysing
594 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
595 // for threading over phi nodes.
596
Craig Topper9f008862014-04-15 04:59:12 +0000597 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000598}
599
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000600Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000601 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000602 const DominatorTree *DT, AssumptionCache *AC,
603 const Instruction *CxtI) {
604 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000605 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000606}
607
Chandler Carrutha0796552012-03-12 11:19:31 +0000608/// \brief Compute the base pointer and cumulative constant offsets for V.
609///
610/// This strips all constant offsets off of V, leaving it the base pointer, and
611/// accumulates the total constant offset applied in the returned constant. It
612/// returns 0 if V is not a pointer, and returns the constant '0' if there are
613/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000614///
615/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
616/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
617/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000618static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000619 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000620 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000621
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000623 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000624
625 // Even though we don't look through PHI nodes, we could be called on an
626 // instruction in an unreachable block, which may be on a cycle.
627 SmallPtrSet<Value *, 4> Visited;
628 Visited.insert(V);
629 do {
630 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000631 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000632 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000633 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000634 V = GEP->getPointerOperand();
635 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000636 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000637 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000638 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000639 break;
640 V = GA->getAliasee();
641 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000642 if (auto CS = CallSite(V))
643 if (Value *RV = CS.getReturnedArgOperand()) {
644 V = RV;
645 continue;
646 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000647 break;
648 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000649 assert(V->getType()->getScalarType()->isPointerTy() &&
650 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000651 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000652
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000653 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
654 if (V->getType()->isVectorTy())
655 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
656 OffsetIntPtr);
657 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000658}
659
660/// \brief Compute the constant difference between two pointer values.
661/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000662static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
663 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000664 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
665 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000666
667 // If LHS and RHS are not related via constant offsets to the same base
668 // value, there is nothing we can do here.
669 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000670 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000671
672 // Otherwise, the difference of LHS - RHS can be computed as:
673 // LHS - RHS
674 // = (LHSOffset + Base) - (RHSOffset + Base)
675 // = LHSOffset - RHSOffset
676 return ConstantExpr::getSub(LHSOffset, RHSOffset);
677}
678
Sanjay Patel472cc782016-01-11 22:14:42 +0000679/// Given operands for a Sub, see if we can fold the result.
680/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000681static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000682 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000683 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
684 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000685
686 // X - undef -> undef
687 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000688 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000689 return UndefValue::get(Op0->getType());
690
691 // X - 0 -> X
692 if (match(Op1, m_Zero()))
693 return Op0;
694
695 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000696 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000697 return Constant::getNullValue(Op0->getType());
698
Sanjay Patelefd88852016-10-19 21:23:45 +0000699 // Is this a negation?
700 if (match(Op0, m_Zero())) {
701 // 0 - X -> 0 if the sub is NUW.
702 if (isNUW)
703 return Op0;
704
705 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
706 APInt KnownZero(BitWidth, 0);
707 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000708 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topper6856d342017-03-30 22:10:54 +0000709 if (KnownZero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000710 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
711 // Op1 must be 0 because negating the minimum signed value is undefined.
712 if (isNSW)
713 return Op0;
714
715 // 0 - X -> X if X is 0 or the minimum signed value.
716 return Op1;
717 }
718 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000719
Duncan Sands99589d02011-01-18 11:50:19 +0000720 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
721 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000722 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000723 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
724 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000725 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000726 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000727 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000728 // It does, we successfully reassociated!
729 ++NumReassoc;
730 return W;
731 }
732 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000736 // It does, we successfully reassociated!
737 ++NumReassoc;
738 return W;
739 }
740 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000741
Duncan Sands99589d02011-01-18 11:50:19 +0000742 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
743 // For example, X - (X + 1) -> -1
744 X = Op0;
745 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
746 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000747 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000748 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000749 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000750 // It does, we successfully reassociated!
751 ++NumReassoc;
752 return W;
753 }
754 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000756 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000757 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000758 // It does, we successfully reassociated!
759 ++NumReassoc;
760 return W;
761 }
762 }
763
764 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
765 // For example, X - (X - Y) -> Y.
766 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000767 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
768 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000769 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000770 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000771 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000772 // It does, we successfully reassociated!
773 ++NumReassoc;
774 return W;
775 }
776
Duncan Sands395ac42d2012-03-13 14:07:05 +0000777 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
778 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
779 match(Op1, m_Trunc(m_Value(Y))))
780 if (X->getType() == Y->getType())
781 // See if "V === X - Y" simplifies.
782 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
783 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000784 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
785 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000786 // It does, return the simplified "trunc V".
787 return W;
788
789 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000790 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000791 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000792 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000793 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
794
Duncan Sands99589d02011-01-18 11:50:19 +0000795 // i1 sub -> xor.
Craig Topperaa5f5242017-04-06 05:28:41 +0000796 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000797 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000798 return V;
799
Duncan Sands0a2c41682010-12-15 14:07:39 +0000800 // Threading Sub over selects and phi nodes is pointless, so don't bother.
801 // Threading over the select in "A - select(cond, B, C)" means evaluating
802 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
803 // only if B and C are equal. If B and C are equal then (since we assume
804 // that operands have already been simplified) "select(cond, B, C)" should
805 // have been simplified to the common value of B and C already. Analysing
806 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
807 // for threading over phi nodes.
808
Craig Topper9f008862014-04-15 04:59:12 +0000809 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000810}
811
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000812Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000813 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000814 const DominatorTree *DT, AssumptionCache *AC,
815 const Instruction *CxtI) {
816 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000817 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000818}
819
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000820/// Given operands for an FAdd, see if we can fold the result. If not, this
821/// returns null.
822static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
823 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000824 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
825 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000826
827 // fadd X, -0 ==> X
828 if (match(Op1, m_NegZero()))
829 return Op0;
830
831 // fadd X, 0 ==> X, when we know X is not -0
832 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000833 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000834 return Op0;
835
836 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
837 // where nnan and ninf have to occur at least once somewhere in this
838 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000839 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000840 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
841 SubOp = Op1;
842 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
843 SubOp = Op0;
844 if (SubOp) {
845 Instruction *FSub = cast<Instruction>(SubOp);
846 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
847 (FMF.noInfs() || FSub->hasNoInfs()))
848 return Constant::getNullValue(Op0->getType());
849 }
850
Craig Topper9f008862014-04-15 04:59:12 +0000851 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852}
853
854/// Given operands for an FSub, see if we can fold the result. If not, this
855/// returns null.
856static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
857 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000858 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
859 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000860
861 // fsub X, 0 ==> X
862 if (match(Op1, m_Zero()))
863 return Op0;
864
865 // fsub X, -0 ==> X, when we know X is not -0
866 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000867 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000868 return Op0;
869
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000870 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000871 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000872 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
873 return X;
874
875 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000876 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000877 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
878 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000879
Benjamin Kramer228680d2015-06-14 21:01:20 +0000880 // fsub nnan x, x ==> 0.0
881 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000882 return Constant::getNullValue(Op0->getType());
883
Craig Topper9f008862014-04-15 04:59:12 +0000884 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000885}
886
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000887/// Given the operands for an FMul, see if we can fold the result
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000888static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
889 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000890 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
891 return C;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000892
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000893 // fmul X, 1.0 ==> X
894 if (match(Op1, m_FPOne()))
895 return Op0;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000896
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000897 // fmul nnan nsz X, 0 ==> 0
898 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
899 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000900
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000901 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000902}
903
Sanjay Patel472cc782016-01-11 22:14:42 +0000904/// Given operands for a Mul, see if we can fold the result.
905/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000906static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
907 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000908 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
909 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000910
911 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000912 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000913 return Constant::getNullValue(Op0->getType());
914
915 // X * 0 -> 0
916 if (match(Op1, m_Zero()))
917 return Op1;
918
919 // X * 1 -> X
920 if (match(Op1, m_One()))
921 return Op0;
922
Duncan Sandsb67edc62011-01-30 18:03:50 +0000923 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000924 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000925 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
926 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
927 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000928
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000929 // i1 mul -> and.
Craig Topper2f1e1c32017-04-06 17:33:37 +0000930 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000931 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000932 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000933
934 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000935 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000936 MaxRecurse))
937 return V;
938
939 // Mul distributes over Add. Try some generic simplifications based on this.
940 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000941 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000942 return V;
943
944 // If the operation is with the result of a select instruction, check whether
945 // operating on either branch of the select always yields the same value.
946 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000947 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000948 MaxRecurse))
949 return V;
950
951 // If the operation is with the result of a phi instruction, check whether
952 // operating on all incoming values of the phi always yields the same value.
953 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000954 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000955 MaxRecurse))
956 return V;
957
Craig Topper9f008862014-04-15 04:59:12 +0000958 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000959}
960
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000961Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000962 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000963 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000964 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000965 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000966 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000967 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000968}
969
970Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000972 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000973 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000974 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000975 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000976 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000977}
978
Chandler Carruth66b31302015-01-04 12:03:27 +0000979Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000981 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000982 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000983 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000984 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000985 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000986}
987
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000988Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000989 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000990 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000991 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000992 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000993 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000994}
995
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000996/// Check for common or similar folds of integer division or integer remainder.
997static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
998 Type *Ty = Op0->getType();
999
1000 // X / undef -> undef
1001 // X % undef -> undef
1002 if (match(Op1, m_Undef()))
1003 return Op1;
1004
1005 // X / 0 -> undef
1006 // X % 0 -> undef
1007 // We don't need to preserve faults!
1008 if (match(Op1, m_Zero()))
1009 return UndefValue::get(Ty);
1010
Sanjay Patel2b1f6f42017-03-09 16:20:52 +00001011 // If any element of a constant divisor vector is zero, the whole op is undef.
1012 auto *Op1C = dyn_cast<Constant>(Op1);
1013 if (Op1C && Ty->isVectorTy()) {
1014 unsigned NumElts = Ty->getVectorNumElements();
1015 for (unsigned i = 0; i != NumElts; ++i) {
1016 Constant *Elt = Op1C->getAggregateElement(i);
1017 if (Elt && Elt->isNullValue())
1018 return UndefValue::get(Ty);
1019 }
1020 }
1021
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001022 // undef / X -> 0
1023 // undef % X -> 0
1024 if (match(Op0, m_Undef()))
1025 return Constant::getNullValue(Ty);
1026
1027 // 0 / X -> 0
1028 // 0 % X -> 0
1029 if (match(Op0, m_Zero()))
1030 return Op0;
1031
1032 // X / X -> 1
1033 // X % X -> 0
1034 if (Op0 == Op1)
1035 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1036
1037 // X / 1 -> X
1038 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +00001039 // If this is a boolean op (single-bit element type), we can't have
1040 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
1041 if (match(Op1, m_One()) || Ty->getScalarType()->isIntegerTy(1))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001042 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1043
1044 return nullptr;
1045}
1046
Sanjay Patel472cc782016-01-11 22:14:42 +00001047/// Given operands for an SDiv or UDiv, see if we can fold the result.
1048/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001049static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001050 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001051 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1052 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +00001053
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001054 if (Value *V = simplifyDivRem(Op0, Op1, true))
1055 return V;
1056
Duncan Sands65995fa2011-01-28 18:50:50 +00001057 bool isSigned = Opcode == Instruction::SDiv;
1058
Duncan Sands771e82a2011-01-28 16:51:11 +00001059 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001060 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001061 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1062 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001063 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001064 // If the Mul knows it does not overflow, then we are good to go.
1065 if ((isSigned && Mul->hasNoSignedWrap()) ||
1066 (!isSigned && Mul->hasNoUnsignedWrap()))
1067 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001068 // If X has the form X = A / Y then X * Y cannot overflow.
1069 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1070 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1071 return X;
1072 }
1073
Duncan Sands65995fa2011-01-28 18:50:50 +00001074 // (X rem Y) / Y -> 0
1075 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1076 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1077 return Constant::getNullValue(Op0->getType());
1078
David Majnemercb9d5962014-10-11 10:20:01 +00001079 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1080 ConstantInt *C1, *C2;
1081 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1082 match(Op1, m_ConstantInt(C2))) {
1083 bool Overflow;
Craig Topper9b71a402017-04-19 21:09:45 +00001084 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
David Majnemercb9d5962014-10-11 10:20:01 +00001085 if (Overflow)
1086 return Constant::getNullValue(Op0->getType());
1087 }
1088
Duncan Sands65995fa2011-01-28 18:50:50 +00001089 // If the operation is with the result of a select instruction, check whether
1090 // operating on either branch of the select always yields the same value.
1091 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001092 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001093 return V;
1094
1095 // If the operation is with the result of a phi instruction, check whether
1096 // operating on all incoming values of the phi always yields the same value.
1097 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001098 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001099 return V;
1100
Craig Topper9f008862014-04-15 04:59:12 +00001101 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001102}
1103
Sanjay Patel472cc782016-01-11 22:14:42 +00001104/// Given operands for an SDiv, see if we can fold the result.
1105/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001106static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1107 unsigned MaxRecurse) {
1108 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001109 return V;
1110
Craig Topper9f008862014-04-15 04:59:12 +00001111 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001112}
1113
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001114Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001115 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001116 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001117 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001118 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001119 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001120}
1121
Sanjay Patel472cc782016-01-11 22:14:42 +00001122/// Given operands for a UDiv, see if we can fold the result.
1123/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001124static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1125 unsigned MaxRecurse) {
1126 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001127 return V;
1128
David Majnemer63da0c22017-01-06 22:58:02 +00001129 // udiv %V, C -> 0 if %V < C
1130 if (MaxRecurse) {
1131 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1132 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1133 if (C->isAllOnesValue()) {
1134 return Constant::getNullValue(Op0->getType());
1135 }
1136 }
1137 }
1138
Craig Topper9f008862014-04-15 04:59:12 +00001139 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001140}
1141
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001143 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001144 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001145 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001146 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001147 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001148}
1149
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001150static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1151 const Query &Q, unsigned) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001152 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
1153 return C;
1154
Frits van Bommelc2549662011-01-29 15:26:31 +00001155 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001156 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001157 return Op0;
1158
1159 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001160 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001161 return Op1;
1162
Zia Ansari394cef82016-12-08 23:27:40 +00001163 // X / 1.0 -> X
1164 if (match(Op1, m_FPOne()))
1165 return Op0;
1166
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001167 // 0 / X -> 0
1168 // Requires that NaNs are off (X could be zero) and signed zeroes are
1169 // ignored (X could be positive or negative, so the output sign is unknown).
1170 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1171 return Op0;
1172
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001173 if (FMF.noNaNs()) {
1174 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001175 if (Op0 == Op1)
1176 return ConstantFP::get(Op0->getType(), 1.0);
1177
1178 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001179 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001180 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1181 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1182 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1183 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1184 BinaryOperator::getFNegArgument(Op1) == Op0))
1185 return ConstantFP::get(Op0->getType(), -1.0);
1186 }
1187
Craig Topper9f008862014-04-15 04:59:12 +00001188 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001189}
1190
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001191Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001192 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001193 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001194 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001195 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001196 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001197 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001198}
1199
Sanjay Patel472cc782016-01-11 22:14:42 +00001200/// Given operands for an SRem or URem, see if we can fold the result.
1201/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001202static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001203 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001204 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1205 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001206
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001207 if (Value *V = simplifyDivRem(Op0, Op1, false))
1208 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001209
David Majnemerb435a422014-09-17 04:16:35 +00001210 // (X % Y) % Y -> X % Y
1211 if ((Opcode == Instruction::SRem &&
1212 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1213 (Opcode == Instruction::URem &&
1214 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001215 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001216
Duncan Sandsa3e36992011-05-02 16:27:02 +00001217 // If the operation is with the result of a select instruction, check whether
1218 // operating on either branch of the select always yields the same value.
1219 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001220 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001221 return V;
1222
1223 // If the operation is with the result of a phi instruction, check whether
1224 // operating on all incoming values of the phi always yields the same value.
1225 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001226 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001227 return V;
1228
Craig Topper9f008862014-04-15 04:59:12 +00001229 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230}
1231
Sanjay Patel472cc782016-01-11 22:14:42 +00001232/// Given operands for an SRem, see if we can fold the result.
1233/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001234static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1235 unsigned MaxRecurse) {
1236 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001237 return V;
1238
Craig Topper9f008862014-04-15 04:59:12 +00001239 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001240}
1241
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001243 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001244 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001245 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001246 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001247 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248}
1249
Sanjay Patel472cc782016-01-11 22:14:42 +00001250/// Given operands for a URem, see if we can fold the result.
1251/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001252static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001253 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001254 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001255 return V;
1256
David Majnemer8c0e62f2017-01-06 21:23:51 +00001257 // urem %V, C -> %V if %V < C
1258 if (MaxRecurse) {
1259 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1260 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1261 if (C->isAllOnesValue()) {
1262 return Op0;
1263 }
1264 }
1265 }
1266
Craig Topper9f008862014-04-15 04:59:12 +00001267 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001268}
1269
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001270Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001271 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001272 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001273 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001274 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001275 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001276}
1277
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001278static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001279 const Query &Q, unsigned) {
1280 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
1281 return C;
1282
Duncan Sandsa3e36992011-05-02 16:27:02 +00001283 // undef % X -> undef (the undef could be a snan).
1284 if (match(Op0, m_Undef()))
1285 return Op0;
1286
1287 // X % undef -> undef
1288 if (match(Op1, m_Undef()))
1289 return Op1;
1290
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001291 // 0 % X -> 0
1292 // Requires that NaNs are off (X could be zero) and signed zeroes are
1293 // ignored (X could be positive or negative, so the output sign is unknown).
1294 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1295 return Op0;
1296
Craig Topper9f008862014-04-15 04:59:12 +00001297 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001298}
1299
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001300Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001301 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001302 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001303 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001304 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001305 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001306 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001307}
1308
Sanjay Patel472cc782016-01-11 22:14:42 +00001309/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001310static bool isUndefShift(Value *Amount) {
1311 Constant *C = dyn_cast<Constant>(Amount);
1312 if (!C)
1313 return false;
1314
1315 // X shift by undef -> undef because it may shift by the bitwidth.
1316 if (isa<UndefValue>(C))
1317 return true;
1318
1319 // Shifting by the bitwidth or more is undefined.
1320 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1321 if (CI->getValue().getLimitedValue() >=
1322 CI->getType()->getScalarSizeInBits())
1323 return true;
1324
1325 // If all lanes of a vector shift are undefined the whole shift is.
1326 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1327 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1328 if (!isUndefShift(C->getAggregateElement(I)))
1329 return false;
1330 return true;
1331 }
1332
1333 return false;
1334}
1335
Sanjay Patel472cc782016-01-11 22:14:42 +00001336/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1337/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001338static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1339 Value *Op1, const Query &Q, unsigned MaxRecurse) {
1340 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1341 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001342
Duncan Sands571fd9a2011-01-14 14:44:12 +00001343 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001344 if (match(Op0, m_Zero()))
1345 return Op0;
1346
Duncan Sands571fd9a2011-01-14 14:44:12 +00001347 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001348 if (match(Op1, m_Zero()))
1349 return Op0;
1350
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001351 // Fold undefined shifts.
1352 if (isUndefShift(Op1))
1353 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001354
Duncan Sands571fd9a2011-01-14 14:44:12 +00001355 // If the operation is with the result of a select instruction, check whether
1356 // operating on either branch of the select always yields the same value.
1357 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001358 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001359 return V;
1360
1361 // If the operation is with the result of a phi instruction, check whether
1362 // operating on all incoming values of the phi always yields the same value.
1363 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001364 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001365 return V;
1366
Sanjay Patel6786bc52016-05-10 20:46:54 +00001367 // If any bits in the shift amount make that value greater than or equal to
1368 // the number of bits in the type, the shift is undefined.
1369 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1370 APInt KnownZero(BitWidth, 0);
1371 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001372 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001373 if (KnownOne.getLimitedValue() >= BitWidth)
1374 return UndefValue::get(Op0->getType());
1375
1376 // If all valid bits in the shift amount are known zero, the first operand is
1377 // unchanged.
1378 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
Craig Topperf3dbd172017-04-25 17:46:30 +00001379 if (KnownZero.countTrailingOnes() >= NumValidShiftBits)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001380 return Op0;
1381
Craig Topper9f008862014-04-15 04:59:12 +00001382 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001383}
1384
David Majnemerbf7550e2014-11-05 00:59:59 +00001385/// \brief Given operands for an Shl, LShr or AShr, see if we can
1386/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001387static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1388 Value *Op1, bool isExact, const Query &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001389 unsigned MaxRecurse) {
1390 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1391 return V;
1392
1393 // X >> X -> 0
1394 if (Op0 == Op1)
1395 return Constant::getNullValue(Op0->getType());
1396
David Majnemer65c52ae2014-12-17 01:54:33 +00001397 // undef >> X -> 0
1398 // undef >> X -> undef (if it's exact)
1399 if (match(Op0, m_Undef()))
1400 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1401
David Majnemerbf7550e2014-11-05 00:59:59 +00001402 // The low bit cannot be shifted out of an exact shift if it is set.
1403 if (isExact) {
1404 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1405 APInt Op0KnownZero(BitWidth, 0);
1406 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001407 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1408 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001409 if (Op0KnownOne[0])
1410 return Op0;
1411 }
1412
1413 return nullptr;
1414}
1415
Sanjay Patel472cc782016-01-11 22:14:42 +00001416/// Given operands for an Shl, see if we can fold the result.
1417/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001418static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001419 const Query &Q, unsigned MaxRecurse) {
1420 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001421 return V;
1422
1423 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001424 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001425 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001426 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001427
Chris Lattner9e4aa022011-02-09 17:15:04 +00001428 // (X >> A) << A -> X
1429 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001430 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001431 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001432 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001433}
1434
Chris Lattner9e4aa022011-02-09 17:15:04 +00001435Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001436 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001437 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001438 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001439 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001440 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001441}
1442
Sanjay Patel472cc782016-01-11 22:14:42 +00001443/// Given operands for an LShr, see if we can fold the result.
1444/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001445static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001446 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001447 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1448 MaxRecurse))
1449 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001450
Chris Lattner9e4aa022011-02-09 17:15:04 +00001451 // (X << A) >> A -> X
1452 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001453 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001454 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001455
Craig Topper9f008862014-04-15 04:59:12 +00001456 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001457}
1458
Chris Lattner9e4aa022011-02-09 17:15:04 +00001459Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001460 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001461 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001462 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001463 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001464 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001465 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001466}
1467
Sanjay Patel472cc782016-01-11 22:14:42 +00001468/// Given operands for an AShr, see if we can fold the result.
1469/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001470static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001471 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001472 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1473 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001474 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001475
1476 // all ones >>a X -> all ones
1477 if (match(Op0, m_AllOnes()))
1478 return Op0;
1479
Chris Lattner9e4aa022011-02-09 17:15:04 +00001480 // (X << A) >> A -> X
1481 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001482 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001483 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001484
Suyog Sarda68862412014-07-17 06:28:15 +00001485 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001486 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001487 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1488 return Op0;
1489
Craig Topper9f008862014-04-15 04:59:12 +00001490 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001491}
1492
Chris Lattner9e4aa022011-02-09 17:15:04 +00001493Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001494 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001495 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001496 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001497 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001498 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001499 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001500}
1501
David Majnemer1af36e52014-12-06 10:51:40 +00001502static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1503 ICmpInst *UnsignedICmp, bool IsAnd) {
1504 Value *X, *Y;
1505
1506 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001507 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1508 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001509 return nullptr;
1510
1511 ICmpInst::Predicate UnsignedPred;
1512 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1513 ICmpInst::isUnsigned(UnsignedPred))
1514 ;
1515 else if (match(UnsignedICmp,
1516 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1517 ICmpInst::isUnsigned(UnsignedPred))
1518 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1519 else
1520 return nullptr;
1521
1522 // X < Y && Y != 0 --> X < Y
1523 // X < Y || Y != 0 --> Y != 0
1524 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1525 return IsAnd ? UnsignedICmp : ZeroICmp;
1526
1527 // X >= Y || Y != 0 --> true
1528 // X >= Y || Y == 0 --> X >= Y
1529 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1530 if (EqPred == ICmpInst::ICMP_NE)
1531 return getTrue(UnsignedICmp->getType());
1532 return UnsignedICmp;
1533 }
1534
David Majnemerd5b3aa42014-12-08 18:30:43 +00001535 // X < Y && Y == 0 --> false
1536 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1537 IsAnd)
1538 return getFalse(UnsignedICmp->getType());
1539
David Majnemer1af36e52014-12-06 10:51:40 +00001540 return nullptr;
1541}
1542
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001543/// Commuted variants are assumed to be handled by calling this function again
1544/// with the parameters swapped.
1545static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1546 ICmpInst::Predicate Pred0, Pred1;
1547 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001548 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1549 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001550 return nullptr;
1551
1552 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1553 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1554 // can eliminate Op1 from this 'and'.
1555 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1556 return Op0;
1557
1558 // Check for any combination of predicates that are guaranteed to be disjoint.
1559 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1560 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1561 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1562 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1563 return getFalse(Op0->getType());
1564
1565 return nullptr;
1566}
1567
1568/// Commuted variants are assumed to be handled by calling this function again
1569/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001570static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001571 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1572 return X;
1573
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001574 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1575 return X;
1576
Sanjay Patel35c362e2017-04-24 21:52:39 +00001577 // FIXME: This should be shared with or-of-icmps.
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001578 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001579 Type *ITy = Op0->getType();
1580 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001581 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001582 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001583 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1584 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1585 // Make a constant range that's the intersection of the two icmp ranges.
1586 // If the intersection is empty, we know that the result is false.
Sanjay Patel35c362e2017-04-24 21:52:39 +00001587 auto Range0 = ConstantRange::makeExactICmpRegion(Pred0, *C0);
1588 auto Range1 = ConstantRange::makeExactICmpRegion(Pred1, *C1);
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001589 if (Range0.intersectWith(Range1).isEmptySet())
1590 return getFalse(ITy);
Sanjay Patel35c362e2017-04-24 21:52:39 +00001591
1592 // If a range is a superset of the other, the smaller set is all we need.
1593 if (Range0.contains(Range1))
1594 return Op1;
1595 if (Range1.contains(Range0))
1596 return Op0;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001597 }
1598
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001599 // (icmp (add V, C0), C1) & (icmp V, C0)
1600 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001601 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001602
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001603 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001604 return nullptr;
1605
David Majnemera315bd82014-09-15 08:15:28 +00001606 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001607 if (AddInst->getOperand(1) != Op1->getOperand(1))
1608 return nullptr;
1609
David Majnemera315bd82014-09-15 08:15:28 +00001610 bool isNSW = AddInst->hasNoSignedWrap();
1611 bool isNUW = AddInst->hasNoUnsignedWrap();
1612
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001613 const APInt Delta = *C1 - *C0;
1614 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001615 if (Delta == 2) {
1616 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1617 return getFalse(ITy);
1618 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1619 return getFalse(ITy);
1620 }
1621 if (Delta == 1) {
1622 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1623 return getFalse(ITy);
1624 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1625 return getFalse(ITy);
1626 }
1627 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001628 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001629 if (Delta == 2)
1630 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1631 return getFalse(ITy);
1632 if (Delta == 1)
1633 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1634 return getFalse(ITy);
1635 }
1636
1637 return nullptr;
1638}
1639
Sanjay Patel472cc782016-01-11 22:14:42 +00001640/// Given operands for an And, see if we can fold the result.
1641/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001642static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001643 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001644 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1645 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001646
Chris Lattnera71e9d62009-11-10 00:55:12 +00001647 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001648 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001649 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001650
Chris Lattnera71e9d62009-11-10 00:55:12 +00001651 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001652 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001653 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001654
Duncan Sandsc89ac072010-11-17 18:52:15 +00001655 // X & 0 = 0
1656 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001657 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001658
Duncan Sandsc89ac072010-11-17 18:52:15 +00001659 // X & -1 = X
1660 if (match(Op1, m_AllOnes()))
1661 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001662
Chris Lattnera71e9d62009-11-10 00:55:12 +00001663 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001664 if (match(Op0, m_Not(m_Specific(Op1))) ||
1665 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001666 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001667
Chris Lattnera71e9d62009-11-10 00:55:12 +00001668 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001669 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001670 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001671 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001672 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001673
Chris Lattnera71e9d62009-11-10 00:55:12 +00001674 // A & (A | ?) = A
1675 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001676 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001677 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001678
Duncan Sandsba286d72011-10-26 20:55:21 +00001679 // A & (-A) = A if A is a power of two or zero.
1680 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1681 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001682 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1683 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001684 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001685 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1686 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001687 return Op1;
1688 }
1689
David Majnemera315bd82014-09-15 08:15:28 +00001690 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1691 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1692 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1693 return V;
1694 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1695 return V;
1696 }
1697 }
1698
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001699 // The compares may be hidden behind casts. Look through those and try the
1700 // same folds as above.
1701 auto *Cast0 = dyn_cast<CastInst>(Op0);
1702 auto *Cast1 = dyn_cast<CastInst>(Op1);
1703 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1704 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1705 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1706 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1707 if (Cmp0 && Cmp1) {
1708 Instruction::CastOps CastOpc = Cast0->getOpcode();
1709 Type *ResultType = Cast0->getType();
1710 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1711 return ConstantExpr::getCast(CastOpc, V, ResultType);
1712 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1713 return ConstantExpr::getCast(CastOpc, V, ResultType);
1714 }
1715 }
1716
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001717 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001718 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1719 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001720 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001721
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001722 // And distributes over Or. Try some generic simplifications based on this.
1723 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001724 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001725 return V;
1726
1727 // And distributes over Xor. Try some generic simplifications based on this.
1728 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001729 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001730 return V;
1731
Duncan Sandsb0579e92010-11-10 13:00:08 +00001732 // If the operation is with the result of a select instruction, check whether
1733 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001734 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001735 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1736 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001737 return V;
1738
1739 // If the operation is with the result of a phi instruction, check whether
1740 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001741 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001742 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001743 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001744 return V;
1745
Craig Topper9f008862014-04-15 04:59:12 +00001746 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001747}
1748
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001749Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001750 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001751 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001752 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001753 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001754 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001755}
1756
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001757/// Commuted variants are assumed to be handled by calling this function again
1758/// with the parameters swapped.
1759static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1760 ICmpInst::Predicate Pred0, Pred1;
1761 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001762 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1763 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001764 return nullptr;
1765
1766 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1767 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1768 // can eliminate Op0 from this 'or'.
1769 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1770 return Op1;
1771
1772 // Check for any combination of predicates that cover the entire range of
1773 // possibilities.
1774 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1775 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1776 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1777 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1778 return getTrue(Op0->getType());
1779
1780 return nullptr;
1781}
1782
1783/// Commuted variants are assumed to be handled by calling this function again
1784/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001785static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001786 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1787 return X;
1788
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001789 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1790 return X;
1791
Sanjay Patel220a8732016-09-28 14:27:21 +00001792 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001793 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001794 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001795 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001796 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001797 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001798
Sanjay Patel220a8732016-09-28 14:27:21 +00001799 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1800 return nullptr;
1801
1802 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1803 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001804 return nullptr;
1805
1806 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001807 bool isNSW = AddInst->hasNoSignedWrap();
1808 bool isNUW = AddInst->hasNoUnsignedWrap();
1809
Sanjay Patel220a8732016-09-28 14:27:21 +00001810 const APInt Delta = *C1 - *C0;
1811 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001812 if (Delta == 2) {
1813 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1814 return getTrue(ITy);
1815 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1816 return getTrue(ITy);
1817 }
1818 if (Delta == 1) {
1819 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1820 return getTrue(ITy);
1821 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1822 return getTrue(ITy);
1823 }
1824 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001825 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001826 if (Delta == 2)
1827 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1828 return getTrue(ITy);
1829 if (Delta == 1)
1830 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1831 return getTrue(ITy);
1832 }
1833
1834 return nullptr;
1835}
1836
Sanjay Patel472cc782016-01-11 22:14:42 +00001837/// Given operands for an Or, see if we can fold the result.
1838/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001839static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1840 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001841 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1842 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001843
Chris Lattnera71e9d62009-11-10 00:55:12 +00001844 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001845 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001846 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001847
Chris Lattnera71e9d62009-11-10 00:55:12 +00001848 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001849 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001850 return Op0;
1851
Duncan Sandsc89ac072010-11-17 18:52:15 +00001852 // X | 0 = X
1853 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001854 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001855
Duncan Sandsc89ac072010-11-17 18:52:15 +00001856 // X | -1 = -1
1857 if (match(Op1, m_AllOnes()))
1858 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001859
Chris Lattnera71e9d62009-11-10 00:55:12 +00001860 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001861 if (match(Op0, m_Not(m_Specific(Op1))) ||
1862 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001863 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001864
Chris Lattnera71e9d62009-11-10 00:55:12 +00001865 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001866 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001867 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001868 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001869 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001870
Chris Lattnera71e9d62009-11-10 00:55:12 +00001871 // A | (A & ?) = A
1872 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001873 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001874 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001875
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001876 // ~(A & ?) | A = -1
1877 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1878 (A == Op1 || B == Op1))
1879 return Constant::getAllOnesValue(Op1->getType());
1880
1881 // A | ~(A & ?) = -1
1882 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1883 (A == Op0 || B == Op0))
1884 return Constant::getAllOnesValue(Op0->getType());
1885
Sanjay Patel08892252017-04-24 18:24:36 +00001886 // (A & ~B) | (A ^ B) -> (A ^ B)
1887 // (~B & A) | (A ^ B) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001888 // (A & ~B) | (B ^ A) -> (B ^ A)
1889 // (~B & A) | (B ^ A) -> (B ^ A)
1890 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1891 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1892 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001893 return Op1;
1894
1895 // Commute the 'or' operands.
1896 // (A ^ B) | (A & ~B) -> (A ^ B)
1897 // (A ^ B) | (~B & A) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001898 // (B ^ A) | (A & ~B) -> (B ^ A)
1899 // (B ^ A) | (~B & A) -> (B ^ A)
1900 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1901 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1902 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001903 return Op0;
1904
David Majnemera315bd82014-09-15 08:15:28 +00001905 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1906 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1907 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1908 return V;
1909 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1910 return V;
1911 }
1912 }
1913
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001914 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001915 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1916 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001917 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001918
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001919 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001920 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1921 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001922 return V;
1923
Duncan Sandsb0579e92010-11-10 13:00:08 +00001924 // If the operation is with the result of a select instruction, check whether
1925 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001926 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001927 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001928 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001929 return V;
1930
Nick Lewycky8561a492014-06-19 03:51:46 +00001931 // (A & C)|(B & D)
1932 Value *C = nullptr, *D = nullptr;
1933 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1934 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1935 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1936 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1937 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1938 // (A & C1)|(B & C2)
1939 // If we have: ((V + N) & C1) | (V & C2)
1940 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1941 // replace with V+N.
1942 Value *V1, *V2;
1943 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1944 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1945 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001946 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001947 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001948 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001949 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001950 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001951 return A;
1952 }
1953 // Or commutes, try both ways.
1954 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1955 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1956 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001957 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001958 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001959 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001960 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001961 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001962 return B;
1963 }
1964 }
1965 }
1966
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001967 // If the operation is with the result of a phi instruction, check whether
1968 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001969 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001970 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001971 return V;
1972
Craig Topper9f008862014-04-15 04:59:12 +00001973 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001974}
1975
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001976Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001977 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001978 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001979 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001980 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001981 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001982}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001983
Sanjay Patel472cc782016-01-11 22:14:42 +00001984/// Given operands for a Xor, see if we can fold the result.
1985/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001986static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1987 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001988 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
1989 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001990
1991 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001992 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001993 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001994
1995 // A ^ 0 = A
1996 if (match(Op1, m_Zero()))
1997 return Op0;
1998
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001999 // A ^ A = 0
2000 if (Op0 == Op1)
2001 return Constant::getNullValue(Op0->getType());
2002
Duncan Sandsc89ac072010-11-17 18:52:15 +00002003 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00002004 if (match(Op0, m_Not(m_Specific(Op1))) ||
2005 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002006 return Constant::getAllOnesValue(Op0->getType());
2007
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002008 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002009 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2010 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002011 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002012
Duncan Sandsb238de02010-11-19 09:20:39 +00002013 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2014 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2015 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2016 // only if B and C are equal. If B and C are equal then (since we assume
2017 // that operands have already been simplified) "select(cond, B, C)" should
2018 // have been simplified to the common value of B and C already. Analysing
2019 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2020 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002021
Craig Topper9f008862014-04-15 04:59:12 +00002022 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002023}
2024
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002025Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002026 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002027 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002028 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002029 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002030 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002031}
2032
Chris Lattner229907c2011-07-18 04:54:35 +00002033static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002034 return CmpInst::makeCmpResultType(Op->getType());
2035}
2036
Sanjay Patel472cc782016-01-11 22:14:42 +00002037/// Rummage around inside V looking for something equivalent to the comparison
2038/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2039/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002040static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2041 Value *LHS, Value *RHS) {
2042 SelectInst *SI = dyn_cast<SelectInst>(V);
2043 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002044 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002045 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2046 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002047 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002048 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2049 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2050 return Cmp;
2051 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2052 LHS == CmpRHS && RHS == CmpLHS)
2053 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002054 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002055}
2056
Dan Gohman9631d902013-02-01 00:49:06 +00002057// A significant optimization not implemented here is assuming that alloca
2058// addresses are not equal to incoming argument values. They don't *alias*,
2059// as we say, but that doesn't mean they aren't equal, so we take a
2060// conservative approach.
2061//
2062// This is inspired in part by C++11 5.10p1:
2063// "Two pointers of the same type compare equal if and only if they are both
2064// null, both point to the same function, or both represent the same
2065// address."
2066//
2067// This is pretty permissive.
2068//
2069// It's also partly due to C11 6.5.9p6:
2070// "Two pointers compare equal if and only if both are null pointers, both are
2071// pointers to the same object (including a pointer to an object and a
2072// subobject at its beginning) or function, both are pointers to one past the
2073// last element of the same array object, or one is a pointer to one past the
2074// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002075// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002076// object in the address space.)
2077//
2078// C11's version is more restrictive, however there's no reason why an argument
2079// couldn't be a one-past-the-end value for a stack object in the caller and be
2080// equal to the beginning of a stack object in the callee.
2081//
2082// If the C and C++ standards are ever made sufficiently restrictive in this
2083// area, it may be possible to update LLVM's semantics accordingly and reinstate
2084// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002085static Constant *
2086computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2087 const DominatorTree *DT, CmpInst::Predicate Pred,
2088 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002089 // First, skip past any trivial no-ops.
2090 LHS = LHS->stripPointerCasts();
2091 RHS = RHS->stripPointerCasts();
2092
2093 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002094 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002095 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2096 return ConstantInt::get(GetCompareTy(LHS),
2097 !CmpInst::isTrueWhenEqual(Pred));
2098
Chandler Carruth8059c842012-03-25 21:28:14 +00002099 // We can only fold certain predicates on pointer comparisons.
2100 switch (Pred) {
2101 default:
Craig Topper9f008862014-04-15 04:59:12 +00002102 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002103
2104 // Equality comaprisons are easy to fold.
2105 case CmpInst::ICMP_EQ:
2106 case CmpInst::ICMP_NE:
2107 break;
2108
2109 // We can only handle unsigned relational comparisons because 'inbounds' on
2110 // a GEP only protects against unsigned wrapping.
2111 case CmpInst::ICMP_UGT:
2112 case CmpInst::ICMP_UGE:
2113 case CmpInst::ICMP_ULT:
2114 case CmpInst::ICMP_ULE:
2115 // However, we have to switch them to their signed variants to handle
2116 // negative indices from the base pointer.
2117 Pred = ICmpInst::getSignedPredicate(Pred);
2118 break;
2119 }
2120
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002121 // Strip off any constant offsets so that we can reason about them.
2122 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2123 // here and compare base addresses like AliasAnalysis does, however there are
2124 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2125 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2126 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002127 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2128 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002129
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002130 // If LHS and RHS are related via constant offsets to the same base
2131 // value, we can replace it with an icmp which just compares the offsets.
2132 if (LHS == RHS)
2133 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002134
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002135 // Various optimizations for (in)equality comparisons.
2136 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2137 // Different non-empty allocations that exist at the same time have
2138 // different addresses (if the program can tell). Global variables always
2139 // exist, so they always exist during the lifetime of each other and all
2140 // allocas. Two different allocas usually have different addresses...
2141 //
2142 // However, if there's an @llvm.stackrestore dynamically in between two
2143 // allocas, they may have the same address. It's tempting to reduce the
2144 // scope of the problem by only looking at *static* allocas here. That would
2145 // cover the majority of allocas while significantly reducing the likelihood
2146 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2147 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2148 // an entry block. Also, if we have a block that's not attached to a
2149 // function, we can't tell if it's "static" under the current definition.
2150 // Theoretically, this problem could be fixed by creating a new kind of
2151 // instruction kind specifically for static allocas. Such a new instruction
2152 // could be required to be at the top of the entry block, thus preventing it
2153 // from being subject to a @llvm.stackrestore. Instcombine could even
2154 // convert regular allocas into these special allocas. It'd be nifty.
2155 // However, until then, this problem remains open.
2156 //
2157 // So, we'll assume that two non-empty allocas have different addresses
2158 // for now.
2159 //
2160 // With all that, if the offsets are within the bounds of their allocations
2161 // (and not one-past-the-end! so we can't use inbounds!), and their
2162 // allocations aren't the same, the pointers are not equal.
2163 //
2164 // Note that it's not necessary to check for LHS being a global variable
2165 // address, due to canonicalization and constant folding.
2166 if (isa<AllocaInst>(LHS) &&
2167 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002168 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2169 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002170 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002171 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002172 getObjectSize(LHS, LHSSize, DL, TLI) &&
2173 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002174 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2175 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002176 if (!LHSOffsetValue.isNegative() &&
2177 !RHSOffsetValue.isNegative() &&
2178 LHSOffsetValue.ult(LHSSize) &&
2179 RHSOffsetValue.ult(RHSSize)) {
2180 return ConstantInt::get(GetCompareTy(LHS),
2181 !CmpInst::isTrueWhenEqual(Pred));
2182 }
2183 }
2184
2185 // Repeat the above check but this time without depending on DataLayout
2186 // or being able to compute a precise size.
2187 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2188 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2189 LHSOffset->isNullValue() &&
2190 RHSOffset->isNullValue())
2191 return ConstantInt::get(GetCompareTy(LHS),
2192 !CmpInst::isTrueWhenEqual(Pred));
2193 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002194
2195 // Even if an non-inbounds GEP occurs along the path we can still optimize
2196 // equality comparisons concerning the result. We avoid walking the whole
2197 // chain again by starting where the last calls to
2198 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002199 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2200 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002201 if (LHS == RHS)
2202 return ConstantExpr::getICmp(Pred,
2203 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2204 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002205
2206 // If one side of the equality comparison must come from a noalias call
2207 // (meaning a system memory allocation function), and the other side must
2208 // come from a pointer that cannot overlap with dynamically-allocated
2209 // memory within the lifetime of the current function (allocas, byval
2210 // arguments, globals), then determine the comparison result here.
2211 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2212 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2213 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2214
2215 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002216 auto IsNAC = [](ArrayRef<Value *> Objects) {
2217 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002218 };
2219
2220 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002221 // noalias calls. For allocas, we consider only static ones (dynamic
2222 // allocas might be transformed into calls to malloc not simultaneously
2223 // live with the compared-to allocation). For globals, we exclude symbols
2224 // that might be resolve lazily to symbols in another dynamically-loaded
2225 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002226 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2227 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002228 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2229 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2230 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2231 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002232 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002233 !GV->isThreadLocal();
2234 if (const Argument *A = dyn_cast<Argument>(V))
2235 return A->hasByValAttr();
2236 return false;
2237 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002238 };
2239
2240 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2241 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2242 return ConstantInt::get(GetCompareTy(LHS),
2243 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002244
2245 // Fold comparisons for non-escaping pointer even if the allocation call
2246 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2247 // dynamic allocation call could be either of the operands.
2248 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002249 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002250 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002251 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002252 MI = RHS;
2253 // FIXME: We should also fold the compare when the pointer escapes, but the
2254 // compare dominates the pointer escape
2255 if (MI && !PointerMayBeCaptured(MI, true, true))
2256 return ConstantInt::get(GetCompareTy(LHS),
2257 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002258 }
2259
2260 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002261 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002262}
Chris Lattner01990f02012-02-24 19:01:58 +00002263
Sanjay Pateldc65a272016-12-03 17:30:22 +00002264/// Fold an icmp when its operands have i1 scalar type.
2265static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2266 Value *RHS, const Query &Q) {
2267 Type *ITy = GetCompareTy(LHS); // The return type.
2268 Type *OpTy = LHS->getType(); // The operand type.
2269 if (!OpTy->getScalarType()->isIntegerTy(1))
2270 return nullptr;
2271
2272 switch (Pred) {
2273 default:
2274 break;
2275 case ICmpInst::ICMP_EQ:
2276 // X == 1 -> X
2277 if (match(RHS, m_One()))
2278 return LHS;
2279 break;
2280 case ICmpInst::ICMP_NE:
2281 // X != 0 -> X
2282 if (match(RHS, m_Zero()))
2283 return LHS;
2284 break;
2285 case ICmpInst::ICMP_UGT:
2286 // X >u 0 -> X
2287 if (match(RHS, m_Zero()))
2288 return LHS;
2289 break;
2290 case ICmpInst::ICMP_UGE:
2291 // X >=u 1 -> X
2292 if (match(RHS, m_One()))
2293 return LHS;
2294 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2295 return getTrue(ITy);
2296 break;
2297 case ICmpInst::ICMP_SGE:
2298 /// For signed comparison, the values for an i1 are 0 and -1
2299 /// respectively. This maps into a truth table of:
2300 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2301 /// 0 | 0 | 1 (0 >= 0) | 1
2302 /// 0 | 1 | 1 (0 >= -1) | 1
2303 /// 1 | 0 | 0 (-1 >= 0) | 0
2304 /// 1 | 1 | 1 (-1 >= -1) | 1
2305 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2306 return getTrue(ITy);
2307 break;
2308 case ICmpInst::ICMP_SLT:
2309 // X <s 0 -> X
2310 if (match(RHS, m_Zero()))
2311 return LHS;
2312 break;
2313 case ICmpInst::ICMP_SLE:
2314 // X <=s -1 -> X
2315 if (match(RHS, m_One()))
2316 return LHS;
2317 break;
2318 case ICmpInst::ICMP_ULE:
2319 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2320 return getTrue(ITy);
2321 break;
2322 }
2323
2324 return nullptr;
2325}
2326
2327/// Try hard to fold icmp with zero RHS because this is a common case.
2328static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2329 Value *RHS, const Query &Q) {
2330 if (!match(RHS, m_Zero()))
2331 return nullptr;
2332
2333 Type *ITy = GetCompareTy(LHS); // The return type.
2334 bool LHSKnownNonNegative, LHSKnownNegative;
2335 switch (Pred) {
2336 default:
2337 llvm_unreachable("Unknown ICmp predicate!");
2338 case ICmpInst::ICMP_ULT:
2339 return getFalse(ITy);
2340 case ICmpInst::ICMP_UGE:
2341 return getTrue(ITy);
2342 case ICmpInst::ICMP_EQ:
2343 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002344 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002345 return getFalse(ITy);
2346 break;
2347 case ICmpInst::ICMP_NE:
2348 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002349 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002350 return getTrue(ITy);
2351 break;
2352 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002353 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2354 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002355 if (LHSKnownNegative)
2356 return getTrue(ITy);
2357 if (LHSKnownNonNegative)
2358 return getFalse(ITy);
2359 break;
2360 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002361 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2362 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002363 if (LHSKnownNegative)
2364 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002365 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002366 return getFalse(ITy);
2367 break;
2368 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002369 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2370 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002371 if (LHSKnownNegative)
2372 return getFalse(ITy);
2373 if (LHSKnownNonNegative)
2374 return getTrue(ITy);
2375 break;
2376 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002377 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2378 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002379 if (LHSKnownNegative)
2380 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002381 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002382 return getTrue(ITy);
2383 break;
2384 }
2385
2386 return nullptr;
2387}
2388
Sanjay Patelbe332132017-01-23 18:22:26 +00002389/// Many binary operators with a constant operand have an easy-to-compute
2390/// range of outputs. This can be used to fold a comparison to always true or
2391/// always false.
2392static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2393 unsigned Width = Lower.getBitWidth();
2394 const APInt *C;
2395 switch (BO.getOpcode()) {
2396 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002397 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2398 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2399 if (BO.hasNoUnsignedWrap()) {
2400 // 'add nuw x, C' produces [C, UINT_MAX].
2401 Lower = *C;
2402 } else if (BO.hasNoSignedWrap()) {
2403 if (C->isNegative()) {
2404 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2405 Lower = APInt::getSignedMinValue(Width);
2406 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2407 } else {
2408 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2409 Lower = APInt::getSignedMinValue(Width) + *C;
2410 Upper = APInt::getSignedMaxValue(Width) + 1;
2411 }
2412 }
2413 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002414 break;
2415
2416 case Instruction::And:
2417 if (match(BO.getOperand(1), m_APInt(C)))
2418 // 'and x, C' produces [0, C].
2419 Upper = *C + 1;
2420 break;
2421
2422 case Instruction::Or:
2423 if (match(BO.getOperand(1), m_APInt(C)))
2424 // 'or x, C' produces [C, UINT_MAX].
2425 Lower = *C;
2426 break;
2427
2428 case Instruction::AShr:
2429 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2430 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2431 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2432 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2433 } else if (match(BO.getOperand(0), m_APInt(C))) {
2434 unsigned ShiftAmount = Width - 1;
2435 if (*C != 0 && BO.isExact())
2436 ShiftAmount = C->countTrailingZeros();
2437 if (C->isNegative()) {
2438 // 'ashr C, x' produces [C, C >> (Width-1)]
2439 Lower = *C;
2440 Upper = C->ashr(ShiftAmount) + 1;
2441 } else {
2442 // 'ashr C, x' produces [C >> (Width-1), C]
2443 Lower = C->ashr(ShiftAmount);
2444 Upper = *C + 1;
2445 }
2446 }
2447 break;
2448
2449 case Instruction::LShr:
2450 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2451 // 'lshr x, C' produces [0, UINT_MAX >> C].
2452 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2453 } else if (match(BO.getOperand(0), m_APInt(C))) {
2454 // 'lshr C, x' produces [C >> (Width-1), C].
2455 unsigned ShiftAmount = Width - 1;
2456 if (*C != 0 && BO.isExact())
2457 ShiftAmount = C->countTrailingZeros();
2458 Lower = C->lshr(ShiftAmount);
2459 Upper = *C + 1;
2460 }
2461 break;
2462
2463 case Instruction::Shl:
2464 if (match(BO.getOperand(0), m_APInt(C))) {
2465 if (BO.hasNoUnsignedWrap()) {
2466 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2467 Lower = *C;
2468 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2469 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2470 if (C->isNegative()) {
2471 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2472 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2473 Lower = C->shl(ShiftAmount);
2474 Upper = *C + 1;
2475 } else {
2476 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2477 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2478 Lower = *C;
2479 Upper = C->shl(ShiftAmount) + 1;
2480 }
2481 }
2482 }
2483 break;
2484
2485 case Instruction::SDiv:
2486 if (match(BO.getOperand(1), m_APInt(C))) {
2487 APInt IntMin = APInt::getSignedMinValue(Width);
2488 APInt IntMax = APInt::getSignedMaxValue(Width);
2489 if (C->isAllOnesValue()) {
2490 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2491 // where C != -1 and C != 0 and C != 1
2492 Lower = IntMin + 1;
2493 Upper = IntMax + 1;
2494 } else if (C->countLeadingZeros() < Width - 1) {
2495 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2496 // where C != -1 and C != 0 and C != 1
2497 Lower = IntMin.sdiv(*C);
2498 Upper = IntMax.sdiv(*C);
2499 if (Lower.sgt(Upper))
2500 std::swap(Lower, Upper);
2501 Upper = Upper + 1;
2502 assert(Upper != Lower && "Upper part of range has wrapped!");
2503 }
2504 } else if (match(BO.getOperand(0), m_APInt(C))) {
2505 if (C->isMinSignedValue()) {
2506 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2507 Lower = *C;
2508 Upper = Lower.lshr(1) + 1;
2509 } else {
2510 // 'sdiv C, x' produces [-|C|, |C|].
2511 Upper = C->abs() + 1;
2512 Lower = (-Upper) + 1;
2513 }
2514 }
2515 break;
2516
2517 case Instruction::UDiv:
2518 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2519 // 'udiv x, C' produces [0, UINT_MAX / C].
2520 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2521 } else if (match(BO.getOperand(0), m_APInt(C))) {
2522 // 'udiv C, x' produces [0, C].
2523 Upper = *C + 1;
2524 }
2525 break;
2526
2527 case Instruction::SRem:
2528 if (match(BO.getOperand(1), m_APInt(C))) {
2529 // 'srem x, C' produces (-|C|, |C|).
2530 Upper = C->abs();
2531 Lower = (-Upper) + 1;
2532 }
2533 break;
2534
2535 case Instruction::URem:
2536 if (match(BO.getOperand(1), m_APInt(C)))
2537 // 'urem x, C' produces [0, C).
2538 Upper = *C;
2539 break;
2540
2541 default:
2542 break;
2543 }
2544}
2545
Sanjay Patel67bde282016-08-22 23:12:02 +00002546static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2547 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002548 const APInt *C;
2549 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002550 return nullptr;
2551
2552 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002553 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002554 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002555 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002556 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002557 return ConstantInt::getTrue(GetCompareTy(RHS));
2558
Sanjay Patelbe332132017-01-23 18:22:26 +00002559 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002560 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002561 APInt Lower = APInt(Width, 0);
2562 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002563 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2564 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002565
2566 ConstantRange LHS_CR =
2567 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2568
2569 if (auto *I = dyn_cast<Instruction>(LHS))
2570 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2571 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2572
2573 if (!LHS_CR.isFullSet()) {
2574 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002575 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002576 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002577 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002578 }
2579
2580 return nullptr;
2581}
2582
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002583static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2584 Value *RHS, const Query &Q,
2585 unsigned MaxRecurse) {
2586 Type *ITy = GetCompareTy(LHS); // The return type.
2587
2588 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2589 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2590 if (MaxRecurse && (LBO || RBO)) {
2591 // Analyze the case when either LHS or RHS is an add instruction.
2592 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2593 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2594 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2595 if (LBO && LBO->getOpcode() == Instruction::Add) {
2596 A = LBO->getOperand(0);
2597 B = LBO->getOperand(1);
2598 NoLHSWrapProblem =
2599 ICmpInst::isEquality(Pred) ||
2600 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2601 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2602 }
2603 if (RBO && RBO->getOpcode() == Instruction::Add) {
2604 C = RBO->getOperand(0);
2605 D = RBO->getOperand(1);
2606 NoRHSWrapProblem =
2607 ICmpInst::isEquality(Pred) ||
2608 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2609 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2610 }
2611
2612 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2613 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2614 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2615 Constant::getNullValue(RHS->getType()), Q,
2616 MaxRecurse - 1))
2617 return V;
2618
2619 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2620 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2621 if (Value *V =
2622 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2623 C == LHS ? D : C, Q, MaxRecurse - 1))
2624 return V;
2625
2626 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2627 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2628 NoRHSWrapProblem) {
2629 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2630 Value *Y, *Z;
2631 if (A == C) {
2632 // C + B == C + D -> B == D
2633 Y = B;
2634 Z = D;
2635 } else if (A == D) {
2636 // D + B == C + D -> B == C
2637 Y = B;
2638 Z = C;
2639 } else if (B == C) {
2640 // A + C == C + D -> A == D
2641 Y = A;
2642 Z = D;
2643 } else {
2644 assert(B == D);
2645 // A + D == C + D -> A == C
2646 Y = A;
2647 Z = C;
2648 }
2649 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2650 return V;
2651 }
2652 }
2653
2654 {
2655 Value *Y = nullptr;
2656 // icmp pred (or X, Y), X
2657 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2658 if (Pred == ICmpInst::ICMP_ULT)
2659 return getFalse(ITy);
2660 if (Pred == ICmpInst::ICMP_UGE)
2661 return getTrue(ITy);
2662
2663 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2664 bool RHSKnownNonNegative, RHSKnownNegative;
2665 bool YKnownNonNegative, YKnownNegative;
2666 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002667 Q.AC, Q.CxtI, Q.DT);
2668 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002669 Q.CxtI, Q.DT);
2670 if (RHSKnownNonNegative && YKnownNegative)
2671 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2672 if (RHSKnownNegative || YKnownNonNegative)
2673 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2674 }
2675 }
2676 // icmp pred X, (or X, Y)
2677 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2678 if (Pred == ICmpInst::ICMP_ULE)
2679 return getTrue(ITy);
2680 if (Pred == ICmpInst::ICMP_UGT)
2681 return getFalse(ITy);
2682
2683 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2684 bool LHSKnownNonNegative, LHSKnownNegative;
2685 bool YKnownNonNegative, YKnownNegative;
2686 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002687 Q.AC, Q.CxtI, Q.DT);
2688 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002689 Q.CxtI, Q.DT);
2690 if (LHSKnownNonNegative && YKnownNegative)
2691 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2692 if (LHSKnownNegative || YKnownNonNegative)
2693 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2694 }
2695 }
2696 }
2697
2698 // icmp pred (and X, Y), X
2699 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2700 m_And(m_Specific(RHS), m_Value())))) {
2701 if (Pred == ICmpInst::ICMP_UGT)
2702 return getFalse(ITy);
2703 if (Pred == ICmpInst::ICMP_ULE)
2704 return getTrue(ITy);
2705 }
2706 // icmp pred X, (and X, Y)
2707 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2708 m_And(m_Specific(LHS), m_Value())))) {
2709 if (Pred == ICmpInst::ICMP_UGE)
2710 return getTrue(ITy);
2711 if (Pred == ICmpInst::ICMP_ULT)
2712 return getFalse(ITy);
2713 }
2714
2715 // 0 - (zext X) pred C
2716 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2717 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2718 if (RHSC->getValue().isStrictlyPositive()) {
2719 if (Pred == ICmpInst::ICMP_SLT)
2720 return ConstantInt::getTrue(RHSC->getContext());
2721 if (Pred == ICmpInst::ICMP_SGE)
2722 return ConstantInt::getFalse(RHSC->getContext());
2723 if (Pred == ICmpInst::ICMP_EQ)
2724 return ConstantInt::getFalse(RHSC->getContext());
2725 if (Pred == ICmpInst::ICMP_NE)
2726 return ConstantInt::getTrue(RHSC->getContext());
2727 }
2728 if (RHSC->getValue().isNonNegative()) {
2729 if (Pred == ICmpInst::ICMP_SLE)
2730 return ConstantInt::getTrue(RHSC->getContext());
2731 if (Pred == ICmpInst::ICMP_SGT)
2732 return ConstantInt::getFalse(RHSC->getContext());
2733 }
2734 }
2735 }
2736
2737 // icmp pred (urem X, Y), Y
2738 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2739 bool KnownNonNegative, KnownNegative;
2740 switch (Pred) {
2741 default:
2742 break;
2743 case ICmpInst::ICMP_SGT:
2744 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002745 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2746 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002747 if (!KnownNonNegative)
2748 break;
2749 LLVM_FALLTHROUGH;
2750 case ICmpInst::ICMP_EQ:
2751 case ICmpInst::ICMP_UGT:
2752 case ICmpInst::ICMP_UGE:
2753 return getFalse(ITy);
2754 case ICmpInst::ICMP_SLT:
2755 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002756 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2757 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002758 if (!KnownNonNegative)
2759 break;
2760 LLVM_FALLTHROUGH;
2761 case ICmpInst::ICMP_NE:
2762 case ICmpInst::ICMP_ULT:
2763 case ICmpInst::ICMP_ULE:
2764 return getTrue(ITy);
2765 }
2766 }
2767
2768 // icmp pred X, (urem Y, X)
2769 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2770 bool KnownNonNegative, KnownNegative;
2771 switch (Pred) {
2772 default:
2773 break;
2774 case ICmpInst::ICMP_SGT:
2775 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002776 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2777 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002778 if (!KnownNonNegative)
2779 break;
2780 LLVM_FALLTHROUGH;
2781 case ICmpInst::ICMP_NE:
2782 case ICmpInst::ICMP_UGT:
2783 case ICmpInst::ICMP_UGE:
2784 return getTrue(ITy);
2785 case ICmpInst::ICMP_SLT:
2786 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002787 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2788 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002789 if (!KnownNonNegative)
2790 break;
2791 LLVM_FALLTHROUGH;
2792 case ICmpInst::ICMP_EQ:
2793 case ICmpInst::ICMP_ULT:
2794 case ICmpInst::ICMP_ULE:
2795 return getFalse(ITy);
2796 }
2797 }
2798
2799 // x >> y <=u x
2800 // x udiv y <=u x.
2801 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2802 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2803 // icmp pred (X op Y), X
2804 if (Pred == ICmpInst::ICMP_UGT)
2805 return getFalse(ITy);
2806 if (Pred == ICmpInst::ICMP_ULE)
2807 return getTrue(ITy);
2808 }
2809
2810 // x >=u x >> y
2811 // x >=u x udiv y.
2812 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2813 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2814 // icmp pred X, (X op Y)
2815 if (Pred == ICmpInst::ICMP_ULT)
2816 return getFalse(ITy);
2817 if (Pred == ICmpInst::ICMP_UGE)
2818 return getTrue(ITy);
2819 }
2820
2821 // handle:
2822 // CI2 << X == CI
2823 // CI2 << X != CI
2824 //
2825 // where CI2 is a power of 2 and CI isn't
2826 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2827 const APInt *CI2Val, *CIVal = &CI->getValue();
2828 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2829 CI2Val->isPowerOf2()) {
2830 if (!CIVal->isPowerOf2()) {
2831 // CI2 << X can equal zero in some circumstances,
2832 // this simplification is unsafe if CI is zero.
2833 //
2834 // We know it is safe if:
2835 // - The shift is nsw, we can't shift out the one bit.
2836 // - The shift is nuw, we can't shift out the one bit.
2837 // - CI2 is one
2838 // - CI isn't zero
2839 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2840 *CI2Val == 1 || !CI->isZero()) {
2841 if (Pred == ICmpInst::ICMP_EQ)
2842 return ConstantInt::getFalse(RHS->getContext());
2843 if (Pred == ICmpInst::ICMP_NE)
2844 return ConstantInt::getTrue(RHS->getContext());
2845 }
2846 }
Craig Topperbcfd2d12017-04-20 16:56:25 +00002847 if (CIVal->isSignMask() && *CI2Val == 1) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002848 if (Pred == ICmpInst::ICMP_UGT)
2849 return ConstantInt::getFalse(RHS->getContext());
2850 if (Pred == ICmpInst::ICMP_ULE)
2851 return ConstantInt::getTrue(RHS->getContext());
2852 }
2853 }
2854 }
2855
2856 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2857 LBO->getOperand(1) == RBO->getOperand(1)) {
2858 switch (LBO->getOpcode()) {
2859 default:
2860 break;
2861 case Instruction::UDiv:
2862 case Instruction::LShr:
2863 if (ICmpInst::isSigned(Pred))
2864 break;
2865 LLVM_FALLTHROUGH;
2866 case Instruction::SDiv:
2867 case Instruction::AShr:
2868 if (!LBO->isExact() || !RBO->isExact())
2869 break;
2870 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2871 RBO->getOperand(0), Q, MaxRecurse - 1))
2872 return V;
2873 break;
2874 case Instruction::Shl: {
2875 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2876 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2877 if (!NUW && !NSW)
2878 break;
2879 if (!NSW && ICmpInst::isSigned(Pred))
2880 break;
2881 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2882 RBO->getOperand(0), Q, MaxRecurse - 1))
2883 return V;
2884 break;
2885 }
2886 }
2887 }
2888 return nullptr;
2889}
2890
Sanjay Patel35289c62016-12-10 17:40:47 +00002891/// Simplify integer comparisons where at least one operand of the compare
2892/// matches an integer min/max idiom.
2893static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2894 Value *RHS, const Query &Q,
2895 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002896 Type *ITy = GetCompareTy(LHS); // The return type.
2897 Value *A, *B;
2898 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2899 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2900
2901 // Signed variants on "max(a,b)>=a -> true".
2902 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2903 if (A != RHS)
2904 std::swap(A, B); // smax(A, B) pred A.
2905 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2906 // We analyze this as smax(A, B) pred A.
2907 P = Pred;
2908 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2909 (A == LHS || B == LHS)) {
2910 if (A != LHS)
2911 std::swap(A, B); // A pred smax(A, B).
2912 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2913 // We analyze this as smax(A, B) swapped-pred A.
2914 P = CmpInst::getSwappedPredicate(Pred);
2915 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2916 (A == RHS || B == RHS)) {
2917 if (A != RHS)
2918 std::swap(A, B); // smin(A, B) pred A.
2919 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2920 // We analyze this as smax(-A, -B) swapped-pred -A.
2921 // Note that we do not need to actually form -A or -B thanks to EqP.
2922 P = CmpInst::getSwappedPredicate(Pred);
2923 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2924 (A == LHS || B == LHS)) {
2925 if (A != LHS)
2926 std::swap(A, B); // A pred smin(A, B).
2927 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2928 // We analyze this as smax(-A, -B) pred -A.
2929 // Note that we do not need to actually form -A or -B thanks to EqP.
2930 P = Pred;
2931 }
2932 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2933 // Cases correspond to "max(A, B) p A".
2934 switch (P) {
2935 default:
2936 break;
2937 case CmpInst::ICMP_EQ:
2938 case CmpInst::ICMP_SLE:
2939 // Equivalent to "A EqP B". This may be the same as the condition tested
2940 // in the max/min; if so, we can just return that.
2941 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2942 return V;
2943 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2944 return V;
2945 // Otherwise, see if "A EqP B" simplifies.
2946 if (MaxRecurse)
2947 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2948 return V;
2949 break;
2950 case CmpInst::ICMP_NE:
2951 case CmpInst::ICMP_SGT: {
2952 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2953 // Equivalent to "A InvEqP B". This may be the same as the condition
2954 // tested in the max/min; if so, we can just return that.
2955 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2956 return V;
2957 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2958 return V;
2959 // Otherwise, see if "A InvEqP B" simplifies.
2960 if (MaxRecurse)
2961 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2962 return V;
2963 break;
2964 }
2965 case CmpInst::ICMP_SGE:
2966 // Always true.
2967 return getTrue(ITy);
2968 case CmpInst::ICMP_SLT:
2969 // Always false.
2970 return getFalse(ITy);
2971 }
2972 }
2973
2974 // Unsigned variants on "max(a,b)>=a -> true".
2975 P = CmpInst::BAD_ICMP_PREDICATE;
2976 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2977 if (A != RHS)
2978 std::swap(A, B); // umax(A, B) pred A.
2979 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2980 // We analyze this as umax(A, B) pred A.
2981 P = Pred;
2982 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2983 (A == LHS || B == LHS)) {
2984 if (A != LHS)
2985 std::swap(A, B); // A pred umax(A, B).
2986 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2987 // We analyze this as umax(A, B) swapped-pred A.
2988 P = CmpInst::getSwappedPredicate(Pred);
2989 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2990 (A == RHS || B == RHS)) {
2991 if (A != RHS)
2992 std::swap(A, B); // umin(A, B) pred A.
2993 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2994 // We analyze this as umax(-A, -B) swapped-pred -A.
2995 // Note that we do not need to actually form -A or -B thanks to EqP.
2996 P = CmpInst::getSwappedPredicate(Pred);
2997 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2998 (A == LHS || B == LHS)) {
2999 if (A != LHS)
3000 std::swap(A, B); // A pred umin(A, B).
3001 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3002 // We analyze this as umax(-A, -B) pred -A.
3003 // Note that we do not need to actually form -A or -B thanks to EqP.
3004 P = Pred;
3005 }
3006 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3007 // Cases correspond to "max(A, B) p A".
3008 switch (P) {
3009 default:
3010 break;
3011 case CmpInst::ICMP_EQ:
3012 case CmpInst::ICMP_ULE:
3013 // Equivalent to "A EqP B". This may be the same as the condition tested
3014 // in the max/min; if so, we can just return that.
3015 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3016 return V;
3017 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3018 return V;
3019 // Otherwise, see if "A EqP B" simplifies.
3020 if (MaxRecurse)
3021 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3022 return V;
3023 break;
3024 case CmpInst::ICMP_NE:
3025 case CmpInst::ICMP_UGT: {
3026 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3027 // Equivalent to "A InvEqP B". This may be the same as the condition
3028 // tested in the max/min; if so, we can just return that.
3029 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3030 return V;
3031 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3032 return V;
3033 // Otherwise, see if "A InvEqP B" simplifies.
3034 if (MaxRecurse)
3035 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3036 return V;
3037 break;
3038 }
3039 case CmpInst::ICMP_UGE:
3040 // Always true.
3041 return getTrue(ITy);
3042 case CmpInst::ICMP_ULT:
3043 // Always false.
3044 return getFalse(ITy);
3045 }
3046 }
3047
3048 // Variants on "max(x,y) >= min(x,z)".
3049 Value *C, *D;
3050 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3051 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3052 (A == C || A == D || B == C || B == D)) {
3053 // max(x, ?) pred min(x, ?).
3054 if (Pred == CmpInst::ICMP_SGE)
3055 // Always true.
3056 return getTrue(ITy);
3057 if (Pred == CmpInst::ICMP_SLT)
3058 // Always false.
3059 return getFalse(ITy);
3060 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3061 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3062 (A == C || A == D || B == C || B == D)) {
3063 // min(x, ?) pred max(x, ?).
3064 if (Pred == CmpInst::ICMP_SLE)
3065 // Always true.
3066 return getTrue(ITy);
3067 if (Pred == CmpInst::ICMP_SGT)
3068 // Always false.
3069 return getFalse(ITy);
3070 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3071 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3072 (A == C || A == D || B == C || B == D)) {
3073 // max(x, ?) pred min(x, ?).
3074 if (Pred == CmpInst::ICMP_UGE)
3075 // Always true.
3076 return getTrue(ITy);
3077 if (Pred == CmpInst::ICMP_ULT)
3078 // Always false.
3079 return getFalse(ITy);
3080 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3081 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3082 (A == C || A == D || B == C || B == D)) {
3083 // min(x, ?) pred max(x, ?).
3084 if (Pred == CmpInst::ICMP_ULE)
3085 // Always true.
3086 return getTrue(ITy);
3087 if (Pred == CmpInst::ICMP_UGT)
3088 // Always false.
3089 return getFalse(ITy);
3090 }
3091
3092 return nullptr;
3093}
3094
Sanjay Patel472cc782016-01-11 22:14:42 +00003095/// Given operands for an ICmpInst, see if we can fold the result.
3096/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003097static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003098 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003099 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003100 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003101
Chris Lattnera71e9d62009-11-10 00:55:12 +00003102 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003103 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003104 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003105
3106 // If we have a constant, make sure it is on the RHS.
3107 std::swap(LHS, RHS);
3108 Pred = CmpInst::getSwappedPredicate(Pred);
3109 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003110
Chris Lattner229907c2011-07-18 04:54:35 +00003111 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003112
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003113 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003114 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3115 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003116 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003117 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003118
Sanjay Pateldc65a272016-12-03 17:30:22 +00003119 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3120 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003121
Sanjay Pateldc65a272016-12-03 17:30:22 +00003122 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3123 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003124
Sanjay Patel67bde282016-08-22 23:12:02 +00003125 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3126 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003127
Chen Li7452d952015-09-26 03:26:47 +00003128 // If both operands have range metadata, use the metadata
3129 // to simplify the comparison.
3130 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
Craig Topper0c198612017-04-10 19:37:10 +00003131 auto RHS_Instr = cast<Instruction>(RHS);
3132 auto LHS_Instr = cast<Instruction>(LHS);
Chen Li7452d952015-09-26 03:26:47 +00003133
3134 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3135 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003136 auto RHS_CR = getConstantRangeFromMetadata(
3137 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3138 auto LHS_CR = getConstantRangeFromMetadata(
3139 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003140
3141 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3142 if (Satisfied_CR.contains(LHS_CR))
3143 return ConstantInt::getTrue(RHS->getContext());
3144
3145 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3146 CmpInst::getInversePredicate(Pred), RHS_CR);
3147 if (InversedSatisfied_CR.contains(LHS_CR))
3148 return ConstantInt::getFalse(RHS->getContext());
3149 }
3150 }
3151
Duncan Sands8fb2c382011-01-20 13:21:55 +00003152 // Compare of cast, for example (zext X) != 0 -> X != 0
3153 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3154 Instruction *LI = cast<CastInst>(LHS);
3155 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003156 Type *SrcTy = SrcOp->getType();
3157 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003158
3159 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3160 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003161 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3162 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003163 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3164 // Transfer the cast to the constant.
3165 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3166 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003167 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003168 return V;
3169 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3170 if (RI->getOperand(0)->getType() == SrcTy)
3171 // Compare without the cast.
3172 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003173 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003174 return V;
3175 }
3176 }
3177
3178 if (isa<ZExtInst>(LHS)) {
3179 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3180 // same type.
3181 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3182 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3183 // Compare X and Y. Note that signed predicates become unsigned.
3184 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003185 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003186 MaxRecurse-1))
3187 return V;
3188 }
3189 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3190 // too. If not, then try to deduce the result of the comparison.
3191 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3192 // Compute the constant that would happen if we truncated to SrcTy then
3193 // reextended to DstTy.
3194 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3195 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3196
3197 // If the re-extended constant didn't change then this is effectively
3198 // also a case of comparing two zero-extended values.
3199 if (RExt == CI && MaxRecurse)
3200 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003201 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003202 return V;
3203
3204 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3205 // there. Use this to work out the result of the comparison.
3206 if (RExt != CI) {
3207 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003208 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003209 // LHS <u RHS.
3210 case ICmpInst::ICMP_EQ:
3211 case ICmpInst::ICMP_UGT:
3212 case ICmpInst::ICMP_UGE:
3213 return ConstantInt::getFalse(CI->getContext());
3214
3215 case ICmpInst::ICMP_NE:
3216 case ICmpInst::ICMP_ULT:
3217 case ICmpInst::ICMP_ULE:
3218 return ConstantInt::getTrue(CI->getContext());
3219
3220 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3221 // is non-negative then LHS <s RHS.
3222 case ICmpInst::ICMP_SGT:
3223 case ICmpInst::ICMP_SGE:
3224 return CI->getValue().isNegative() ?
3225 ConstantInt::getTrue(CI->getContext()) :
3226 ConstantInt::getFalse(CI->getContext());
3227
3228 case ICmpInst::ICMP_SLT:
3229 case ICmpInst::ICMP_SLE:
3230 return CI->getValue().isNegative() ?
3231 ConstantInt::getFalse(CI->getContext()) :
3232 ConstantInt::getTrue(CI->getContext());
3233 }
3234 }
3235 }
3236 }
3237
3238 if (isa<SExtInst>(LHS)) {
3239 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3240 // same type.
3241 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3242 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3243 // Compare X and Y. Note that the predicate does not change.
3244 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003245 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003246 return V;
3247 }
3248 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3249 // too. If not, then try to deduce the result of the comparison.
3250 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3251 // Compute the constant that would happen if we truncated to SrcTy then
3252 // reextended to DstTy.
3253 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3254 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3255
3256 // If the re-extended constant didn't change then this is effectively
3257 // also a case of comparing two sign-extended values.
3258 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003259 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003260 return V;
3261
3262 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3263 // bits there. Use this to work out the result of the comparison.
3264 if (RExt != CI) {
3265 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003266 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003267 case ICmpInst::ICMP_EQ:
3268 return ConstantInt::getFalse(CI->getContext());
3269 case ICmpInst::ICMP_NE:
3270 return ConstantInt::getTrue(CI->getContext());
3271
3272 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3273 // LHS >s RHS.
3274 case ICmpInst::ICMP_SGT:
3275 case ICmpInst::ICMP_SGE:
3276 return CI->getValue().isNegative() ?
3277 ConstantInt::getTrue(CI->getContext()) :
3278 ConstantInt::getFalse(CI->getContext());
3279 case ICmpInst::ICMP_SLT:
3280 case ICmpInst::ICMP_SLE:
3281 return CI->getValue().isNegative() ?
3282 ConstantInt::getFalse(CI->getContext()) :
3283 ConstantInt::getTrue(CI->getContext());
3284
3285 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3286 // LHS >u RHS.
3287 case ICmpInst::ICMP_UGT:
3288 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003289 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003290 if (MaxRecurse)
3291 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3292 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003293 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003294 return V;
3295 break;
3296 case ICmpInst::ICMP_ULT:
3297 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003298 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003299 if (MaxRecurse)
3300 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3301 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003302 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003303 return V;
3304 break;
3305 }
3306 }
3307 }
3308 }
3309 }
3310
James Molloy1d88d6f2015-10-22 13:18:42 +00003311 // icmp eq|ne X, Y -> false|true if X != Y
3312 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003313 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003314 LLVMContext &Ctx = LHS->getType()->getContext();
3315 return Pred == ICmpInst::ICMP_NE ?
3316 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3317 }
Junmo Park53470fc2016-04-05 21:14:31 +00003318
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003319 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3320 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003321
Sanjay Patel35289c62016-12-10 17:40:47 +00003322 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003323 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003324
Chandler Carruth8059c842012-03-25 21:28:14 +00003325 // Simplify comparisons of related pointers using a powerful, recursive
3326 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003327 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003328 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003329 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003330 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3331 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3332 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3333 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3334 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3335 Q.DL.getTypeSizeInBits(CRHS->getType()))
3336 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3337 CLHS->getPointerOperand(),
3338 CRHS->getPointerOperand()))
3339 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003340
Nick Lewycky3db143e2012-02-26 02:09:49 +00003341 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3342 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3343 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3344 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3345 (ICmpInst::isEquality(Pred) ||
3346 (GLHS->isInBounds() && GRHS->isInBounds() &&
3347 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3348 // The bases are equal and the indices are constant. Build a constant
3349 // expression GEP with the same indices and a null base pointer to see
3350 // what constant folding can make out of it.
3351 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3352 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003353 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3354 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003355
3356 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003357 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3358 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003359 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3360 }
3361 }
3362 }
3363
David Majnemer5854e9f2014-11-16 02:20:08 +00003364 // If a bit is known to be zero for A and known to be one for B,
3365 // then A and B cannot be equal.
3366 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003367 const APInt *RHSVal;
3368 if (match(RHS, m_APInt(RHSVal))) {
3369 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003370 APInt LHSKnownZero(BitWidth, 0);
3371 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003372 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003373 Q.CxtI, Q.DT);
Craig Topperf3dbd172017-04-25 17:46:30 +00003374 if (LHSKnownZero.intersects(*RHSVal) || !LHSKnownOne.isSubsetOf(*RHSVal))
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003375 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3376 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003377 }
3378 }
3379
Duncan Sandsf532d312010-11-07 16:12:23 +00003380 // If the comparison is with the result of a select instruction, check whether
3381 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003382 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003383 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003384 return V;
3385
3386 // If the comparison is with the result of a phi instruction, check whether
3387 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003388 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003389 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003390 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003391
Craig Topper9f008862014-04-15 04:59:12 +00003392 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003393}
3394
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003395Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003396 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003397 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003398 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003399 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003400 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003401 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003402}
3403
Sanjay Patel472cc782016-01-11 22:14:42 +00003404/// Given operands for an FCmpInst, see if we can fold the result.
3405/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003406static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003407 FastMathFlags FMF, const Query &Q,
3408 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003409 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3410 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3411
Chris Lattnera71e9d62009-11-10 00:55:12 +00003412 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003413 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003414 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003415
Chris Lattnera71e9d62009-11-10 00:55:12 +00003416 // If we have a constant, make sure it is on the RHS.
3417 std::swap(LHS, RHS);
3418 Pred = CmpInst::getSwappedPredicate(Pred);
3419 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003420
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003421 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003422 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003423 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003424 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003425 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003426 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003427
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003428 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3429 if (FMF.noNaNs()) {
3430 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003431 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003432 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003433 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003434 }
3435
Mehdi Aminieb242a52015-03-09 03:20:25 +00003436 // fcmp pred x, undef and fcmp pred undef, x
3437 // fold to true if unordered, false if ordered
3438 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3439 // Choosing NaN for the undef will always make unordered comparison succeed
3440 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003441 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003442 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003443
3444 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003445 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003446 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003447 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003448 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003449 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003450 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003451
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003452 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003453 const ConstantFP *CFP = nullptr;
3454 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3455 if (RHS->getType()->isVectorTy())
3456 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3457 else
3458 CFP = dyn_cast<ConstantFP>(RHSC);
3459 }
3460 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003461 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003462 if (CFP->getValueAPF().isNaN()) {
3463 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003464 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003465 assert(FCmpInst::isUnordered(Pred) &&
3466 "Comparison must be either ordered or unordered!");
3467 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003468 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003469 }
3470 // Check whether the constant is an infinity.
3471 if (CFP->getValueAPF().isInfinity()) {
3472 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003473 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003474 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003475 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003476 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003477 case FCmpInst::FCMP_UGE:
3478 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003479 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003480 default:
3481 break;
3482 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003483 } else {
3484 switch (Pred) {
3485 case FCmpInst::FCMP_OGT:
3486 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003487 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003488 case FCmpInst::FCMP_ULE:
3489 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003490 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003491 default:
3492 break;
3493 }
3494 }
3495 }
3496 if (CFP->getValueAPF().isZero()) {
3497 switch (Pred) {
3498 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003499 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003500 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003501 break;
3502 case FCmpInst::FCMP_OLT:
3503 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003504 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003505 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003506 break;
3507 default:
3508 break;
3509 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003510 }
3511 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003512
Duncan Sandsa620bd12010-11-07 16:46:25 +00003513 // If the comparison is with the result of a select instruction, check whether
3514 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003515 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003516 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003517 return V;
3518
3519 // If the comparison is with the result of a phi instruction, check whether
3520 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003521 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003522 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003523 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003524
Craig Topper9f008862014-04-15 04:59:12 +00003525 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003526}
3527
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003528Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003529 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003530 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003531 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003532 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003533 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003534 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003535}
3536
Sanjay Patel472cc782016-01-11 22:14:42 +00003537/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003538static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3539 const Query &Q,
3540 unsigned MaxRecurse) {
3541 // Trivial replacement.
3542 if (V == Op)
3543 return RepOp;
3544
3545 auto *I = dyn_cast<Instruction>(V);
3546 if (!I)
3547 return nullptr;
3548
3549 // If this is a binary operator, try to simplify it with the replaced op.
3550 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3551 // Consider:
3552 // %cmp = icmp eq i32 %x, 2147483647
3553 // %add = add nsw i32 %x, 1
3554 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3555 //
3556 // We can't replace %sel with %add unless we strip away the flags.
3557 if (isa<OverflowingBinaryOperator>(B))
3558 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3559 return nullptr;
3560 if (isa<PossiblyExactOperator>(B))
3561 if (B->isExact())
3562 return nullptr;
3563
3564 if (MaxRecurse) {
3565 if (B->getOperand(0) == Op)
3566 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3567 MaxRecurse - 1);
3568 if (B->getOperand(1) == Op)
3569 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3570 MaxRecurse - 1);
3571 }
3572 }
3573
3574 // Same for CmpInsts.
3575 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3576 if (MaxRecurse) {
3577 if (C->getOperand(0) == Op)
3578 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3579 MaxRecurse - 1);
3580 if (C->getOperand(1) == Op)
3581 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3582 MaxRecurse - 1);
3583 }
3584 }
3585
3586 // TODO: We could hand off more cases to instsimplify here.
3587
3588 // If all operands are constant after substituting Op for RepOp then we can
3589 // constant fold the instruction.
3590 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3591 // Build a list of all constant operands.
3592 SmallVector<Constant *, 8> ConstOps;
3593 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3594 if (I->getOperand(i) == Op)
3595 ConstOps.push_back(CRepOp);
3596 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3597 ConstOps.push_back(COp);
3598 else
3599 break;
3600 }
3601
3602 // All operands were constants, fold it.
3603 if (ConstOps.size() == I->getNumOperands()) {
3604 if (CmpInst *C = dyn_cast<CmpInst>(I))
3605 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3606 ConstOps[1], Q.DL, Q.TLI);
3607
3608 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3609 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003610 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003611
Manuel Jacobe9024592016-01-21 06:33:22 +00003612 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003613 }
3614 }
3615
3616 return nullptr;
3617}
3618
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003619/// Try to simplify a select instruction when its condition operand is an
3620/// integer comparison where one operand of the compare is a constant.
3621static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3622 const APInt *Y, bool TrueWhenUnset) {
3623 const APInt *C;
3624
3625 // (X & Y) == 0 ? X & ~Y : X --> X
3626 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3627 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3628 *Y == ~*C)
3629 return TrueWhenUnset ? FalseVal : TrueVal;
3630
3631 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3632 // (X & Y) != 0 ? X : X & ~Y --> X
3633 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3634 *Y == ~*C)
3635 return TrueWhenUnset ? FalseVal : TrueVal;
3636
3637 if (Y->isPowerOf2()) {
3638 // (X & Y) == 0 ? X | Y : X --> X | Y
3639 // (X & Y) != 0 ? X | Y : X --> X
3640 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3641 *Y == *C)
3642 return TrueWhenUnset ? TrueVal : FalseVal;
3643
3644 // (X & Y) == 0 ? X : X | Y --> X
3645 // (X & Y) != 0 ? X : X | Y --> X | Y
3646 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3647 *Y == *C)
3648 return TrueWhenUnset ? TrueVal : FalseVal;
3649 }
Matt Arsenault82606662017-01-11 00:57:54 +00003650
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003651 return nullptr;
3652}
3653
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003654/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3655/// eq/ne.
3656static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3657 Value *FalseVal,
3658 bool TrueWhenUnset) {
3659 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003660 if (!BitWidth)
3661 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003662
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003663 APInt MinSignedValue;
3664 Value *X;
3665 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3666 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3667 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3668 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3669 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3670 } else {
3671 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3672 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3673 X = CmpLHS;
3674 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3675 }
3676
3677 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3678 TrueWhenUnset))
3679 return V;
3680
3681 return nullptr;
3682}
3683
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003684/// Try to simplify a select instruction when its condition operand is an
3685/// integer comparison.
3686static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3687 Value *FalseVal, const Query &Q,
3688 unsigned MaxRecurse) {
3689 ICmpInst::Predicate Pred;
3690 Value *CmpLHS, *CmpRHS;
3691 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3692 return nullptr;
3693
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003694 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3695 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003696 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3697 Value *X;
3698 const APInt *Y;
3699 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3700 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3701 Pred == ICmpInst::ICMP_EQ))
3702 return V;
3703 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003704 // Comparing signed-less-than 0 checks if the sign bit is set.
3705 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3706 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003707 return V;
3708 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003709 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3710 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3711 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003712 return V;
3713 }
3714
3715 if (CondVal->hasOneUse()) {
3716 const APInt *C;
3717 if (match(CmpRHS, m_APInt(C))) {
3718 // X < MIN ? T : F --> F
3719 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3720 return FalseVal;
3721 // X < MIN ? T : F --> F
3722 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3723 return FalseVal;
3724 // X > MAX ? T : F --> F
3725 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3726 return FalseVal;
3727 // X > MAX ? T : F --> F
3728 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3729 return FalseVal;
3730 }
3731 }
3732
3733 // If we have an equality comparison, then we know the value in one of the
3734 // arms of the select. See if substituting this value into the arm and
3735 // simplifying the result yields the same value as the other arm.
3736 if (Pred == ICmpInst::ICMP_EQ) {
3737 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3738 TrueVal ||
3739 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3740 TrueVal)
3741 return FalseVal;
3742 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3743 FalseVal ||
3744 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3745 FalseVal)
3746 return FalseVal;
3747 } else if (Pred == ICmpInst::ICMP_NE) {
3748 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3749 FalseVal ||
3750 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3751 FalseVal)
3752 return TrueVal;
3753 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3754 TrueVal ||
3755 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3756 TrueVal)
3757 return TrueVal;
3758 }
3759
3760 return nullptr;
3761}
3762
Sanjay Patel472cc782016-01-11 22:14:42 +00003763/// Given operands for a SelectInst, see if we can fold the result.
3764/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003765static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3766 Value *FalseVal, const Query &Q,
3767 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003768 // select true, X, Y -> X
3769 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003770 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3771 if (CB->isAllOnesValue())
3772 return TrueVal;
3773 if (CB->isNullValue())
3774 return FalseVal;
3775 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003776
Chris Lattnerc707fa92010-04-20 05:32:14 +00003777 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003778 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003779 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003780
Chris Lattnerc707fa92010-04-20 05:32:14 +00003781 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3782 if (isa<Constant>(TrueVal))
3783 return TrueVal;
3784 return FalseVal;
3785 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003786 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3787 return FalseVal;
3788 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3789 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003790
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003791 if (Value *V =
3792 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3793 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003794
Craig Topper9f008862014-04-15 04:59:12 +00003795 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003796}
3797
Duncan Sandsb8cee002012-03-13 11:42:19 +00003798Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003799 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003800 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003801 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003802 const Instruction *CxtI) {
3803 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003804 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003805}
3806
Sanjay Patel472cc782016-01-11 22:14:42 +00003807/// Given operands for an GetElementPtrInst, see if we can fold the result.
3808/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003809static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3810 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003811 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003812 unsigned AS =
3813 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003814
Chris Lattner8574aba2009-11-27 00:29:05 +00003815 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003816 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003817 return Ops[0];
3818
Nico Weber48c82402014-08-27 20:06:19 +00003819 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003820 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003821 Type *GEPTy = PointerType::get(LastType, AS);
3822 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3823 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Davide Italianoa9f047a2017-04-19 14:23:42 +00003824 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3825 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Nico Weber48c82402014-08-27 20:06:19 +00003826
3827 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003828 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003829
Jay Foadb992a632011-07-19 15:07:52 +00003830 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003831 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003832 if (match(Ops[1], m_Zero()))
3833 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003834
David Blaikie4a2e73b2015-04-02 18:55:32 +00003835 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003837 Value *P;
3838 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003839 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003840 // getelementptr P, N -> P if P points to a type of zero size.
3841 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003842 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003843
3844 // The following transforms are only safe if the ptrtoint cast
3845 // doesn't truncate the pointers.
3846 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003847 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003848 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3849 if (match(P, m_Zero()))
3850 return Constant::getNullValue(GEPTy);
3851 Value *Temp;
3852 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003853 if (Temp->getType() == GEPTy)
3854 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003855 return nullptr;
3856 };
3857
3858 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3859 if (TyAllocSize == 1 &&
3860 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3861 if (Value *R = PtrToIntOrZero(P))
3862 return R;
3863
3864 // getelementptr V, (ashr (sub P, V), C) -> Q
3865 // if P points to a type of size 1 << C.
3866 if (match(Ops[1],
3867 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3868 m_ConstantInt(C))) &&
3869 TyAllocSize == 1ULL << C)
3870 if (Value *R = PtrToIntOrZero(P))
3871 return R;
3872
3873 // getelementptr V, (sdiv (sub P, V), C) -> Q
3874 // if P points to a type of size C.
3875 if (match(Ops[1],
3876 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3877 m_SpecificInt(TyAllocSize))))
3878 if (Value *R = PtrToIntOrZero(P))
3879 return R;
3880 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003881 }
3882 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003883
David Majnemerd1501372016-08-07 07:58:12 +00003884 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3885 all_of(Ops.slice(1).drop_back(1),
3886 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3887 unsigned PtrWidth =
3888 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3889 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3890 APInt BasePtrOffset(PtrWidth, 0);
3891 Value *StrippedBasePtr =
3892 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3893 BasePtrOffset);
3894
David Majnemer5c5df622016-08-16 06:13:46 +00003895 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003896 if (match(Ops.back(),
3897 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3898 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3899 return ConstantExpr::getIntToPtr(CI, GEPTy);
3900 }
David Majnemer5c5df622016-08-16 06:13:46 +00003901 // gep (gep V, C), (xor V, -1) -> C-1
3902 if (match(Ops.back(),
3903 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3904 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3905 return ConstantExpr::getIntToPtr(CI, GEPTy);
3906 }
David Majnemerd1501372016-08-07 07:58:12 +00003907 }
3908 }
3909
Chris Lattner8574aba2009-11-27 00:29:05 +00003910 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003911 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003912 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003913 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003914
David Blaikie4a2e73b2015-04-02 18:55:32 +00003915 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3916 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003917}
3918
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003919Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3920 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003921 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003922 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003923 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003924 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003925 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003926}
3927
Sanjay Patel472cc782016-01-11 22:14:42 +00003928/// Given operands for an InsertValueInst, see if we can fold the result.
3929/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003930static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3931 ArrayRef<unsigned> Idxs, const Query &Q,
3932 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003933 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3934 if (Constant *CVal = dyn_cast<Constant>(Val))
3935 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3936
3937 // insertvalue x, undef, n -> x
3938 if (match(Val, m_Undef()))
3939 return Agg;
3940
3941 // insertvalue x, (extractvalue y, n), n
3942 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003943 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3944 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003945 // insertvalue undef, (extractvalue y, n), n -> y
3946 if (match(Agg, m_Undef()))
3947 return EV->getAggregateOperand();
3948
3949 // insertvalue y, (extractvalue y, n), n -> y
3950 if (Agg == EV->getAggregateOperand())
3951 return Agg;
3952 }
3953
Craig Topper9f008862014-04-15 04:59:12 +00003954 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003955}
3956
Chandler Carruth66b31302015-01-04 12:03:27 +00003957Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003958 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003959 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003960 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003961 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003962 RecursionLimit);
3963}
3964
Sanjay Patel472cc782016-01-11 22:14:42 +00003965/// Given operands for an ExtractValueInst, see if we can fold the result.
3966/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003967static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3968 const Query &, unsigned) {
3969 if (auto *CAgg = dyn_cast<Constant>(Agg))
3970 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3971
3972 // extractvalue x, (insertvalue y, elt, n), n -> elt
3973 unsigned NumIdxs = Idxs.size();
3974 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3975 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3976 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3977 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3978 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3979 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3980 Idxs.slice(0, NumCommonIdxs)) {
3981 if (NumIdxs == NumInsertValueIdxs)
3982 return IVI->getInsertedValueOperand();
3983 break;
3984 }
3985 }
3986
3987 return nullptr;
3988}
3989
3990Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3991 const DataLayout &DL,
3992 const TargetLibraryInfo *TLI,
3993 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003994 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003995 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003996 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003997 RecursionLimit);
3998}
3999
Sanjay Patel472cc782016-01-11 22:14:42 +00004000/// Given operands for an ExtractElementInst, see if we can fold the result.
4001/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00004002static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
4003 unsigned) {
4004 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4005 if (auto *CIdx = dyn_cast<Constant>(Idx))
4006 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4007
4008 // The index is not relevant if our vector is a splat.
4009 if (auto *Splat = CVec->getSplatValue())
4010 return Splat;
4011
4012 if (isa<UndefValue>(Vec))
4013 return UndefValue::get(Vec->getType()->getVectorElementType());
4014 }
4015
4016 // If extracting a specified index from the vector, see if we can recursively
4017 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00004018 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
4019 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00004020 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00004021
4022 return nullptr;
4023}
4024
4025Value *llvm::SimplifyExtractElementInst(
4026 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004027 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4028 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004029 RecursionLimit);
4030}
4031
Sanjay Patel472cc782016-01-11 22:14:42 +00004032/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004033static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004034 // If all of the PHI's incoming values are the same then replace the PHI node
4035 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004036 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004037 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004038 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004039 // If the incoming value is the phi node itself, it can safely be skipped.
4040 if (Incoming == PN) continue;
4041 if (isa<UndefValue>(Incoming)) {
4042 // Remember that we saw an undef value, but otherwise ignore them.
4043 HasUndefInput = true;
4044 continue;
4045 }
4046 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004047 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004048 CommonValue = Incoming;
4049 }
4050
4051 // If CommonValue is null then all of the incoming values were either undef or
4052 // equal to the phi node itself.
4053 if (!CommonValue)
4054 return UndefValue::get(PN->getType());
4055
4056 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4057 // instruction, we cannot return X as the result of the PHI node unless it
4058 // dominates the PHI block.
4059 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004060 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004061
4062 return CommonValue;
4063}
4064
David Majnemer6774d612016-07-26 17:58:05 +00004065static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4066 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004067 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004068 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004069
David Majnemer6774d612016-07-26 17:58:05 +00004070 if (auto *CI = dyn_cast<CastInst>(Op)) {
4071 auto *Src = CI->getOperand(0);
4072 Type *SrcTy = Src->getType();
4073 Type *MidTy = CI->getType();
4074 Type *DstTy = Ty;
4075 if (Src->getType() == Ty) {
4076 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4077 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4078 Type *SrcIntPtrTy =
4079 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4080 Type *MidIntPtrTy =
4081 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4082 Type *DstIntPtrTy =
4083 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4084 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4085 SrcIntPtrTy, MidIntPtrTy,
4086 DstIntPtrTy) == Instruction::BitCast)
4087 return Src;
4088 }
4089 }
David Majnemera90a6212016-07-26 05:52:29 +00004090
4091 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004092 if (CastOpc == Instruction::BitCast)
4093 if (Op->getType() == Ty)
4094 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004095
4096 return nullptr;
4097}
4098
David Majnemer6774d612016-07-26 17:58:05 +00004099Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4100 const DataLayout &DL,
4101 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004102 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004103 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004104 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004105 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004106}
4107
Sanjay Patela3c297d2017-04-19 16:48:22 +00004108/// For the given destination element of a shuffle, peek through shuffles to
4109/// match a root vector source operand that contains that element in the same
4110/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4111static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4112 Constant *Mask, Value *RootVec, int RootElt,
4113 unsigned MaxRecurse) {
4114 if (!MaxRecurse--)
4115 return nullptr;
4116
4117 // Bail out if any mask value is undefined. That kind of shuffle may be
4118 // simplified further based on demanded bits or other folds.
4119 int MaskVal = ShuffleVectorInst::getMaskValue(Mask, RootElt);
4120 if (MaskVal == -1)
4121 return nullptr;
4122
4123 // The mask value chooses which source operand we need to look at next.
4124 Value *SourceOp;
4125 int InVecNumElts = Op0->getType()->getVectorNumElements();
4126 if (MaskVal < InVecNumElts) {
4127 RootElt = MaskVal;
4128 SourceOp = Op0;
4129 } else {
4130 RootElt = MaskVal - InVecNumElts;
4131 SourceOp = Op1;
4132 }
4133
4134 // If the source operand is a shuffle itself, look through it to find the
4135 // matching root vector.
4136 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4137 return foldIdentityShuffles(
4138 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4139 SourceShuf->getMask(), RootVec, RootElt, MaxRecurse);
4140 }
4141
4142 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4143 // size?
4144
4145 // The source operand is not a shuffle. Initialize the root vector value for
4146 // this shuffle if that has not been done yet.
4147 if (!RootVec)
4148 RootVec = SourceOp;
4149
4150 // Give up as soon as a source operand does not match the existing root value.
4151 if (RootVec != SourceOp)
4152 return nullptr;
4153
4154 // The element must be coming from the same lane in the source vector
4155 // (although it may have crossed lanes in intermediate shuffles).
4156 if (RootElt != DestElt)
4157 return nullptr;
4158
4159 return RootVec;
4160}
4161
Zvi Rackover8f460652017-04-03 22:05:30 +00004162static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4163 Type *RetTy, const Query &Q,
4164 unsigned MaxRecurse) {
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004165 Type *InVecTy = Op0->getType();
Zvi Rackover8f460652017-04-03 22:05:30 +00004166 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004167 unsigned InVecNumElts = InVecTy->getVectorNumElements();
Zvi Rackover8f460652017-04-03 22:05:30 +00004168
4169 auto *Op0Const = dyn_cast<Constant>(Op0);
4170 auto *Op1Const = dyn_cast<Constant>(Op1);
4171
4172 // If all operands are constant, constant fold the shuffle.
4173 if (Op0Const && Op1Const)
4174 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4175
4176 // If only one of the operands is constant, constant fold the shuffle if the
4177 // mask does not select elements from the variable operand.
4178 bool MaskSelects0 = false, MaskSelects1 = false;
4179 for (unsigned i = 0; i != MaskNumElts; ++i) {
4180 int Idx = ShuffleVectorInst::getMaskValue(Mask, i);
4181 if (Idx == -1)
4182 continue;
4183 if ((unsigned)Idx < InVecNumElts)
4184 MaskSelects0 = true;
4185 else
4186 MaskSelects1 = true;
4187 }
4188 if (!MaskSelects0 && Op1Const)
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004189 return ConstantFoldShuffleVectorInstruction(UndefValue::get(InVecTy),
Zvi Rackover8f460652017-04-03 22:05:30 +00004190 Op1Const, Mask);
4191 if (!MaskSelects1 && Op0Const)
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004192 return ConstantFoldShuffleVectorInstruction(Op0Const,
4193 UndefValue::get(InVecTy), Mask);
4194
4195 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4196 // value type is same as the input vectors' type.
4197 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4198 if (!MaskSelects1 && RetTy == InVecTy &&
4199 OpShuf->getMask()->getSplatValue())
4200 return Op0;
4201 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op1))
4202 if (!MaskSelects0 && RetTy == InVecTy &&
4203 OpShuf->getMask()->getSplatValue())
4204 return Op1;
Zvi Rackover8f460652017-04-03 22:05:30 +00004205
Sanjay Patela3c297d2017-04-19 16:48:22 +00004206 // Don't fold a shuffle with undef mask elements. This may get folded in a
4207 // better way using demanded bits or other analysis.
4208 // TODO: Should we allow this?
4209 for (unsigned i = 0; i != MaskNumElts; ++i)
4210 if (ShuffleVectorInst::getMaskValue(Mask, i) == -1)
4211 return nullptr;
4212
4213 // Check if every element of this shuffle can be mapped back to the
4214 // corresponding element of a single root vector. If so, we don't need this
4215 // shuffle. This handles simple identity shuffles as well as chains of
4216 // shuffles that may widen/narrow and/or move elements across lanes and back.
4217 Value *RootVec = nullptr;
4218 for (unsigned i = 0; i != MaskNumElts; ++i) {
4219 // Note that recursion is limited for each vector element, so if any element
4220 // exceeds the limit, this will fail to simplify.
4221 RootVec = foldIdentityShuffles(i, Op0, Op1, Mask, RootVec, i, MaxRecurse);
4222
4223 // We can't replace a widening/narrowing shuffle with one of its operands.
4224 if (!RootVec || RootVec->getType() != RetTy)
4225 return nullptr;
4226 }
4227 return RootVec;
Zvi Rackover8f460652017-04-03 22:05:30 +00004228}
4229
4230/// Given operands for a ShuffleVectorInst, fold the result or return null.
4231Value *llvm::SimplifyShuffleVectorInst(
4232 Value *Op0, Value *Op1, Constant *Mask, Type *RetTy,
4233 const DataLayout &DL, const TargetLibraryInfo *TLI, const DominatorTree *DT,
4234 AssumptionCache *AC, const Instruction *CxtI) {
4235 return ::SimplifyShuffleVectorInst(
4236 Op0, Op1, Mask, RetTy, Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4237}
4238
Chris Lattnera71e9d62009-11-10 00:55:12 +00004239//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004240
Sanjay Patel472cc782016-01-11 22:14:42 +00004241/// Given operands for a BinaryOperator, see if we can fold the result.
4242/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004243static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004244 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004245 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004246 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004247 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004248 case Instruction::FAdd:
4249 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004250 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004251 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004252 case Instruction::FSub:
4253 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004254 case Instruction::Mul:
4255 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004256 case Instruction::FMul:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004257 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4258 case Instruction::SDiv:
4259 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4260 case Instruction::UDiv:
4261 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004262 case Instruction::FDiv:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004263 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4264 case Instruction::SRem:
4265 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4266 case Instruction::URem:
4267 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004268 case Instruction::FRem:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004269 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004270 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004271 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004272 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004273 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004274 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004275 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4276 case Instruction::And:
4277 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4278 case Instruction::Or:
4279 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4280 case Instruction::Xor:
4281 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004282 default:
Craig Topper8ef20ea2017-04-06 18:59:08 +00004283 llvm_unreachable("Unexpected opcode");
Chris Lattnera71e9d62009-11-10 00:55:12 +00004284 }
4285}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004286
Sanjay Patel472cc782016-01-11 22:14:42 +00004287/// Given operands for a BinaryOperator, see if we can fold the result.
4288/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004289/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4290/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4291static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4292 const FastMathFlags &FMF, const Query &Q,
4293 unsigned MaxRecurse) {
4294 switch (Opcode) {
4295 case Instruction::FAdd:
4296 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4297 case Instruction::FSub:
4298 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4299 case Instruction::FMul:
4300 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004301 case Instruction::FDiv:
4302 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004303 default:
4304 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4305 }
4306}
4307
Duncan Sands7e800d62010-11-14 11:23:23 +00004308Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004309 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004310 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004311 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004312 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004313 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004314}
4315
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004316Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004317 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004318 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004319 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004320 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004321 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004322 RecursionLimit);
4323}
4324
Sanjay Patel472cc782016-01-11 22:14:42 +00004325/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004326static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004327 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004328 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004329 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004330 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004331}
4332
4333Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004334 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004335 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004336 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004337 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004338 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004339}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004340
Michael Ilseman54857292013-02-07 19:26:05 +00004341static bool IsIdempotent(Intrinsic::ID ID) {
4342 switch (ID) {
4343 default: return false;
4344
4345 // Unary idempotent: f(f(x)) = f(x)
4346 case Intrinsic::fabs:
4347 case Intrinsic::floor:
4348 case Intrinsic::ceil:
4349 case Intrinsic::trunc:
4350 case Intrinsic::rint:
4351 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004352 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004353 return true;
4354 }
4355}
4356
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004357static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4358 const DataLayout &DL) {
4359 GlobalValue *PtrSym;
4360 APInt PtrOffset;
4361 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4362 return nullptr;
4363
4364 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4365 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4366 Type *Int32PtrTy = Int32Ty->getPointerTo();
4367 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4368
4369 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4370 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4371 return nullptr;
4372
4373 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4374 if (OffsetInt % 4 != 0)
4375 return nullptr;
4376
4377 Constant *C = ConstantExpr::getGetElementPtr(
4378 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4379 ConstantInt::get(Int64Ty, OffsetInt / 4));
4380 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4381 if (!Loaded)
4382 return nullptr;
4383
4384 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4385 if (!LoadedCE)
4386 return nullptr;
4387
4388 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4389 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4390 if (!LoadedCE)
4391 return nullptr;
4392 }
4393
4394 if (LoadedCE->getOpcode() != Instruction::Sub)
4395 return nullptr;
4396
4397 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4398 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4399 return nullptr;
4400 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4401
4402 Constant *LoadedRHS = LoadedCE->getOperand(1);
4403 GlobalValue *LoadedRHSSym;
4404 APInt LoadedRHSOffset;
4405 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4406 DL) ||
4407 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4408 return nullptr;
4409
4410 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4411}
4412
David Majnemer17a95aa2016-07-14 06:58:37 +00004413static bool maskIsAllZeroOrUndef(Value *Mask) {
4414 auto *ConstMask = dyn_cast<Constant>(Mask);
4415 if (!ConstMask)
4416 return false;
4417 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4418 return true;
4419 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4420 ++I) {
4421 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4422 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4423 continue;
4424 return false;
4425 }
4426 return true;
4427}
4428
Michael Ilseman54857292013-02-07 19:26:05 +00004429template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004430static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004431 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004432 Intrinsic::ID IID = F->getIntrinsicID();
4433 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004434
4435 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004436 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004437 // Perform idempotent optimizations
4438 if (IsIdempotent(IID)) {
4439 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4440 if (II->getIntrinsicID() == IID)
4441 return II;
4442 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004443 }
4444
4445 switch (IID) {
4446 case Intrinsic::fabs: {
4447 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4448 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004449 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004450 }
4451 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004452 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004453 }
4454 }
Michael Ilseman54857292013-02-07 19:26:05 +00004455
Matt Arsenault82606662017-01-11 00:57:54 +00004456 // Binary Ops
4457 if (NumOperands == 2) {
4458 Value *LHS = *ArgBegin;
4459 Value *RHS = *(ArgBegin + 1);
4460 Type *ReturnType = F->getReturnType();
4461
4462 switch (IID) {
4463 case Intrinsic::usub_with_overflow:
4464 case Intrinsic::ssub_with_overflow: {
4465 // X - X -> { 0, false }
4466 if (LHS == RHS)
4467 return Constant::getNullValue(ReturnType);
4468
4469 // X - undef -> undef
4470 // undef - X -> undef
4471 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4472 return UndefValue::get(ReturnType);
4473
4474 return nullptr;
4475 }
4476 case Intrinsic::uadd_with_overflow:
4477 case Intrinsic::sadd_with_overflow: {
4478 // X + undef -> undef
4479 if (isa<UndefValue>(RHS))
4480 return UndefValue::get(ReturnType);
4481
4482 return nullptr;
4483 }
4484 case Intrinsic::umul_with_overflow:
4485 case Intrinsic::smul_with_overflow: {
4486 // X * 0 -> { 0, false }
4487 if (match(RHS, m_Zero()))
4488 return Constant::getNullValue(ReturnType);
4489
4490 // X * undef -> { 0, false }
4491 if (match(RHS, m_Undef()))
4492 return Constant::getNullValue(ReturnType);
4493
4494 return nullptr;
4495 }
4496 case Intrinsic::load_relative: {
4497 Constant *C0 = dyn_cast<Constant>(LHS);
4498 Constant *C1 = dyn_cast<Constant>(RHS);
4499 if (C0 && C1)
4500 return SimplifyRelativeLoad(C0, C1, Q.DL);
4501 return nullptr;
4502 }
4503 default:
4504 return nullptr;
4505 }
4506 }
4507
4508 // Simplify calls to llvm.masked.load.*
4509 switch (IID) {
4510 case Intrinsic::masked_load: {
4511 Value *MaskArg = ArgBegin[2];
4512 Value *PassthruArg = ArgBegin[3];
4513 // If the mask is all zeros or undef, the "passthru" argument is the result.
4514 if (maskIsAllZeroOrUndef(MaskArg))
4515 return PassthruArg;
4516 return nullptr;
4517 }
4518 default:
4519 return nullptr;
4520 }
Michael Ilseman54857292013-02-07 19:26:05 +00004521}
4522
Chandler Carruth9dc35582012-12-28 11:30:55 +00004523template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004524static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004525 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004526 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004527 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4528 Ty = PTy->getElementType();
4529 FunctionType *FTy = cast<FunctionType>(Ty);
4530
Dan Gohman85977e62011-11-04 18:32:42 +00004531 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004532 // call null -> undef
4533 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004534 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004535
Chandler Carruthf6182152012-12-28 14:23:29 +00004536 Function *F = dyn_cast<Function>(V);
4537 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004538 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004539
David Majnemer15032582015-05-22 03:56:46 +00004540 if (F->isIntrinsic())
4541 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004542 return Ret;
4543
Chandler Carruthf6182152012-12-28 14:23:29 +00004544 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004545 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004546
4547 SmallVector<Constant *, 4> ConstantArgs;
4548 ConstantArgs.reserve(ArgEnd - ArgBegin);
4549 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4550 Constant *C = dyn_cast<Constant>(*I);
4551 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004552 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004553 ConstantArgs.push_back(C);
4554 }
4555
4556 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004557}
4558
Chandler Carruthf6182152012-12-28 14:23:29 +00004559Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004560 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004561 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004562 AssumptionCache *AC, const Instruction *CxtI) {
4563 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004564 RecursionLimit);
4565}
4566
Chandler Carruthf6182152012-12-28 14:23:29 +00004567Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004568 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004569 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004570 const Instruction *CxtI) {
4571 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004572 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004573}
4574
Sanjay Patel472cc782016-01-11 22:14:42 +00004575/// See if we can compute a simplified version of this instruction.
4576/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004577Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004578 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004579 const DominatorTree *DT, AssumptionCache *AC,
4580 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004581 Value *Result;
4582
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004583 switch (I->getOpcode()) {
4584 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004585 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004586 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004587 case Instruction::FAdd:
4588 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004589 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004590 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004591 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004592 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4593 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004594 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004595 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004596 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004597 case Instruction::FSub:
4598 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004599 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004600 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004601 case Instruction::Sub:
4602 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4603 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004604 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004605 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004606 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004607 case Instruction::FMul:
4608 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004609 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004610 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004611 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004612 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004613 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004614 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004615 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004616 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004617 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004618 break;
4619 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004620 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004621 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004622 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004623 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004624 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004625 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004626 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004627 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004628 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004629 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004630 break;
4631 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004632 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004633 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004634 break;
4635 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004636 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004637 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004638 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004639 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004640 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4641 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004642 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004643 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004644 break;
4645 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004646 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004647 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004648 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004649 break;
4650 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004651 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004652 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004653 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004654 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004655 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004656 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004657 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004658 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004659 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004660 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004661 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004662 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004663 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004664 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004665 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004666 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004667 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004668 Result =
4669 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004670 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004671 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004672 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004673 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4674 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004675 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004676 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004677 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004678 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004679 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004680 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004681 case Instruction::GetElementPtr: {
4682 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004683 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004684 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004685 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004686 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004687 case Instruction::InsertValue: {
4688 InsertValueInst *IV = cast<InsertValueInst>(I);
4689 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4690 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004691 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004692 break;
4693 }
David Majnemer25a796e2015-07-13 01:15:46 +00004694 case Instruction::ExtractValue: {
4695 auto *EVI = cast<ExtractValueInst>(I);
4696 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004697 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004698 break;
4699 }
David Majnemer599ca442015-07-13 01:15:53 +00004700 case Instruction::ExtractElement: {
4701 auto *EEI = cast<ExtractElementInst>(I);
4702 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004703 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004704 break;
4705 }
Zvi Rackover8f460652017-04-03 22:05:30 +00004706 case Instruction::ShuffleVector: {
4707 auto *SVI = cast<ShuffleVectorInst>(I);
4708 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4709 SVI->getMask(), SVI->getType(), DL, TLI,
4710 DT, AC, I);
4711 break;
4712 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004713 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004714 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004715 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004716 case Instruction::Call: {
4717 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004718 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004719 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004720 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004721 }
David Majnemer6774d612016-07-26 17:58:05 +00004722#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4723#include "llvm/IR/Instruction.def"
4724#undef HANDLE_CAST_INST
4725 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004726 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004727 break;
Craig Topper81c03a72017-04-12 22:54:24 +00004728 case Instruction::Alloca:
4729 // No simplifications for Alloca and it can't be constant folded.
4730 Result = nullptr;
4731 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004732 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004733
Hal Finkelf2199b22015-10-23 20:37:08 +00004734 // In general, it is possible for computeKnownBits to determine all bits in a
4735 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004736 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004737 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4738 APInt KnownZero(BitWidth, 0);
4739 APInt KnownOne(BitWidth, 0);
Sanjay Patel54656ca2017-02-06 18:26:06 +00004740 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT, ORE);
Hal Finkelf2199b22015-10-23 20:37:08 +00004741 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004742 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004743 }
4744
Duncan Sands64e41cf2010-11-17 08:35:29 +00004745 /// If called on unreachable code, the above logic may report that the
4746 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004747 /// detecting that case here, returning a safe value instead.
4748 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004749}
4750
Sanjay Patelf44bd382016-01-20 18:59:48 +00004751/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004752/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004753///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004754/// This is the common implementation of the recursive simplification routines.
4755/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4756/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4757/// instructions to process and attempt to simplify it using
4758/// InstructionSimplify.
4759///
4760/// This routine returns 'true' only when *it* simplifies something. The passed
4761/// in simplified value does not count toward this.
4762static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004763 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004764 const DominatorTree *DT,
4765 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004766 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004767 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004768 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004769
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004770 // If we have an explicit value to collapse to, do that round of the
4771 // simplification loop by hand initially.
4772 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004773 for (User *U : I->users())
4774 if (U != I)
4775 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004776
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004777 // Replace the instruction with its simplified value.
4778 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004779
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004780 // Gracefully handle edge cases where the instruction is not wired into any
4781 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004782 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4783 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004784 I->eraseFromParent();
4785 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004786 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004787 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004788
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004789 // Note that we must test the size on each iteration, the worklist can grow.
4790 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4791 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004792
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004793 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004794 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004795 if (!SimpleV)
4796 continue;
4797
4798 Simplified = true;
4799
4800 // Stash away all the uses of the old instruction so we can check them for
4801 // recursive simplifications after a RAUW. This is cheaper than checking all
4802 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004803 for (User *U : I->users())
4804 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004805
4806 // Replace the instruction with its simplified value.
4807 I->replaceAllUsesWith(SimpleV);
4808
4809 // Gracefully handle edge cases where the instruction is not wired into any
4810 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004811 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4812 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004813 I->eraseFromParent();
4814 }
4815 return Simplified;
4816}
4817
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004818bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004819 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004820 const DominatorTree *DT,
4821 AssumptionCache *AC) {
4822 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004823}
4824
4825bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004826 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004827 const DominatorTree *DT,
4828 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004829 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4830 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004831 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004832}