blob: 5245b4914de9084e41623b847a935c4e3b53971c [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"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000027#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000028#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000029#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalAlias.h"
34#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000036#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000037#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000038using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000039using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000040
Chandler Carruthf1221bd2014-04-22 02:48:03 +000041#define DEBUG_TYPE "instsimplify"
42
Chris Lattner9e4aa022011-02-09 17:15:04 +000043enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000044
Duncan Sands3547d2e2010-12-22 09:40:51 +000045STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumReassoc, "Number of reassociations");
47
Benjamin Kramercfd8d902014-09-12 08:56:53 +000048namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000049struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000051 const TargetLibraryInfo *TLI;
52 const DominatorTree *DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000053 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000054 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000055
Mehdi Aminia28d91d2015-03-10 02:37:25 +000056 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000057 const DominatorTree *dt, AssumptionCache *ac = nullptr,
58 const Instruction *cxti = nullptr)
59 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000060};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000061} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000062
63static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000065 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000066static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000068static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000069 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000070static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
71 const Query &Q, unsigned MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +000072static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
73static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000074static Value *SimplifyCastInst(unsigned, Value *, Type *,
75 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000076
Sanjay Patel472cc782016-01-11 22:14:42 +000077/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000078/// a vector with every element false, as appropriate for the type.
79static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000080 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000081 "Expected i1 type or a vector of i1!");
82 return Constant::getNullValue(Ty);
83}
84
Sanjay Patel472cc782016-01-11 22:14:42 +000085/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000086/// a vector with every element true, as appropriate for the type.
87static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000088 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000089 "Expected i1 type or a vector of i1!");
90 return Constant::getAllOnesValue(Ty);
91}
92
Duncan Sands3d5692a2011-10-30 19:56:36 +000093/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
94static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
95 Value *RHS) {
96 CmpInst *Cmp = dyn_cast<CmpInst>(V);
97 if (!Cmp)
98 return false;
99 CmpInst::Predicate CPred = Cmp->getPredicate();
100 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
101 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
102 return true;
103 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
104 CRHS == LHS;
105}
106
Sanjay Patel472cc782016-01-11 22:14:42 +0000107/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000108static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
109 Instruction *I = dyn_cast<Instruction>(V);
110 if (!I)
111 // Arguments and constants dominate all instructions.
112 return true;
113
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000114 // If we are processing instructions (and/or basic blocks) that have not been
115 // fully added to a function, the parent nodes may still be null. Simply
116 // return the conservative answer in these cases.
117 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
118 return false;
119
Duncan Sands5ffc2982010-11-16 12:16:38 +0000120 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000121 if (DT) {
122 if (!DT->isReachableFromEntry(P->getParent()))
123 return true;
124 if (!DT->isReachableFromEntry(I->getParent()))
125 return false;
126 return DT->dominates(I, P);
127 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000128
David Majnemer8a1c45d2015-12-12 05:38:55 +0000129 // Otherwise, if the instruction is in the entry block and is not an invoke,
130 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000131 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000132 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000133 return true;
134
135 return false;
136}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000137
Sanjay Patel472cc782016-01-11 22:14:42 +0000138/// Simplify "A op (B op' C)" by distributing op over op', turning it into
139/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000140/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
141/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
142/// Returns the simplified value, or null if no simplification was performed.
143static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000144 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000145 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000146 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000147 // Recursion is always used, so bail out at once if we already hit the limit.
148 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000149 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000150
151 // Check whether the expression has the form "(A op' B) op C".
152 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
153 if (Op0->getOpcode() == OpcodeToExpand) {
154 // It does! Try turning it into "(A op C) op' (B op C)".
155 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
156 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000157 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
158 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000159 // They do! Return "L op' R" if it simplifies or is already available.
160 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000161 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
162 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000163 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000164 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000165 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000166 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000167 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000168 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000169 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000170 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000171 }
172 }
173
174 // Check whether the expression has the form "A op (B op' C)".
175 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
176 if (Op1->getOpcode() == OpcodeToExpand) {
177 // It does! Try turning it into "(A op B) op' (A op C)".
178 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
179 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000180 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
181 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000182 // They do! Return "L op' R" if it simplifies or is already available.
183 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000184 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
185 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000186 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000187 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000188 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000190 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000191 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000192 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000193 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000194 }
195 }
196
Craig Topper9f008862014-04-15 04:59:12 +0000197 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000198}
199
Sanjay Patel472cc782016-01-11 22:14:42 +0000200/// Generic simplifications for associative binary operations.
201/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000202static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000203 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000204 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000205 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
206
207 // Recursion is always used, so bail out at once if we already hit the limit.
208 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000209 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000210
211 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
212 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
213
214 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
215 if (Op0 && Op0->getOpcode() == Opcode) {
216 Value *A = Op0->getOperand(0);
217 Value *B = Op0->getOperand(1);
218 Value *C = RHS;
219
220 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000221 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000222 // It does! Return "A op V" if it simplifies or is already available.
223 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000224 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000225 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000226 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000227 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000228 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000229 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000230 }
231 }
232
233 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
234 if (Op1 && Op1->getOpcode() == Opcode) {
235 Value *A = LHS;
236 Value *B = Op1->getOperand(0);
237 Value *C = Op1->getOperand(1);
238
239 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000240 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000241 // It does! Return "V op C" if it simplifies or is already available.
242 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000243 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000244 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000245 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000246 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000247 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000248 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000249 }
250 }
251
252 // The remaining transforms require commutativity as well as associativity.
253 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000254 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000255
256 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
257 if (Op0 && Op0->getOpcode() == Opcode) {
258 Value *A = Op0->getOperand(0);
259 Value *B = Op0->getOperand(1);
260 Value *C = RHS;
261
262 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000263 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000264 // It does! Return "V op B" if it simplifies or is already available.
265 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000266 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000267 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000268 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000269 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000270 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000271 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000272 }
273 }
274
275 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
276 if (Op1 && Op1->getOpcode() == Opcode) {
277 Value *A = LHS;
278 Value *B = Op1->getOperand(0);
279 Value *C = Op1->getOperand(1);
280
281 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000282 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283 // It does! Return "B op V" if it simplifies or is already available.
284 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000285 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000287 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000288 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000289 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000290 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000291 }
292 }
293
Craig Topper9f008862014-04-15 04:59:12 +0000294 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000295}
296
Sanjay Patel472cc782016-01-11 22:14:42 +0000297/// In the case of a binary operation with a select instruction as an operand,
298/// try to simplify the binop by seeing whether evaluating it on both branches
299/// of the select results in the same value. Returns the common value if so,
300/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000301static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000302 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000303 // Recursion is always used, so bail out at once if we already hit the limit.
304 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000305 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000306
Duncan Sandsb0579e92010-11-10 13:00:08 +0000307 SelectInst *SI;
308 if (isa<SelectInst>(LHS)) {
309 SI = cast<SelectInst>(LHS);
310 } else {
311 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
312 SI = cast<SelectInst>(RHS);
313 }
314
315 // Evaluate the BinOp on the true and false branches of the select.
316 Value *TV;
317 Value *FV;
318 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000319 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000321 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000322 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
323 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000324 }
325
Duncan Sandse3c53952011-01-01 16:12:09 +0000326 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000327 // If they both failed to simplify then return null.
328 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000329 return TV;
330
331 // If one branch simplified to undef, return the other one.
332 if (TV && isa<UndefValue>(TV))
333 return FV;
334 if (FV && isa<UndefValue>(FV))
335 return TV;
336
337 // If applying the operation did not change the true and false select values,
338 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000339 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000340 return SI;
341
342 // If one branch simplified and the other did not, and the simplified
343 // value is equal to the unsimplified one, return the simplified value.
344 // For example, select (cond, X, X & Z) & Z -> X & Z.
345 if ((FV && !TV) || (TV && !FV)) {
346 // Check that the simplified value has the form "X op Y" where "op" is the
347 // same as the original operation.
348 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
349 if (Simplified && Simplified->getOpcode() == Opcode) {
350 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
351 // We already know that "op" is the same as for the simplified value. See
352 // if the operands match too. If so, return the simplified value.
353 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
354 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
355 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000356 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
357 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000358 return Simplified;
359 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000360 Simplified->getOperand(1) == UnsimplifiedLHS &&
361 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000362 return Simplified;
363 }
364 }
365
Craig Topper9f008862014-04-15 04:59:12 +0000366 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000367}
368
Sanjay Patel472cc782016-01-11 22:14:42 +0000369/// In the case of a comparison with a select instruction, try to simplify the
370/// comparison by seeing whether both branches of the select result in the same
371/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000372static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000373 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000374 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000375 // Recursion is always used, so bail out at once if we already hit the limit.
376 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000377 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000378
Duncan Sandsb0579e92010-11-10 13:00:08 +0000379 // Make sure the select is on the LHS.
380 if (!isa<SelectInst>(LHS)) {
381 std::swap(LHS, RHS);
382 Pred = CmpInst::getSwappedPredicate(Pred);
383 }
384 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
385 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000386 Value *Cond = SI->getCondition();
387 Value *TV = SI->getTrueValue();
388 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000389
Duncan Sands06504022011-02-03 09:37:39 +0000390 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000391 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000392 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000393 if (TCmp == Cond) {
394 // It not only simplified, it simplified to the select condition. Replace
395 // it with 'true'.
396 TCmp = getTrue(Cond->getType());
397 } else if (!TCmp) {
398 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
399 // condition then we can replace it with 'true'. Otherwise give up.
400 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000401 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000403 }
404
Duncan Sands3d5692a2011-10-30 19:56:36 +0000405 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000406 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000407 if (FCmp == Cond) {
408 // It not only simplified, it simplified to the select condition. Replace
409 // it with 'false'.
410 FCmp = getFalse(Cond->getType());
411 } else if (!FCmp) {
412 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
413 // condition then we can replace it with 'false'. Otherwise give up.
414 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000415 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000416 FCmp = getFalse(Cond->getType());
417 }
418
419 // If both sides simplified to the same value, then use it as the result of
420 // the original comparison.
421 if (TCmp == FCmp)
422 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000423
424 // The remaining cases only make sense if the select condition has the same
425 // type as the result of the comparison, so bail out if this is not so.
426 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000427 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 // If the false value simplified to false, then the result of the compare
429 // is equal to "Cond && TCmp". This also catches the case when the false
430 // value simplified to false and the true value to true, returning "Cond".
431 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000432 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000433 return V;
434 // If the true value simplified to true, then the result of the compare
435 // is equal to "Cond || FCmp".
436 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000437 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000438 return V;
439 // Finally, if the false value simplified to true and the true value to
440 // false, then the result of the compare is equal to "!Cond".
441 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
442 if (Value *V =
443 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000444 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000445 return V;
446
Craig Topper9f008862014-04-15 04:59:12 +0000447 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000448}
449
Sanjay Patel472cc782016-01-11 22:14:42 +0000450/// In the case of a binary operation with an operand that is a PHI instruction,
451/// try to simplify the binop by seeing whether evaluating it on the incoming
452/// phi values yields the same result for every value. If so returns the common
453/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000454static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000455 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000456 // Recursion is always used, so bail out at once if we already hit the limit.
457 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000458 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000459
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000460 PHINode *PI;
461 if (isa<PHINode>(LHS)) {
462 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000463 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000464 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000465 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 } else {
467 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
468 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000469 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000470 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000471 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000472 }
473
474 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000475 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000476 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000477 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000478 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000479 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000480 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
481 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000482 // If the operation failed to simplify, or simplified to a different value
483 // to previously, then give up.
484 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000485 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000486 CommonValue = V;
487 }
488
489 return CommonValue;
490}
491
Sanjay Patel472cc782016-01-11 22:14:42 +0000492/// In the case of a comparison with a PHI instruction, try to simplify the
493/// comparison by seeing whether comparing with all of the incoming phi values
494/// yields the same result every time. If so returns the common result,
495/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000496static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000497 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000498 // Recursion is always used, so bail out at once if we already hit the limit.
499 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000500 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000501
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000502 // Make sure the phi is on the LHS.
503 if (!isa<PHINode>(LHS)) {
504 std::swap(LHS, RHS);
505 Pred = CmpInst::getSwappedPredicate(Pred);
506 }
507 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
508 PHINode *PI = cast<PHINode>(LHS);
509
Duncan Sands5ffc2982010-11-16 12:16:38 +0000510 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000511 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000512 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000513
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000514 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000515 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000516 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000517 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000518 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000519 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000520 // If the operation failed to simplify, or simplified to a different value
521 // to previously, then give up.
522 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000523 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000524 CommonValue = V;
525 }
526
527 return CommonValue;
528}
529
Sanjay Patel472cc782016-01-11 22:14:42 +0000530/// Given operands for an Add, see if we can fold the result.
531/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000532static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000533 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000534 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000535 if (Constant *CRHS = dyn_cast<Constant>(Op1))
536 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000537
Chris Lattner3d9823b2009-11-27 17:42:22 +0000538 // Canonicalize the constant to the RHS.
539 std::swap(Op0, Op1);
540 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000541
Duncan Sands0a2c41682010-12-15 14:07:39 +0000542 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000543 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000544 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000545
Duncan Sands0a2c41682010-12-15 14:07:39 +0000546 // X + 0 -> X
547 if (match(Op1, m_Zero()))
548 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000549
Duncan Sands0a2c41682010-12-15 14:07:39 +0000550 // X + (Y - X) -> Y
551 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000552 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000553 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000554 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
555 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000556 return Y;
557
558 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000559 if (match(Op0, m_Not(m_Specific(Op1))) ||
560 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000561 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000562
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000563 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000564 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000565 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000566 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000567
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000568 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000569 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000570 MaxRecurse))
571 return V;
572
Duncan Sandsb238de02010-11-19 09:20:39 +0000573 // Threading Add over selects and phi nodes is pointless, so don't bother.
574 // Threading over the select in "A + select(cond, B, C)" means evaluating
575 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
576 // only if B and C are equal. If B and C are equal then (since we assume
577 // that operands have already been simplified) "select(cond, B, C)" should
578 // have been simplified to the common value of B and C already. Analysing
579 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
580 // for threading over phi nodes.
581
Craig Topper9f008862014-04-15 04:59:12 +0000582 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000583}
584
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000585Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 const DominatorTree *DT, AssumptionCache *AC,
588 const Instruction *CxtI) {
589 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000590 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000591}
592
Chandler Carrutha0796552012-03-12 11:19:31 +0000593/// \brief Compute the base pointer and cumulative constant offsets for V.
594///
595/// This strips all constant offsets off of V, leaving it the base pointer, and
596/// accumulates the total constant offset applied in the returned constant. It
597/// returns 0 if V is not a pointer, and returns the constant '0' if there are
598/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000599///
600/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
601/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
602/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000603static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000604 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000605 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000606
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000608 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000609
610 // Even though we don't look through PHI nodes, we could be called on an
611 // instruction in an unreachable block, which may be on a cycle.
612 SmallPtrSet<Value *, 4> Visited;
613 Visited.insert(V);
614 do {
615 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000616 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000618 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 V = GEP->getPointerOperand();
620 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000621 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000623 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000624 break;
625 V = GA->getAliasee();
626 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000627 if (auto CS = CallSite(V))
628 if (Value *RV = CS.getReturnedArgOperand()) {
629 V = RV;
630 continue;
631 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000632 break;
633 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000634 assert(V->getType()->getScalarType()->isPointerTy() &&
635 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000636 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000637
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000638 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
639 if (V->getType()->isVectorTy())
640 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
641 OffsetIntPtr);
642 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000643}
644
645/// \brief Compute the constant difference between two pointer values.
646/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000647static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
648 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000649 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
650 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000651
652 // If LHS and RHS are not related via constant offsets to the same base
653 // value, there is nothing we can do here.
654 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000655 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000656
657 // Otherwise, the difference of LHS - RHS can be computed as:
658 // LHS - RHS
659 // = (LHSOffset + Base) - (RHSOffset + Base)
660 // = LHSOffset - RHSOffset
661 return ConstantExpr::getSub(LHSOffset, RHSOffset);
662}
663
Sanjay Patel472cc782016-01-11 22:14:42 +0000664/// Given operands for a Sub, see if we can fold the result.
665/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000666static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000667 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000668 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000669 if (Constant *CRHS = dyn_cast<Constant>(Op1))
670 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000671
672 // X - undef -> undef
673 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000674 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000675 return UndefValue::get(Op0->getType());
676
677 // X - 0 -> X
678 if (match(Op1, m_Zero()))
679 return Op0;
680
681 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000682 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000683 return Constant::getNullValue(Op0->getType());
684
Sanjay Patelefd88852016-10-19 21:23:45 +0000685 // Is this a negation?
686 if (match(Op0, m_Zero())) {
687 // 0 - X -> 0 if the sub is NUW.
688 if (isNUW)
689 return Op0;
690
691 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
692 APInt KnownZero(BitWidth, 0);
693 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000694 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patelefd88852016-10-19 21:23:45 +0000695 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
696 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
697 // Op1 must be 0 because negating the minimum signed value is undefined.
698 if (isNSW)
699 return Op0;
700
701 // 0 - X -> X if X is 0 or the minimum signed value.
702 return Op1;
703 }
704 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000705
Duncan Sands99589d02011-01-18 11:50:19 +0000706 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
707 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000708 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000709 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
710 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000711 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000712 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000713 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000714 // It does, we successfully reassociated!
715 ++NumReassoc;
716 return W;
717 }
718 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000719 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000720 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000721 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000722 // It does, we successfully reassociated!
723 ++NumReassoc;
724 return W;
725 }
726 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000727
Duncan Sands99589d02011-01-18 11:50:19 +0000728 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
729 // For example, X - (X + 1) -> -1
730 X = Op0;
731 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
732 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000736 // It does, we successfully reassociated!
737 ++NumReassoc;
738 return W;
739 }
740 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000741 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000742 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000743 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000744 // It does, we successfully reassociated!
745 ++NumReassoc;
746 return W;
747 }
748 }
749
750 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
751 // For example, X - (X - Y) -> Y.
752 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000753 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
754 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, 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::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000758 // It does, we successfully reassociated!
759 ++NumReassoc;
760 return W;
761 }
762
Duncan Sands395ac42d2012-03-13 14:07:05 +0000763 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
764 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
765 match(Op1, m_Trunc(m_Value(Y))))
766 if (X->getType() == Y->getType())
767 // See if "V === X - Y" simplifies.
768 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
769 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000770 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
771 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000772 // It does, return the simplified "trunc V".
773 return W;
774
775 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000776 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000777 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000778 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000779 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
780
Duncan Sands99589d02011-01-18 11:50:19 +0000781 // i1 sub -> xor.
782 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000783 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000784 return V;
785
Duncan Sands0a2c41682010-12-15 14:07:39 +0000786 // Threading Sub over selects and phi nodes is pointless, so don't bother.
787 // Threading over the select in "A - select(cond, B, C)" means evaluating
788 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
789 // only if B and C are equal. If B and C are equal then (since we assume
790 // that operands have already been simplified) "select(cond, B, C)" should
791 // have been simplified to the common value of B and C already. Analysing
792 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
793 // for threading over phi nodes.
794
Craig Topper9f008862014-04-15 04:59:12 +0000795 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000796}
797
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000798Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000800 const DominatorTree *DT, AssumptionCache *AC,
801 const Instruction *CxtI) {
802 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000803 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000804}
805
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000806/// Given operands for an FAdd, see if we can fold the result. If not, this
807/// returns null.
808static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
809 const Query &Q, unsigned MaxRecurse) {
810 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000811 if (Constant *CRHS = dyn_cast<Constant>(Op1))
812 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000813
814 // Canonicalize the constant to the RHS.
815 std::swap(Op0, Op1);
816 }
817
818 // fadd X, -0 ==> X
819 if (match(Op1, m_NegZero()))
820 return Op0;
821
822 // fadd X, 0 ==> X, when we know X is not -0
823 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000824 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000825 return Op0;
826
827 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
828 // where nnan and ninf have to occur at least once somewhere in this
829 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000830 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000831 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
832 SubOp = Op1;
833 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
834 SubOp = Op0;
835 if (SubOp) {
836 Instruction *FSub = cast<Instruction>(SubOp);
837 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
838 (FMF.noInfs() || FSub->hasNoInfs()))
839 return Constant::getNullValue(Op0->getType());
840 }
841
Craig Topper9f008862014-04-15 04:59:12 +0000842 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000843}
844
845/// Given operands for an FSub, see if we can fold the result. If not, this
846/// returns null.
847static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
848 const Query &Q, unsigned MaxRecurse) {
849 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000850 if (Constant *CRHS = dyn_cast<Constant>(Op1))
851 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852 }
853
854 // fsub X, 0 ==> X
855 if (match(Op1, m_Zero()))
856 return Op0;
857
858 // fsub X, -0 ==> X, when we know X is not -0
859 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000860 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000861 return Op0;
862
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000863 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000864 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000865 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
866 return X;
867
868 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000869 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000870 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
871 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872
Benjamin Kramer228680d2015-06-14 21:01:20 +0000873 // fsub nnan x, x ==> 0.0
874 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000875 return Constant::getNullValue(Op0->getType());
876
Craig Topper9f008862014-04-15 04:59:12 +0000877 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000878}
879
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000880/// Given the operands for an FMul, see if we can fold the result
881static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
882 FastMathFlags FMF,
883 const Query &Q,
884 unsigned MaxRecurse) {
885 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000886 if (Constant *CRHS = dyn_cast<Constant>(Op1))
887 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000888
889 // Canonicalize the constant to the RHS.
890 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000891 }
892
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000893 // fmul X, 1.0 ==> X
894 if (match(Op1, m_FPOne()))
895 return Op0;
896
897 // 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
Craig Topper9f008862014-04-15 04:59:12 +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) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000908 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000909 if (Constant *CRHS = dyn_cast<Constant>(Op1))
910 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000911
912 // Canonicalize the constant to the RHS.
913 std::swap(Op0, Op1);
914 }
915
916 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000917 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000918 return Constant::getNullValue(Op0->getType());
919
920 // X * 0 -> 0
921 if (match(Op1, m_Zero()))
922 return Op1;
923
924 // X * 1 -> X
925 if (match(Op1, m_One()))
926 return Op0;
927
Duncan Sandsb67edc62011-01-30 18:03:50 +0000928 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000929 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000930 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
931 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
932 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000933
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000934 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000935 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000936 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000937 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938
939 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000940 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
944 // Mul distributes over Add. Try some generic simplifications based on this.
945 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000946 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000947 return V;
948
949 // If the operation is with the result of a select instruction, check whether
950 // operating on either branch of the select always yields the same value.
951 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000952 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000953 MaxRecurse))
954 return V;
955
956 // If the operation is with the result of a phi instruction, check whether
957 // operating on all incoming values of the phi always yields the same value.
958 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000959 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000960 MaxRecurse))
961 return V;
962
Craig Topper9f008862014-04-15 04:59:12 +0000963 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000964}
965
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000966Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000968 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000969 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000970 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000971 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000972 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000973}
974
975Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000976 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000977 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000978 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000979 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000980 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000981 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000982}
983
Chandler Carruth66b31302015-01-04 12:03:27 +0000984Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000985 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000986 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000987 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000988 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000989 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000990 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000991}
992
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000993Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000994 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000995 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000996 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000997 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000998 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000999}
1000
Sanjay Patel472cc782016-01-11 22:14:42 +00001001/// Given operands for an SDiv or UDiv, see if we can fold the result.
1002/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001003static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001004 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001005 if (Constant *C0 = dyn_cast<Constant>(Op0))
1006 if (Constant *C1 = dyn_cast<Constant>(Op1))
1007 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001008
Duncan Sands65995fa2011-01-28 18:50:50 +00001009 bool isSigned = Opcode == Instruction::SDiv;
1010
Duncan Sands771e82a2011-01-28 16:51:11 +00001011 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001012 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001013 return Op1;
1014
David Majnemer71dc8fb2014-12-10 07:52:18 +00001015 // X / 0 -> undef, we don't need to preserve faults!
1016 if (match(Op1, m_Zero()))
1017 return UndefValue::get(Op1->getType());
1018
Duncan Sands771e82a2011-01-28 16:51:11 +00001019 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001020 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001021 return Constant::getNullValue(Op0->getType());
1022
1023 // 0 / X -> 0, we don't need to preserve faults!
1024 if (match(Op0, m_Zero()))
1025 return Op0;
1026
1027 // X / 1 -> X
1028 if (match(Op1, m_One()))
1029 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001030
1031 if (Op0->getType()->isIntegerTy(1))
1032 // It can't be division by zero, hence it must be division by one.
1033 return Op0;
1034
1035 // X / X -> 1
1036 if (Op0 == Op1)
1037 return ConstantInt::get(Op0->getType(), 1);
1038
1039 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001040 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001041 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1042 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001043 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001044 // If the Mul knows it does not overflow, then we are good to go.
1045 if ((isSigned && Mul->hasNoSignedWrap()) ||
1046 (!isSigned && Mul->hasNoUnsignedWrap()))
1047 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001048 // If X has the form X = A / Y then X * Y cannot overflow.
1049 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1050 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1051 return X;
1052 }
1053
Duncan Sands65995fa2011-01-28 18:50:50 +00001054 // (X rem Y) / Y -> 0
1055 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1056 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1057 return Constant::getNullValue(Op0->getType());
1058
David Majnemercb9d5962014-10-11 10:20:01 +00001059 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1060 ConstantInt *C1, *C2;
1061 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1062 match(Op1, m_ConstantInt(C2))) {
1063 bool Overflow;
1064 C1->getValue().umul_ov(C2->getValue(), Overflow);
1065 if (Overflow)
1066 return Constant::getNullValue(Op0->getType());
1067 }
1068
Duncan Sands65995fa2011-01-28 18:50:50 +00001069 // If the operation is with the result of a select instruction, check whether
1070 // operating on either branch of the select always yields the same value.
1071 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001072 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001073 return V;
1074
1075 // If the operation is with the result of a phi instruction, check whether
1076 // operating on all incoming values of the phi always yields the same value.
1077 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001078 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001079 return V;
1080
Craig Topper9f008862014-04-15 04:59:12 +00001081 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001082}
1083
Sanjay Patel472cc782016-01-11 22:14:42 +00001084/// Given operands for an SDiv, see if we can fold the result.
1085/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001086static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1087 unsigned MaxRecurse) {
1088 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001089 return V;
1090
Craig Topper9f008862014-04-15 04:59:12 +00001091 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001092}
1093
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001094Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001095 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001096 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001097 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001098 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001099 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001100}
1101
Sanjay Patel472cc782016-01-11 22:14:42 +00001102/// Given operands for a UDiv, see if we can fold the result.
1103/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001104static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1105 unsigned MaxRecurse) {
1106 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001107 return V;
1108
David Majnemer63da0c22017-01-06 22:58:02 +00001109 // udiv %V, C -> 0 if %V < C
1110 if (MaxRecurse) {
1111 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1112 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1113 if (C->isAllOnesValue()) {
1114 return Constant::getNullValue(Op0->getType());
1115 }
1116 }
1117 }
1118
Craig Topper9f008862014-04-15 04:59:12 +00001119 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001120}
1121
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001122Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001123 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001124 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001125 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001126 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001127 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001128}
1129
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001130static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1131 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001132 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001133 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001134 return Op0;
1135
1136 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001137 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001138 return Op1;
1139
Zia Ansari394cef82016-12-08 23:27:40 +00001140 // X / 1.0 -> X
1141 if (match(Op1, m_FPOne()))
1142 return Op0;
1143
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001144 // 0 / X -> 0
1145 // Requires that NaNs are off (X could be zero) and signed zeroes are
1146 // ignored (X could be positive or negative, so the output sign is unknown).
1147 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1148 return Op0;
1149
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001150 if (FMF.noNaNs()) {
1151 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001152 if (Op0 == Op1)
1153 return ConstantFP::get(Op0->getType(), 1.0);
1154
1155 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001156 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001157 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1158 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1159 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1160 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1161 BinaryOperator::getFNegArgument(Op1) == Op0))
1162 return ConstantFP::get(Op0->getType(), -1.0);
1163 }
1164
Craig Topper9f008862014-04-15 04:59:12 +00001165 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001166}
1167
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001168Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001170 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001171 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001172 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001173 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001174 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001175}
1176
Sanjay Patel472cc782016-01-11 22:14:42 +00001177/// Given operands for an SRem or URem, see if we can fold the result.
1178/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001179static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001180 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001181 if (Constant *C0 = dyn_cast<Constant>(Op0))
1182 if (Constant *C1 = dyn_cast<Constant>(Op1))
1183 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001184
Duncan Sandsa3e36992011-05-02 16:27:02 +00001185 // X % undef -> undef
1186 if (match(Op1, m_Undef()))
1187 return Op1;
1188
1189 // undef % X -> 0
1190 if (match(Op0, m_Undef()))
1191 return Constant::getNullValue(Op0->getType());
1192
1193 // 0 % X -> 0, we don't need to preserve faults!
1194 if (match(Op0, m_Zero()))
1195 return Op0;
1196
1197 // X % 0 -> undef, we don't need to preserve faults!
1198 if (match(Op1, m_Zero()))
1199 return UndefValue::get(Op0->getType());
1200
1201 // X % 1 -> 0
1202 if (match(Op1, m_One()))
1203 return Constant::getNullValue(Op0->getType());
1204
1205 if (Op0->getType()->isIntegerTy(1))
1206 // It can't be remainder by zero, hence it must be remainder by one.
1207 return Constant::getNullValue(Op0->getType());
1208
1209 // X % X -> 0
1210 if (Op0 == Op1)
1211 return Constant::getNullValue(Op0->getType());
1212
David Majnemerb435a422014-09-17 04:16:35 +00001213 // (X % Y) % Y -> X % Y
1214 if ((Opcode == Instruction::SRem &&
1215 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1216 (Opcode == Instruction::URem &&
1217 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001218 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001219
Duncan Sandsa3e36992011-05-02 16:27:02 +00001220 // If the operation is with the result of a select instruction, check whether
1221 // operating on either branch of the select always yields the same value.
1222 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001223 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001224 return V;
1225
1226 // If the operation is with the result of a phi instruction, check whether
1227 // operating on all incoming values of the phi always yields the same value.
1228 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001229 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230 return V;
1231
Craig Topper9f008862014-04-15 04:59:12 +00001232 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233}
1234
Sanjay Patel472cc782016-01-11 22:14:42 +00001235/// Given operands for an SRem, see if we can fold the result.
1236/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001237static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1238 unsigned MaxRecurse) {
1239 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001240 return V;
1241
Craig Topper9f008862014-04-15 04:59:12 +00001242 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001243}
1244
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001245Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001246 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001247 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001248 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001249 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001250 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001251}
1252
Sanjay Patel472cc782016-01-11 22:14:42 +00001253/// Given operands for a URem, see if we can fold the result.
1254/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001255static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001256 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001257 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001258 return V;
1259
David Majnemer8c0e62f2017-01-06 21:23:51 +00001260 // urem %V, C -> %V if %V < C
1261 if (MaxRecurse) {
1262 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1263 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1264 if (C->isAllOnesValue()) {
1265 return Op0;
1266 }
1267 }
1268 }
1269
Craig Topper9f008862014-04-15 04:59:12 +00001270 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001271}
1272
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001274 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001275 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001276 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001277 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001278 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001279}
1280
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001281static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1282 const Query &, unsigned) {
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.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001338static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001339 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001340 if (Constant *C0 = dyn_cast<Constant>(Op0))
1341 if (Constant *C1 = dyn_cast<Constant>(Op1))
1342 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001343
Duncan Sands571fd9a2011-01-14 14:44:12 +00001344 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001345 if (match(Op0, m_Zero()))
1346 return Op0;
1347
Duncan Sands571fd9a2011-01-14 14:44:12 +00001348 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001349 if (match(Op1, m_Zero()))
1350 return Op0;
1351
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001352 // Fold undefined shifts.
1353 if (isUndefShift(Op1))
1354 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001355
Duncan Sands571fd9a2011-01-14 14:44:12 +00001356 // If the operation is with the result of a select instruction, check whether
1357 // operating on either branch of the select always yields the same value.
1358 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001359 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001360 return V;
1361
1362 // If the operation is with the result of a phi instruction, check whether
1363 // operating on all incoming values of the phi always yields the same value.
1364 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001365 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001366 return V;
1367
Sanjay Patel6786bc52016-05-10 20:46:54 +00001368 // If any bits in the shift amount make that value greater than or equal to
1369 // the number of bits in the type, the shift is undefined.
1370 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1371 APInt KnownZero(BitWidth, 0);
1372 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001373 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001374 if (KnownOne.getLimitedValue() >= BitWidth)
1375 return UndefValue::get(Op0->getType());
1376
1377 // If all valid bits in the shift amount are known zero, the first operand is
1378 // unchanged.
1379 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1380 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1381 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1382 return Op0;
1383
Craig Topper9f008862014-04-15 04:59:12 +00001384 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001385}
1386
David Majnemerbf7550e2014-11-05 00:59:59 +00001387/// \brief Given operands for an Shl, LShr or AShr, see if we can
1388/// fold the result. If not, this returns null.
1389static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1390 bool isExact, const Query &Q,
1391 unsigned MaxRecurse) {
1392 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1393 return V;
1394
1395 // X >> X -> 0
1396 if (Op0 == Op1)
1397 return Constant::getNullValue(Op0->getType());
1398
David Majnemer65c52ae2014-12-17 01:54:33 +00001399 // undef >> X -> 0
1400 // undef >> X -> undef (if it's exact)
1401 if (match(Op0, m_Undef()))
1402 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1403
David Majnemerbf7550e2014-11-05 00:59:59 +00001404 // The low bit cannot be shifted out of an exact shift if it is set.
1405 if (isExact) {
1406 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1407 APInt Op0KnownZero(BitWidth, 0);
1408 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001409 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1410 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001411 if (Op0KnownOne[0])
1412 return Op0;
1413 }
1414
1415 return nullptr;
1416}
1417
Sanjay Patel472cc782016-01-11 22:14:42 +00001418/// Given operands for an Shl, see if we can fold the result.
1419/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001420static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001421 const Query &Q, unsigned MaxRecurse) {
1422 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001423 return V;
1424
1425 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001426 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001427 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001428 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001429
Chris Lattner9e4aa022011-02-09 17:15:04 +00001430 // (X >> A) << A -> X
1431 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001432 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001433 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001434 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001435}
1436
Chris Lattner9e4aa022011-02-09 17:15:04 +00001437Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001439 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001440 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001441 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001442 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001443}
1444
Sanjay Patel472cc782016-01-11 22:14:42 +00001445/// Given operands for an LShr, see if we can fold the result.
1446/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001447static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001448 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001449 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1450 MaxRecurse))
1451 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001452
Chris Lattner9e4aa022011-02-09 17:15:04 +00001453 // (X << A) >> A -> X
1454 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001455 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001456 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001457
Craig Topper9f008862014-04-15 04:59:12 +00001458 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001459}
1460
Chris Lattner9e4aa022011-02-09 17:15:04 +00001461Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001462 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001463 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001464 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001465 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001466 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001467 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001468}
1469
Sanjay Patel472cc782016-01-11 22:14:42 +00001470/// Given operands for an AShr, see if we can fold the result.
1471/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001472static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001473 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001474 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1475 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001476 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001477
1478 // all ones >>a X -> all ones
1479 if (match(Op0, m_AllOnes()))
1480 return Op0;
1481
Chris Lattner9e4aa022011-02-09 17:15:04 +00001482 // (X << A) >> A -> X
1483 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001484 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001485 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001486
Suyog Sarda68862412014-07-17 06:28:15 +00001487 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001488 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001489 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1490 return Op0;
1491
Craig Topper9f008862014-04-15 04:59:12 +00001492 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001493}
1494
Chris Lattner9e4aa022011-02-09 17:15:04 +00001495Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001496 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001497 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001498 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001499 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001500 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001501 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001502}
1503
David Majnemer1af36e52014-12-06 10:51:40 +00001504static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1505 ICmpInst *UnsignedICmp, bool IsAnd) {
1506 Value *X, *Y;
1507
1508 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001509 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1510 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001511 return nullptr;
1512
1513 ICmpInst::Predicate UnsignedPred;
1514 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1515 ICmpInst::isUnsigned(UnsignedPred))
1516 ;
1517 else if (match(UnsignedICmp,
1518 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1519 ICmpInst::isUnsigned(UnsignedPred))
1520 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1521 else
1522 return nullptr;
1523
1524 // X < Y && Y != 0 --> X < Y
1525 // X < Y || Y != 0 --> Y != 0
1526 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1527 return IsAnd ? UnsignedICmp : ZeroICmp;
1528
1529 // X >= Y || Y != 0 --> true
1530 // X >= Y || Y == 0 --> X >= Y
1531 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1532 if (EqPred == ICmpInst::ICMP_NE)
1533 return getTrue(UnsignedICmp->getType());
1534 return UnsignedICmp;
1535 }
1536
David Majnemerd5b3aa42014-12-08 18:30:43 +00001537 // X < Y && Y == 0 --> false
1538 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1539 IsAnd)
1540 return getFalse(UnsignedICmp->getType());
1541
David Majnemer1af36e52014-12-06 10:51:40 +00001542 return nullptr;
1543}
1544
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001545/// Commuted variants are assumed to be handled by calling this function again
1546/// with the parameters swapped.
1547static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1548 ICmpInst::Predicate Pred0, Pred1;
1549 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001550 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1551 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001552 return nullptr;
1553
1554 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1555 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1556 // can eliminate Op1 from this 'and'.
1557 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1558 return Op0;
1559
1560 // Check for any combination of predicates that are guaranteed to be disjoint.
1561 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1562 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1563 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1564 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1565 return getFalse(Op0->getType());
1566
1567 return nullptr;
1568}
1569
1570/// Commuted variants are assumed to be handled by calling this function again
1571/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001572static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001573 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1574 return X;
1575
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001576 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1577 return X;
1578
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001579 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001580 Type *ITy = Op0->getType();
1581 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001582 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001583 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001584 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1585 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1586 // Make a constant range that's the intersection of the two icmp ranges.
1587 // If the intersection is empty, we know that the result is false.
1588 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1589 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1590 if (Range0.intersectWith(Range1).isEmptySet())
1591 return getFalse(ITy);
1592 }
1593
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001594 // (icmp (add V, C0), C1) & (icmp V, C0)
1595 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001596 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001597
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001598 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001599 return nullptr;
1600
David Majnemera315bd82014-09-15 08:15:28 +00001601 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001602 if (AddInst->getOperand(1) != Op1->getOperand(1))
1603 return nullptr;
1604
David Majnemera315bd82014-09-15 08:15:28 +00001605 bool isNSW = AddInst->hasNoSignedWrap();
1606 bool isNUW = AddInst->hasNoUnsignedWrap();
1607
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001608 const APInt Delta = *C1 - *C0;
1609 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001610 if (Delta == 2) {
1611 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1612 return getFalse(ITy);
1613 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1614 return getFalse(ITy);
1615 }
1616 if (Delta == 1) {
1617 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1618 return getFalse(ITy);
1619 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1620 return getFalse(ITy);
1621 }
1622 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001623 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001624 if (Delta == 2)
1625 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1626 return getFalse(ITy);
1627 if (Delta == 1)
1628 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1629 return getFalse(ITy);
1630 }
1631
1632 return nullptr;
1633}
1634
Sanjay Patel472cc782016-01-11 22:14:42 +00001635/// Given operands for an And, see if we can fold the result.
1636/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001637static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001638 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001639 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001640 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1641 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001642
Chris Lattnera71e9d62009-11-10 00:55:12 +00001643 // Canonicalize the constant to the RHS.
1644 std::swap(Op0, Op1);
1645 }
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) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001841 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001842 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1843 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001844
Chris Lattnera71e9d62009-11-10 00:55:12 +00001845 // Canonicalize the constant to the RHS.
1846 std::swap(Op0, Op1);
1847 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001848
Chris Lattnera71e9d62009-11-10 00:55:12 +00001849 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001850 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001851 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001852
Chris Lattnera71e9d62009-11-10 00:55:12 +00001853 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001854 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001855 return Op0;
1856
Duncan Sandsc89ac072010-11-17 18:52:15 +00001857 // X | 0 = X
1858 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001859 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001860
Duncan Sandsc89ac072010-11-17 18:52:15 +00001861 // X | -1 = -1
1862 if (match(Op1, m_AllOnes()))
1863 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001864
Chris Lattnera71e9d62009-11-10 00:55:12 +00001865 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001866 if (match(Op0, m_Not(m_Specific(Op1))) ||
1867 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001868 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001869
Chris Lattnera71e9d62009-11-10 00:55:12 +00001870 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001871 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001872 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001873 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001874 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001875
Chris Lattnera71e9d62009-11-10 00:55:12 +00001876 // A | (A & ?) = A
1877 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001878 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001879 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001880
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001881 // ~(A & ?) | A = -1
1882 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1883 (A == Op1 || B == Op1))
1884 return Constant::getAllOnesValue(Op1->getType());
1885
1886 // A | ~(A & ?) = -1
1887 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1888 (A == Op0 || B == Op0))
1889 return Constant::getAllOnesValue(Op0->getType());
1890
David Majnemera315bd82014-09-15 08:15:28 +00001891 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1892 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1893 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1894 return V;
1895 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1896 return V;
1897 }
1898 }
1899
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001900 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001901 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1902 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001903 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001904
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001905 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001906 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1907 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001908 return V;
1909
Duncan Sandsb0579e92010-11-10 13:00:08 +00001910 // If the operation is with the result of a select instruction, check whether
1911 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001912 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001913 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001914 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001915 return V;
1916
Nick Lewycky8561a492014-06-19 03:51:46 +00001917 // (A & C)|(B & D)
1918 Value *C = nullptr, *D = nullptr;
1919 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1920 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1921 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1922 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1923 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1924 // (A & C1)|(B & C2)
1925 // If we have: ((V + N) & C1) | (V & C2)
1926 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1927 // replace with V+N.
1928 Value *V1, *V2;
1929 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1930 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1931 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001932 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001933 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001934 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001935 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001936 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001937 return A;
1938 }
1939 // Or commutes, try both ways.
1940 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1941 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1942 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001943 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001944 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001945 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001946 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001947 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001948 return B;
1949 }
1950 }
1951 }
1952
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001953 // If the operation is with the result of a phi instruction, check whether
1954 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001955 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001956 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001957 return V;
1958
Craig Topper9f008862014-04-15 04:59:12 +00001959 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001960}
1961
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001962Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001963 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001964 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001965 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001966 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001967 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001968}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001969
Sanjay Patel472cc782016-01-11 22:14:42 +00001970/// Given operands for a Xor, see if we can fold the result.
1971/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001972static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1973 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001974 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001975 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1976 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001977
1978 // Canonicalize the constant to the RHS.
1979 std::swap(Op0, Op1);
1980 }
1981
1982 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001983 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001984 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001985
1986 // A ^ 0 = A
1987 if (match(Op1, m_Zero()))
1988 return Op0;
1989
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001990 // A ^ A = 0
1991 if (Op0 == Op1)
1992 return Constant::getNullValue(Op0->getType());
1993
Duncan Sandsc89ac072010-11-17 18:52:15 +00001994 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001995 if (match(Op0, m_Not(m_Specific(Op1))) ||
1996 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001997 return Constant::getAllOnesValue(Op0->getType());
1998
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001999 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002000 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2001 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002002 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002003
Duncan Sandsb238de02010-11-19 09:20:39 +00002004 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2005 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2006 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2007 // only if B and C are equal. If B and C are equal then (since we assume
2008 // that operands have already been simplified) "select(cond, B, C)" should
2009 // have been simplified to the common value of B and C already. Analysing
2010 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2011 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002012
Craig Topper9f008862014-04-15 04:59:12 +00002013 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002014}
2015
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002016Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002017 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002018 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002019 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002020 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002021 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002022}
2023
Chris Lattner229907c2011-07-18 04:54:35 +00002024static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002025 return CmpInst::makeCmpResultType(Op->getType());
2026}
2027
Sanjay Patel472cc782016-01-11 22:14:42 +00002028/// Rummage around inside V looking for something equivalent to the comparison
2029/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2030/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002031static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2032 Value *LHS, Value *RHS) {
2033 SelectInst *SI = dyn_cast<SelectInst>(V);
2034 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002035 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002036 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2037 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002038 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002039 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2040 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2041 return Cmp;
2042 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2043 LHS == CmpRHS && RHS == CmpLHS)
2044 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002045 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002046}
2047
Dan Gohman9631d902013-02-01 00:49:06 +00002048// A significant optimization not implemented here is assuming that alloca
2049// addresses are not equal to incoming argument values. They don't *alias*,
2050// as we say, but that doesn't mean they aren't equal, so we take a
2051// conservative approach.
2052//
2053// This is inspired in part by C++11 5.10p1:
2054// "Two pointers of the same type compare equal if and only if they are both
2055// null, both point to the same function, or both represent the same
2056// address."
2057//
2058// This is pretty permissive.
2059//
2060// It's also partly due to C11 6.5.9p6:
2061// "Two pointers compare equal if and only if both are null pointers, both are
2062// pointers to the same object (including a pointer to an object and a
2063// subobject at its beginning) or function, both are pointers to one past the
2064// last element of the same array object, or one is a pointer to one past the
2065// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002066// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002067// object in the address space.)
2068//
2069// C11's version is more restrictive, however there's no reason why an argument
2070// couldn't be a one-past-the-end value for a stack object in the caller and be
2071// equal to the beginning of a stack object in the callee.
2072//
2073// If the C and C++ standards are ever made sufficiently restrictive in this
2074// area, it may be possible to update LLVM's semantics accordingly and reinstate
2075// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002076static Constant *
2077computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2078 const DominatorTree *DT, CmpInst::Predicate Pred,
2079 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002080 // First, skip past any trivial no-ops.
2081 LHS = LHS->stripPointerCasts();
2082 RHS = RHS->stripPointerCasts();
2083
2084 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002085 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002086 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2087 return ConstantInt::get(GetCompareTy(LHS),
2088 !CmpInst::isTrueWhenEqual(Pred));
2089
Chandler Carruth8059c842012-03-25 21:28:14 +00002090 // We can only fold certain predicates on pointer comparisons.
2091 switch (Pred) {
2092 default:
Craig Topper9f008862014-04-15 04:59:12 +00002093 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002094
2095 // Equality comaprisons are easy to fold.
2096 case CmpInst::ICMP_EQ:
2097 case CmpInst::ICMP_NE:
2098 break;
2099
2100 // We can only handle unsigned relational comparisons because 'inbounds' on
2101 // a GEP only protects against unsigned wrapping.
2102 case CmpInst::ICMP_UGT:
2103 case CmpInst::ICMP_UGE:
2104 case CmpInst::ICMP_ULT:
2105 case CmpInst::ICMP_ULE:
2106 // However, we have to switch them to their signed variants to handle
2107 // negative indices from the base pointer.
2108 Pred = ICmpInst::getSignedPredicate(Pred);
2109 break;
2110 }
2111
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002112 // Strip off any constant offsets so that we can reason about them.
2113 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2114 // here and compare base addresses like AliasAnalysis does, however there are
2115 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2116 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2117 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002118 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2119 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002120
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002121 // If LHS and RHS are related via constant offsets to the same base
2122 // value, we can replace it with an icmp which just compares the offsets.
2123 if (LHS == RHS)
2124 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002125
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002126 // Various optimizations for (in)equality comparisons.
2127 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2128 // Different non-empty allocations that exist at the same time have
2129 // different addresses (if the program can tell). Global variables always
2130 // exist, so they always exist during the lifetime of each other and all
2131 // allocas. Two different allocas usually have different addresses...
2132 //
2133 // However, if there's an @llvm.stackrestore dynamically in between two
2134 // allocas, they may have the same address. It's tempting to reduce the
2135 // scope of the problem by only looking at *static* allocas here. That would
2136 // cover the majority of allocas while significantly reducing the likelihood
2137 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2138 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2139 // an entry block. Also, if we have a block that's not attached to a
2140 // function, we can't tell if it's "static" under the current definition.
2141 // Theoretically, this problem could be fixed by creating a new kind of
2142 // instruction kind specifically for static allocas. Such a new instruction
2143 // could be required to be at the top of the entry block, thus preventing it
2144 // from being subject to a @llvm.stackrestore. Instcombine could even
2145 // convert regular allocas into these special allocas. It'd be nifty.
2146 // However, until then, this problem remains open.
2147 //
2148 // So, we'll assume that two non-empty allocas have different addresses
2149 // for now.
2150 //
2151 // With all that, if the offsets are within the bounds of their allocations
2152 // (and not one-past-the-end! so we can't use inbounds!), and their
2153 // allocations aren't the same, the pointers are not equal.
2154 //
2155 // Note that it's not necessary to check for LHS being a global variable
2156 // address, due to canonicalization and constant folding.
2157 if (isa<AllocaInst>(LHS) &&
2158 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002159 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2160 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002161 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002162 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002163 getObjectSize(LHS, LHSSize, DL, TLI) &&
2164 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002165 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2166 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002167 if (!LHSOffsetValue.isNegative() &&
2168 !RHSOffsetValue.isNegative() &&
2169 LHSOffsetValue.ult(LHSSize) &&
2170 RHSOffsetValue.ult(RHSSize)) {
2171 return ConstantInt::get(GetCompareTy(LHS),
2172 !CmpInst::isTrueWhenEqual(Pred));
2173 }
2174 }
2175
2176 // Repeat the above check but this time without depending on DataLayout
2177 // or being able to compute a precise size.
2178 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2179 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2180 LHSOffset->isNullValue() &&
2181 RHSOffset->isNullValue())
2182 return ConstantInt::get(GetCompareTy(LHS),
2183 !CmpInst::isTrueWhenEqual(Pred));
2184 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002185
2186 // Even if an non-inbounds GEP occurs along the path we can still optimize
2187 // equality comparisons concerning the result. We avoid walking the whole
2188 // chain again by starting where the last calls to
2189 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002190 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2191 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002192 if (LHS == RHS)
2193 return ConstantExpr::getICmp(Pred,
2194 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2195 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002196
2197 // If one side of the equality comparison must come from a noalias call
2198 // (meaning a system memory allocation function), and the other side must
2199 // come from a pointer that cannot overlap with dynamically-allocated
2200 // memory within the lifetime of the current function (allocas, byval
2201 // arguments, globals), then determine the comparison result here.
2202 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2203 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2204 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2205
2206 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002207 auto IsNAC = [](ArrayRef<Value *> Objects) {
2208 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002209 };
2210
2211 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002212 // noalias calls. For allocas, we consider only static ones (dynamic
2213 // allocas might be transformed into calls to malloc not simultaneously
2214 // live with the compared-to allocation). For globals, we exclude symbols
2215 // that might be resolve lazily to symbols in another dynamically-loaded
2216 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002217 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2218 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002219 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2220 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2221 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2222 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002223 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002224 !GV->isThreadLocal();
2225 if (const Argument *A = dyn_cast<Argument>(V))
2226 return A->hasByValAttr();
2227 return false;
2228 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002229 };
2230
2231 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2232 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2233 return ConstantInt::get(GetCompareTy(LHS),
2234 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002235
2236 // Fold comparisons for non-escaping pointer even if the allocation call
2237 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2238 // dynamic allocation call could be either of the operands.
2239 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002240 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002241 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002242 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002243 MI = RHS;
2244 // FIXME: We should also fold the compare when the pointer escapes, but the
2245 // compare dominates the pointer escape
2246 if (MI && !PointerMayBeCaptured(MI, true, true))
2247 return ConstantInt::get(GetCompareTy(LHS),
2248 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002249 }
2250
2251 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002252 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002253}
Chris Lattner01990f02012-02-24 19:01:58 +00002254
Sanjay Pateldc65a272016-12-03 17:30:22 +00002255/// Fold an icmp when its operands have i1 scalar type.
2256static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2257 Value *RHS, const Query &Q) {
2258 Type *ITy = GetCompareTy(LHS); // The return type.
2259 Type *OpTy = LHS->getType(); // The operand type.
2260 if (!OpTy->getScalarType()->isIntegerTy(1))
2261 return nullptr;
2262
2263 switch (Pred) {
2264 default:
2265 break;
2266 case ICmpInst::ICMP_EQ:
2267 // X == 1 -> X
2268 if (match(RHS, m_One()))
2269 return LHS;
2270 break;
2271 case ICmpInst::ICMP_NE:
2272 // X != 0 -> X
2273 if (match(RHS, m_Zero()))
2274 return LHS;
2275 break;
2276 case ICmpInst::ICMP_UGT:
2277 // X >u 0 -> X
2278 if (match(RHS, m_Zero()))
2279 return LHS;
2280 break;
2281 case ICmpInst::ICMP_UGE:
2282 // X >=u 1 -> X
2283 if (match(RHS, m_One()))
2284 return LHS;
2285 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2286 return getTrue(ITy);
2287 break;
2288 case ICmpInst::ICMP_SGE:
2289 /// For signed comparison, the values for an i1 are 0 and -1
2290 /// respectively. This maps into a truth table of:
2291 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2292 /// 0 | 0 | 1 (0 >= 0) | 1
2293 /// 0 | 1 | 1 (0 >= -1) | 1
2294 /// 1 | 0 | 0 (-1 >= 0) | 0
2295 /// 1 | 1 | 1 (-1 >= -1) | 1
2296 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2297 return getTrue(ITy);
2298 break;
2299 case ICmpInst::ICMP_SLT:
2300 // X <s 0 -> X
2301 if (match(RHS, m_Zero()))
2302 return LHS;
2303 break;
2304 case ICmpInst::ICMP_SLE:
2305 // X <=s -1 -> X
2306 if (match(RHS, m_One()))
2307 return LHS;
2308 break;
2309 case ICmpInst::ICMP_ULE:
2310 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2311 return getTrue(ITy);
2312 break;
2313 }
2314
2315 return nullptr;
2316}
2317
2318/// Try hard to fold icmp with zero RHS because this is a common case.
2319static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2320 Value *RHS, const Query &Q) {
2321 if (!match(RHS, m_Zero()))
2322 return nullptr;
2323
2324 Type *ITy = GetCompareTy(LHS); // The return type.
2325 bool LHSKnownNonNegative, LHSKnownNegative;
2326 switch (Pred) {
2327 default:
2328 llvm_unreachable("Unknown ICmp predicate!");
2329 case ICmpInst::ICMP_ULT:
2330 return getFalse(ITy);
2331 case ICmpInst::ICMP_UGE:
2332 return getTrue(ITy);
2333 case ICmpInst::ICMP_EQ:
2334 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002335 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002336 return getFalse(ITy);
2337 break;
2338 case ICmpInst::ICMP_NE:
2339 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002340 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002341 return getTrue(ITy);
2342 break;
2343 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002344 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2345 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002346 if (LHSKnownNegative)
2347 return getTrue(ITy);
2348 if (LHSKnownNonNegative)
2349 return getFalse(ITy);
2350 break;
2351 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002352 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2353 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002354 if (LHSKnownNegative)
2355 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002356 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002357 return getFalse(ITy);
2358 break;
2359 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002360 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2361 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002362 if (LHSKnownNegative)
2363 return getFalse(ITy);
2364 if (LHSKnownNonNegative)
2365 return getTrue(ITy);
2366 break;
2367 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002368 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2369 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002370 if (LHSKnownNegative)
2371 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002372 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002373 return getTrue(ITy);
2374 break;
2375 }
2376
2377 return nullptr;
2378}
2379
Sanjay Patelbe332132017-01-23 18:22:26 +00002380/// Many binary operators with a constant operand have an easy-to-compute
2381/// range of outputs. This can be used to fold a comparison to always true or
2382/// always false.
2383static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2384 unsigned Width = Lower.getBitWidth();
2385 const APInt *C;
2386 switch (BO.getOpcode()) {
2387 case Instruction::Add:
2388 if (BO.hasNoUnsignedWrap() && match(BO.getOperand(1), m_APInt(C)))
2389 // 'add nuw x, C' produces [C, UINT_MAX].
2390 Lower = *C;
2391 break;
2392
2393 case Instruction::And:
2394 if (match(BO.getOperand(1), m_APInt(C)))
2395 // 'and x, C' produces [0, C].
2396 Upper = *C + 1;
2397 break;
2398
2399 case Instruction::Or:
2400 if (match(BO.getOperand(1), m_APInt(C)))
2401 // 'or x, C' produces [C, UINT_MAX].
2402 Lower = *C;
2403 break;
2404
2405 case Instruction::AShr:
2406 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2407 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2408 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2409 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2410 } else if (match(BO.getOperand(0), m_APInt(C))) {
2411 unsigned ShiftAmount = Width - 1;
2412 if (*C != 0 && BO.isExact())
2413 ShiftAmount = C->countTrailingZeros();
2414 if (C->isNegative()) {
2415 // 'ashr C, x' produces [C, C >> (Width-1)]
2416 Lower = *C;
2417 Upper = C->ashr(ShiftAmount) + 1;
2418 } else {
2419 // 'ashr C, x' produces [C >> (Width-1), C]
2420 Lower = C->ashr(ShiftAmount);
2421 Upper = *C + 1;
2422 }
2423 }
2424 break;
2425
2426 case Instruction::LShr:
2427 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2428 // 'lshr x, C' produces [0, UINT_MAX >> C].
2429 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2430 } else if (match(BO.getOperand(0), m_APInt(C))) {
2431 // 'lshr C, x' produces [C >> (Width-1), C].
2432 unsigned ShiftAmount = Width - 1;
2433 if (*C != 0 && BO.isExact())
2434 ShiftAmount = C->countTrailingZeros();
2435 Lower = C->lshr(ShiftAmount);
2436 Upper = *C + 1;
2437 }
2438 break;
2439
2440 case Instruction::Shl:
2441 if (match(BO.getOperand(0), m_APInt(C))) {
2442 if (BO.hasNoUnsignedWrap()) {
2443 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2444 Lower = *C;
2445 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2446 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2447 if (C->isNegative()) {
2448 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2449 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2450 Lower = C->shl(ShiftAmount);
2451 Upper = *C + 1;
2452 } else {
2453 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2454 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2455 Lower = *C;
2456 Upper = C->shl(ShiftAmount) + 1;
2457 }
2458 }
2459 }
2460 break;
2461
2462 case Instruction::SDiv:
2463 if (match(BO.getOperand(1), m_APInt(C))) {
2464 APInt IntMin = APInt::getSignedMinValue(Width);
2465 APInt IntMax = APInt::getSignedMaxValue(Width);
2466 if (C->isAllOnesValue()) {
2467 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2468 // where C != -1 and C != 0 and C != 1
2469 Lower = IntMin + 1;
2470 Upper = IntMax + 1;
2471 } else if (C->countLeadingZeros() < Width - 1) {
2472 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2473 // where C != -1 and C != 0 and C != 1
2474 Lower = IntMin.sdiv(*C);
2475 Upper = IntMax.sdiv(*C);
2476 if (Lower.sgt(Upper))
2477 std::swap(Lower, Upper);
2478 Upper = Upper + 1;
2479 assert(Upper != Lower && "Upper part of range has wrapped!");
2480 }
2481 } else if (match(BO.getOperand(0), m_APInt(C))) {
2482 if (C->isMinSignedValue()) {
2483 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2484 Lower = *C;
2485 Upper = Lower.lshr(1) + 1;
2486 } else {
2487 // 'sdiv C, x' produces [-|C|, |C|].
2488 Upper = C->abs() + 1;
2489 Lower = (-Upper) + 1;
2490 }
2491 }
2492 break;
2493
2494 case Instruction::UDiv:
2495 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2496 // 'udiv x, C' produces [0, UINT_MAX / C].
2497 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2498 } else if (match(BO.getOperand(0), m_APInt(C))) {
2499 // 'udiv C, x' produces [0, C].
2500 Upper = *C + 1;
2501 }
2502 break;
2503
2504 case Instruction::SRem:
2505 if (match(BO.getOperand(1), m_APInt(C))) {
2506 // 'srem x, C' produces (-|C|, |C|).
2507 Upper = C->abs();
2508 Lower = (-Upper) + 1;
2509 }
2510 break;
2511
2512 case Instruction::URem:
2513 if (match(BO.getOperand(1), m_APInt(C)))
2514 // 'urem x, C' produces [0, C).
2515 Upper = *C;
2516 break;
2517
2518 default:
2519 break;
2520 }
2521}
2522
Sanjay Patel67bde282016-08-22 23:12:02 +00002523static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2524 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002525 const APInt *C;
2526 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002527 return nullptr;
2528
2529 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002530 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002531 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002532 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002533 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002534 return ConstantInt::getTrue(GetCompareTy(RHS));
2535
Sanjay Patelbe332132017-01-23 18:22:26 +00002536 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002537 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002538 APInt Lower = APInt(Width, 0);
2539 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002540 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2541 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002542
2543 ConstantRange LHS_CR =
2544 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2545
2546 if (auto *I = dyn_cast<Instruction>(LHS))
2547 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2548 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2549
2550 if (!LHS_CR.isFullSet()) {
2551 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002552 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002553 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002554 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002555 }
2556
2557 return nullptr;
2558}
2559
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002560static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2561 Value *RHS, const Query &Q,
2562 unsigned MaxRecurse) {
2563 Type *ITy = GetCompareTy(LHS); // The return type.
2564
2565 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2566 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2567 if (MaxRecurse && (LBO || RBO)) {
2568 // Analyze the case when either LHS or RHS is an add instruction.
2569 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2570 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2571 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2572 if (LBO && LBO->getOpcode() == Instruction::Add) {
2573 A = LBO->getOperand(0);
2574 B = LBO->getOperand(1);
2575 NoLHSWrapProblem =
2576 ICmpInst::isEquality(Pred) ||
2577 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2578 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2579 }
2580 if (RBO && RBO->getOpcode() == Instruction::Add) {
2581 C = RBO->getOperand(0);
2582 D = RBO->getOperand(1);
2583 NoRHSWrapProblem =
2584 ICmpInst::isEquality(Pred) ||
2585 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2586 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2587 }
2588
2589 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2590 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2591 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2592 Constant::getNullValue(RHS->getType()), Q,
2593 MaxRecurse - 1))
2594 return V;
2595
2596 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2597 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2598 if (Value *V =
2599 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2600 C == LHS ? D : C, Q, MaxRecurse - 1))
2601 return V;
2602
2603 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2604 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2605 NoRHSWrapProblem) {
2606 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2607 Value *Y, *Z;
2608 if (A == C) {
2609 // C + B == C + D -> B == D
2610 Y = B;
2611 Z = D;
2612 } else if (A == D) {
2613 // D + B == C + D -> B == C
2614 Y = B;
2615 Z = C;
2616 } else if (B == C) {
2617 // A + C == C + D -> A == D
2618 Y = A;
2619 Z = D;
2620 } else {
2621 assert(B == D);
2622 // A + D == C + D -> A == C
2623 Y = A;
2624 Z = C;
2625 }
2626 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2627 return V;
2628 }
2629 }
2630
2631 {
2632 Value *Y = nullptr;
2633 // icmp pred (or X, Y), X
2634 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2635 if (Pred == ICmpInst::ICMP_ULT)
2636 return getFalse(ITy);
2637 if (Pred == ICmpInst::ICMP_UGE)
2638 return getTrue(ITy);
2639
2640 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2641 bool RHSKnownNonNegative, RHSKnownNegative;
2642 bool YKnownNonNegative, YKnownNegative;
2643 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002644 Q.AC, Q.CxtI, Q.DT);
2645 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002646 Q.CxtI, Q.DT);
2647 if (RHSKnownNonNegative && YKnownNegative)
2648 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2649 if (RHSKnownNegative || YKnownNonNegative)
2650 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2651 }
2652 }
2653 // icmp pred X, (or X, Y)
2654 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2655 if (Pred == ICmpInst::ICMP_ULE)
2656 return getTrue(ITy);
2657 if (Pred == ICmpInst::ICMP_UGT)
2658 return getFalse(ITy);
2659
2660 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2661 bool LHSKnownNonNegative, LHSKnownNegative;
2662 bool YKnownNonNegative, YKnownNegative;
2663 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002664 Q.AC, Q.CxtI, Q.DT);
2665 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002666 Q.CxtI, Q.DT);
2667 if (LHSKnownNonNegative && YKnownNegative)
2668 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2669 if (LHSKnownNegative || YKnownNonNegative)
2670 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2671 }
2672 }
2673 }
2674
2675 // icmp pred (and X, Y), X
2676 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2677 m_And(m_Specific(RHS), m_Value())))) {
2678 if (Pred == ICmpInst::ICMP_UGT)
2679 return getFalse(ITy);
2680 if (Pred == ICmpInst::ICMP_ULE)
2681 return getTrue(ITy);
2682 }
2683 // icmp pred X, (and X, Y)
2684 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2685 m_And(m_Specific(LHS), m_Value())))) {
2686 if (Pred == ICmpInst::ICMP_UGE)
2687 return getTrue(ITy);
2688 if (Pred == ICmpInst::ICMP_ULT)
2689 return getFalse(ITy);
2690 }
2691
2692 // 0 - (zext X) pred C
2693 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2694 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2695 if (RHSC->getValue().isStrictlyPositive()) {
2696 if (Pred == ICmpInst::ICMP_SLT)
2697 return ConstantInt::getTrue(RHSC->getContext());
2698 if (Pred == ICmpInst::ICMP_SGE)
2699 return ConstantInt::getFalse(RHSC->getContext());
2700 if (Pred == ICmpInst::ICMP_EQ)
2701 return ConstantInt::getFalse(RHSC->getContext());
2702 if (Pred == ICmpInst::ICMP_NE)
2703 return ConstantInt::getTrue(RHSC->getContext());
2704 }
2705 if (RHSC->getValue().isNonNegative()) {
2706 if (Pred == ICmpInst::ICMP_SLE)
2707 return ConstantInt::getTrue(RHSC->getContext());
2708 if (Pred == ICmpInst::ICMP_SGT)
2709 return ConstantInt::getFalse(RHSC->getContext());
2710 }
2711 }
2712 }
2713
2714 // icmp pred (urem X, Y), Y
2715 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2716 bool KnownNonNegative, KnownNegative;
2717 switch (Pred) {
2718 default:
2719 break;
2720 case ICmpInst::ICMP_SGT:
2721 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002722 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2723 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002724 if (!KnownNonNegative)
2725 break;
2726 LLVM_FALLTHROUGH;
2727 case ICmpInst::ICMP_EQ:
2728 case ICmpInst::ICMP_UGT:
2729 case ICmpInst::ICMP_UGE:
2730 return getFalse(ITy);
2731 case ICmpInst::ICMP_SLT:
2732 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002733 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2734 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002735 if (!KnownNonNegative)
2736 break;
2737 LLVM_FALLTHROUGH;
2738 case ICmpInst::ICMP_NE:
2739 case ICmpInst::ICMP_ULT:
2740 case ICmpInst::ICMP_ULE:
2741 return getTrue(ITy);
2742 }
2743 }
2744
2745 // icmp pred X, (urem Y, X)
2746 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2747 bool KnownNonNegative, KnownNegative;
2748 switch (Pred) {
2749 default:
2750 break;
2751 case ICmpInst::ICMP_SGT:
2752 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002753 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2754 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002755 if (!KnownNonNegative)
2756 break;
2757 LLVM_FALLTHROUGH;
2758 case ICmpInst::ICMP_NE:
2759 case ICmpInst::ICMP_UGT:
2760 case ICmpInst::ICMP_UGE:
2761 return getTrue(ITy);
2762 case ICmpInst::ICMP_SLT:
2763 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002764 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2765 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002766 if (!KnownNonNegative)
2767 break;
2768 LLVM_FALLTHROUGH;
2769 case ICmpInst::ICMP_EQ:
2770 case ICmpInst::ICMP_ULT:
2771 case ICmpInst::ICMP_ULE:
2772 return getFalse(ITy);
2773 }
2774 }
2775
2776 // x >> y <=u x
2777 // x udiv y <=u x.
2778 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2779 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2780 // icmp pred (X op Y), X
2781 if (Pred == ICmpInst::ICMP_UGT)
2782 return getFalse(ITy);
2783 if (Pred == ICmpInst::ICMP_ULE)
2784 return getTrue(ITy);
2785 }
2786
2787 // x >=u x >> y
2788 // x >=u x udiv y.
2789 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2790 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2791 // icmp pred X, (X op Y)
2792 if (Pred == ICmpInst::ICMP_ULT)
2793 return getFalse(ITy);
2794 if (Pred == ICmpInst::ICMP_UGE)
2795 return getTrue(ITy);
2796 }
2797
2798 // handle:
2799 // CI2 << X == CI
2800 // CI2 << X != CI
2801 //
2802 // where CI2 is a power of 2 and CI isn't
2803 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2804 const APInt *CI2Val, *CIVal = &CI->getValue();
2805 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2806 CI2Val->isPowerOf2()) {
2807 if (!CIVal->isPowerOf2()) {
2808 // CI2 << X can equal zero in some circumstances,
2809 // this simplification is unsafe if CI is zero.
2810 //
2811 // We know it is safe if:
2812 // - The shift is nsw, we can't shift out the one bit.
2813 // - The shift is nuw, we can't shift out the one bit.
2814 // - CI2 is one
2815 // - CI isn't zero
2816 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2817 *CI2Val == 1 || !CI->isZero()) {
2818 if (Pred == ICmpInst::ICMP_EQ)
2819 return ConstantInt::getFalse(RHS->getContext());
2820 if (Pred == ICmpInst::ICMP_NE)
2821 return ConstantInt::getTrue(RHS->getContext());
2822 }
2823 }
2824 if (CIVal->isSignBit() && *CI2Val == 1) {
2825 if (Pred == ICmpInst::ICMP_UGT)
2826 return ConstantInt::getFalse(RHS->getContext());
2827 if (Pred == ICmpInst::ICMP_ULE)
2828 return ConstantInt::getTrue(RHS->getContext());
2829 }
2830 }
2831 }
2832
2833 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2834 LBO->getOperand(1) == RBO->getOperand(1)) {
2835 switch (LBO->getOpcode()) {
2836 default:
2837 break;
2838 case Instruction::UDiv:
2839 case Instruction::LShr:
2840 if (ICmpInst::isSigned(Pred))
2841 break;
2842 LLVM_FALLTHROUGH;
2843 case Instruction::SDiv:
2844 case Instruction::AShr:
2845 if (!LBO->isExact() || !RBO->isExact())
2846 break;
2847 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2848 RBO->getOperand(0), Q, MaxRecurse - 1))
2849 return V;
2850 break;
2851 case Instruction::Shl: {
2852 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2853 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2854 if (!NUW && !NSW)
2855 break;
2856 if (!NSW && ICmpInst::isSigned(Pred))
2857 break;
2858 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2859 RBO->getOperand(0), Q, MaxRecurse - 1))
2860 return V;
2861 break;
2862 }
2863 }
2864 }
2865 return nullptr;
2866}
2867
Sanjay Patel35289c62016-12-10 17:40:47 +00002868/// Simplify integer comparisons where at least one operand of the compare
2869/// matches an integer min/max idiom.
2870static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2871 Value *RHS, const Query &Q,
2872 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002873 Type *ITy = GetCompareTy(LHS); // The return type.
2874 Value *A, *B;
2875 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2876 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2877
2878 // Signed variants on "max(a,b)>=a -> true".
2879 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2880 if (A != RHS)
2881 std::swap(A, B); // smax(A, B) pred A.
2882 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2883 // We analyze this as smax(A, B) pred A.
2884 P = Pred;
2885 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2886 (A == LHS || B == LHS)) {
2887 if (A != LHS)
2888 std::swap(A, B); // A pred smax(A, B).
2889 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2890 // We analyze this as smax(A, B) swapped-pred A.
2891 P = CmpInst::getSwappedPredicate(Pred);
2892 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2893 (A == RHS || B == RHS)) {
2894 if (A != RHS)
2895 std::swap(A, B); // smin(A, B) pred A.
2896 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2897 // We analyze this as smax(-A, -B) swapped-pred -A.
2898 // Note that we do not need to actually form -A or -B thanks to EqP.
2899 P = CmpInst::getSwappedPredicate(Pred);
2900 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2901 (A == LHS || B == LHS)) {
2902 if (A != LHS)
2903 std::swap(A, B); // A pred smin(A, B).
2904 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2905 // We analyze this as smax(-A, -B) pred -A.
2906 // Note that we do not need to actually form -A or -B thanks to EqP.
2907 P = Pred;
2908 }
2909 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2910 // Cases correspond to "max(A, B) p A".
2911 switch (P) {
2912 default:
2913 break;
2914 case CmpInst::ICMP_EQ:
2915 case CmpInst::ICMP_SLE:
2916 // Equivalent to "A EqP B". This may be the same as the condition tested
2917 // in the max/min; if so, we can just return that.
2918 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2919 return V;
2920 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2921 return V;
2922 // Otherwise, see if "A EqP B" simplifies.
2923 if (MaxRecurse)
2924 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2925 return V;
2926 break;
2927 case CmpInst::ICMP_NE:
2928 case CmpInst::ICMP_SGT: {
2929 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2930 // Equivalent to "A InvEqP B". This may be the same as the condition
2931 // tested in the max/min; if so, we can just return that.
2932 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2933 return V;
2934 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2935 return V;
2936 // Otherwise, see if "A InvEqP B" simplifies.
2937 if (MaxRecurse)
2938 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2939 return V;
2940 break;
2941 }
2942 case CmpInst::ICMP_SGE:
2943 // Always true.
2944 return getTrue(ITy);
2945 case CmpInst::ICMP_SLT:
2946 // Always false.
2947 return getFalse(ITy);
2948 }
2949 }
2950
2951 // Unsigned variants on "max(a,b)>=a -> true".
2952 P = CmpInst::BAD_ICMP_PREDICATE;
2953 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2954 if (A != RHS)
2955 std::swap(A, B); // umax(A, B) pred A.
2956 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2957 // We analyze this as umax(A, B) pred A.
2958 P = Pred;
2959 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2960 (A == LHS || B == LHS)) {
2961 if (A != LHS)
2962 std::swap(A, B); // A pred umax(A, B).
2963 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2964 // We analyze this as umax(A, B) swapped-pred A.
2965 P = CmpInst::getSwappedPredicate(Pred);
2966 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2967 (A == RHS || B == RHS)) {
2968 if (A != RHS)
2969 std::swap(A, B); // umin(A, B) pred A.
2970 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2971 // We analyze this as umax(-A, -B) swapped-pred -A.
2972 // Note that we do not need to actually form -A or -B thanks to EqP.
2973 P = CmpInst::getSwappedPredicate(Pred);
2974 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2975 (A == LHS || B == LHS)) {
2976 if (A != LHS)
2977 std::swap(A, B); // A pred umin(A, B).
2978 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2979 // We analyze this as umax(-A, -B) pred -A.
2980 // Note that we do not need to actually form -A or -B thanks to EqP.
2981 P = Pred;
2982 }
2983 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2984 // Cases correspond to "max(A, B) p A".
2985 switch (P) {
2986 default:
2987 break;
2988 case CmpInst::ICMP_EQ:
2989 case CmpInst::ICMP_ULE:
2990 // Equivalent to "A EqP B". This may be the same as the condition tested
2991 // in the max/min; if so, we can just return that.
2992 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2993 return V;
2994 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2995 return V;
2996 // Otherwise, see if "A EqP B" simplifies.
2997 if (MaxRecurse)
2998 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2999 return V;
3000 break;
3001 case CmpInst::ICMP_NE:
3002 case CmpInst::ICMP_UGT: {
3003 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3004 // Equivalent to "A InvEqP B". This may be the same as the condition
3005 // tested in the max/min; if so, we can just return that.
3006 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3007 return V;
3008 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3009 return V;
3010 // Otherwise, see if "A InvEqP B" simplifies.
3011 if (MaxRecurse)
3012 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3013 return V;
3014 break;
3015 }
3016 case CmpInst::ICMP_UGE:
3017 // Always true.
3018 return getTrue(ITy);
3019 case CmpInst::ICMP_ULT:
3020 // Always false.
3021 return getFalse(ITy);
3022 }
3023 }
3024
3025 // Variants on "max(x,y) >= min(x,z)".
3026 Value *C, *D;
3027 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3028 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3029 (A == C || A == D || B == C || B == D)) {
3030 // max(x, ?) pred min(x, ?).
3031 if (Pred == CmpInst::ICMP_SGE)
3032 // Always true.
3033 return getTrue(ITy);
3034 if (Pred == CmpInst::ICMP_SLT)
3035 // Always false.
3036 return getFalse(ITy);
3037 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3038 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3039 (A == C || A == D || B == C || B == D)) {
3040 // min(x, ?) pred max(x, ?).
3041 if (Pred == CmpInst::ICMP_SLE)
3042 // Always true.
3043 return getTrue(ITy);
3044 if (Pred == CmpInst::ICMP_SGT)
3045 // Always false.
3046 return getFalse(ITy);
3047 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3048 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3049 (A == C || A == D || B == C || B == D)) {
3050 // max(x, ?) pred min(x, ?).
3051 if (Pred == CmpInst::ICMP_UGE)
3052 // Always true.
3053 return getTrue(ITy);
3054 if (Pred == CmpInst::ICMP_ULT)
3055 // Always false.
3056 return getFalse(ITy);
3057 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3058 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3059 (A == C || A == D || B == C || B == D)) {
3060 // min(x, ?) pred max(x, ?).
3061 if (Pred == CmpInst::ICMP_ULE)
3062 // Always true.
3063 return getTrue(ITy);
3064 if (Pred == CmpInst::ICMP_UGT)
3065 // Always false.
3066 return getFalse(ITy);
3067 }
3068
3069 return nullptr;
3070}
3071
Sanjay Patel472cc782016-01-11 22:14:42 +00003072/// Given operands for an ICmpInst, see if we can fold the result.
3073/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003074static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003075 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003076 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003077 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003078
Chris Lattnera71e9d62009-11-10 00:55:12 +00003079 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003080 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003081 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003082
3083 // If we have a constant, make sure it is on the RHS.
3084 std::swap(LHS, RHS);
3085 Pred = CmpInst::getSwappedPredicate(Pred);
3086 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003087
Chris Lattner229907c2011-07-18 04:54:35 +00003088 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003089
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003090 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003091 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3092 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003093 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003094 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003095
Sanjay Pateldc65a272016-12-03 17:30:22 +00003096 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3097 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003098
Sanjay Pateldc65a272016-12-03 17:30:22 +00003099 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3100 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003101
Sanjay Patel67bde282016-08-22 23:12:02 +00003102 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3103 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003104
Chen Li7452d952015-09-26 03:26:47 +00003105 // If both operands have range metadata, use the metadata
3106 // to simplify the comparison.
3107 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3108 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3109 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3110
3111 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3112 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003113 auto RHS_CR = getConstantRangeFromMetadata(
3114 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3115 auto LHS_CR = getConstantRangeFromMetadata(
3116 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003117
3118 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3119 if (Satisfied_CR.contains(LHS_CR))
3120 return ConstantInt::getTrue(RHS->getContext());
3121
3122 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3123 CmpInst::getInversePredicate(Pred), RHS_CR);
3124 if (InversedSatisfied_CR.contains(LHS_CR))
3125 return ConstantInt::getFalse(RHS->getContext());
3126 }
3127 }
3128
Duncan Sands8fb2c382011-01-20 13:21:55 +00003129 // Compare of cast, for example (zext X) != 0 -> X != 0
3130 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3131 Instruction *LI = cast<CastInst>(LHS);
3132 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003133 Type *SrcTy = SrcOp->getType();
3134 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003135
3136 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3137 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003138 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3139 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003140 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3141 // Transfer the cast to the constant.
3142 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3143 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003144 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003145 return V;
3146 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3147 if (RI->getOperand(0)->getType() == SrcTy)
3148 // Compare without the cast.
3149 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003150 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003151 return V;
3152 }
3153 }
3154
3155 if (isa<ZExtInst>(LHS)) {
3156 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3157 // same type.
3158 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3159 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3160 // Compare X and Y. Note that signed predicates become unsigned.
3161 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003162 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003163 MaxRecurse-1))
3164 return V;
3165 }
3166 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3167 // too. If not, then try to deduce the result of the comparison.
3168 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3169 // Compute the constant that would happen if we truncated to SrcTy then
3170 // reextended to DstTy.
3171 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3172 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3173
3174 // If the re-extended constant didn't change then this is effectively
3175 // also a case of comparing two zero-extended values.
3176 if (RExt == CI && MaxRecurse)
3177 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003178 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003179 return V;
3180
3181 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3182 // there. Use this to work out the result of the comparison.
3183 if (RExt != CI) {
3184 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003185 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003186 // LHS <u RHS.
3187 case ICmpInst::ICMP_EQ:
3188 case ICmpInst::ICMP_UGT:
3189 case ICmpInst::ICMP_UGE:
3190 return ConstantInt::getFalse(CI->getContext());
3191
3192 case ICmpInst::ICMP_NE:
3193 case ICmpInst::ICMP_ULT:
3194 case ICmpInst::ICMP_ULE:
3195 return ConstantInt::getTrue(CI->getContext());
3196
3197 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3198 // is non-negative then LHS <s RHS.
3199 case ICmpInst::ICMP_SGT:
3200 case ICmpInst::ICMP_SGE:
3201 return CI->getValue().isNegative() ?
3202 ConstantInt::getTrue(CI->getContext()) :
3203 ConstantInt::getFalse(CI->getContext());
3204
3205 case ICmpInst::ICMP_SLT:
3206 case ICmpInst::ICMP_SLE:
3207 return CI->getValue().isNegative() ?
3208 ConstantInt::getFalse(CI->getContext()) :
3209 ConstantInt::getTrue(CI->getContext());
3210 }
3211 }
3212 }
3213 }
3214
3215 if (isa<SExtInst>(LHS)) {
3216 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3217 // same type.
3218 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3219 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3220 // Compare X and Y. Note that the predicate does not change.
3221 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003222 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003223 return V;
3224 }
3225 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3226 // too. If not, then try to deduce the result of the comparison.
3227 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3228 // Compute the constant that would happen if we truncated to SrcTy then
3229 // reextended to DstTy.
3230 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3231 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3232
3233 // If the re-extended constant didn't change then this is effectively
3234 // also a case of comparing two sign-extended values.
3235 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003236 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003237 return V;
3238
3239 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3240 // bits there. Use this to work out the result of the comparison.
3241 if (RExt != CI) {
3242 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003243 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003244 case ICmpInst::ICMP_EQ:
3245 return ConstantInt::getFalse(CI->getContext());
3246 case ICmpInst::ICMP_NE:
3247 return ConstantInt::getTrue(CI->getContext());
3248
3249 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3250 // LHS >s RHS.
3251 case ICmpInst::ICMP_SGT:
3252 case ICmpInst::ICMP_SGE:
3253 return CI->getValue().isNegative() ?
3254 ConstantInt::getTrue(CI->getContext()) :
3255 ConstantInt::getFalse(CI->getContext());
3256 case ICmpInst::ICMP_SLT:
3257 case ICmpInst::ICMP_SLE:
3258 return CI->getValue().isNegative() ?
3259 ConstantInt::getFalse(CI->getContext()) :
3260 ConstantInt::getTrue(CI->getContext());
3261
3262 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3263 // LHS >u RHS.
3264 case ICmpInst::ICMP_UGT:
3265 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003266 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003267 if (MaxRecurse)
3268 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3269 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003270 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003271 return V;
3272 break;
3273 case ICmpInst::ICMP_ULT:
3274 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003275 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003276 if (MaxRecurse)
3277 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3278 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003279 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003280 return V;
3281 break;
3282 }
3283 }
3284 }
3285 }
3286 }
3287
James Molloy1d88d6f2015-10-22 13:18:42 +00003288 // icmp eq|ne X, Y -> false|true if X != Y
3289 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003290 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003291 LLVMContext &Ctx = LHS->getType()->getContext();
3292 return Pred == ICmpInst::ICMP_NE ?
3293 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3294 }
Junmo Park53470fc2016-04-05 21:14:31 +00003295
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003296 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3297 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003298
Sanjay Patel35289c62016-12-10 17:40:47 +00003299 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003300 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003301
Chandler Carruth8059c842012-03-25 21:28:14 +00003302 // Simplify comparisons of related pointers using a powerful, recursive
3303 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003304 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003305 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003306 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003307 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3308 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3309 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3310 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3311 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3312 Q.DL.getTypeSizeInBits(CRHS->getType()))
3313 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3314 CLHS->getPointerOperand(),
3315 CRHS->getPointerOperand()))
3316 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003317
Nick Lewycky3db143e2012-02-26 02:09:49 +00003318 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3319 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3320 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3321 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3322 (ICmpInst::isEquality(Pred) ||
3323 (GLHS->isInBounds() && GRHS->isInBounds() &&
3324 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3325 // The bases are equal and the indices are constant. Build a constant
3326 // expression GEP with the same indices and a null base pointer to see
3327 // what constant folding can make out of it.
3328 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3329 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003330 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3331 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003332
3333 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003334 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3335 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003336 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3337 }
3338 }
3339 }
3340
David Majnemer5854e9f2014-11-16 02:20:08 +00003341 // If a bit is known to be zero for A and known to be one for B,
3342 // then A and B cannot be equal.
3343 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003344 const APInt *RHSVal;
3345 if (match(RHS, m_APInt(RHSVal))) {
3346 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003347 APInt LHSKnownZero(BitWidth, 0);
3348 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003349 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003350 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003351 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3352 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3353 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003354 }
3355 }
3356
Duncan Sandsf532d312010-11-07 16:12:23 +00003357 // If the comparison is with the result of a select instruction, check whether
3358 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003359 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003360 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003361 return V;
3362
3363 // If the comparison is with the result of a phi instruction, check whether
3364 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003365 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003366 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003367 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003368
Craig Topper9f008862014-04-15 04:59:12 +00003369 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003370}
3371
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003372Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003373 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003374 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003375 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003376 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003377 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003378 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003379}
3380
Sanjay Patel472cc782016-01-11 22:14:42 +00003381/// Given operands for an FCmpInst, see if we can fold the result.
3382/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003383static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003384 FastMathFlags FMF, const Query &Q,
3385 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003386 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3387 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3388
Chris Lattnera71e9d62009-11-10 00:55:12 +00003389 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003390 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003391 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003392
Chris Lattnera71e9d62009-11-10 00:55:12 +00003393 // If we have a constant, make sure it is on the RHS.
3394 std::swap(LHS, RHS);
3395 Pred = CmpInst::getSwappedPredicate(Pred);
3396 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003397
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003398 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003399 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003400 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003401 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003402 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003403 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003404
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003405 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3406 if (FMF.noNaNs()) {
3407 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003408 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003409 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003410 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003411 }
3412
Mehdi Aminieb242a52015-03-09 03:20:25 +00003413 // fcmp pred x, undef and fcmp pred undef, x
3414 // fold to true if unordered, false if ordered
3415 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3416 // Choosing NaN for the undef will always make unordered comparison succeed
3417 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003418 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003419 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003420
3421 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003422 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003423 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003424 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003425 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003426 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003427 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003428
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003429 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003430 const ConstantFP *CFP = nullptr;
3431 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3432 if (RHS->getType()->isVectorTy())
3433 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3434 else
3435 CFP = dyn_cast<ConstantFP>(RHSC);
3436 }
3437 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003438 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003439 if (CFP->getValueAPF().isNaN()) {
3440 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003441 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003442 assert(FCmpInst::isUnordered(Pred) &&
3443 "Comparison must be either ordered or unordered!");
3444 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003445 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003446 }
3447 // Check whether the constant is an infinity.
3448 if (CFP->getValueAPF().isInfinity()) {
3449 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003450 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003451 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003452 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003453 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003454 case FCmpInst::FCMP_UGE:
3455 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003456 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003457 default:
3458 break;
3459 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003460 } else {
3461 switch (Pred) {
3462 case FCmpInst::FCMP_OGT:
3463 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003464 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003465 case FCmpInst::FCMP_ULE:
3466 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003467 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003468 default:
3469 break;
3470 }
3471 }
3472 }
3473 if (CFP->getValueAPF().isZero()) {
3474 switch (Pred) {
3475 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003476 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003477 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003478 break;
3479 case FCmpInst::FCMP_OLT:
3480 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003481 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003482 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003483 break;
3484 default:
3485 break;
3486 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003487 }
3488 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003489
Duncan Sandsa620bd12010-11-07 16:46:25 +00003490 // If the comparison is with the result of a select instruction, check whether
3491 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003492 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003493 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003494 return V;
3495
3496 // If the comparison is with the result of a phi instruction, check whether
3497 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003498 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003499 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003500 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003501
Craig Topper9f008862014-04-15 04:59:12 +00003502 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003503}
3504
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003505Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003506 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003507 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003508 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003509 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003510 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003511 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003512}
3513
Sanjay Patel472cc782016-01-11 22:14:42 +00003514/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003515static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3516 const Query &Q,
3517 unsigned MaxRecurse) {
3518 // Trivial replacement.
3519 if (V == Op)
3520 return RepOp;
3521
3522 auto *I = dyn_cast<Instruction>(V);
3523 if (!I)
3524 return nullptr;
3525
3526 // If this is a binary operator, try to simplify it with the replaced op.
3527 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3528 // Consider:
3529 // %cmp = icmp eq i32 %x, 2147483647
3530 // %add = add nsw i32 %x, 1
3531 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3532 //
3533 // We can't replace %sel with %add unless we strip away the flags.
3534 if (isa<OverflowingBinaryOperator>(B))
3535 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3536 return nullptr;
3537 if (isa<PossiblyExactOperator>(B))
3538 if (B->isExact())
3539 return nullptr;
3540
3541 if (MaxRecurse) {
3542 if (B->getOperand(0) == Op)
3543 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3544 MaxRecurse - 1);
3545 if (B->getOperand(1) == Op)
3546 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3547 MaxRecurse - 1);
3548 }
3549 }
3550
3551 // Same for CmpInsts.
3552 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3553 if (MaxRecurse) {
3554 if (C->getOperand(0) == Op)
3555 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3556 MaxRecurse - 1);
3557 if (C->getOperand(1) == Op)
3558 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3559 MaxRecurse - 1);
3560 }
3561 }
3562
3563 // TODO: We could hand off more cases to instsimplify here.
3564
3565 // If all operands are constant after substituting Op for RepOp then we can
3566 // constant fold the instruction.
3567 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3568 // Build a list of all constant operands.
3569 SmallVector<Constant *, 8> ConstOps;
3570 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3571 if (I->getOperand(i) == Op)
3572 ConstOps.push_back(CRepOp);
3573 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3574 ConstOps.push_back(COp);
3575 else
3576 break;
3577 }
3578
3579 // All operands were constants, fold it.
3580 if (ConstOps.size() == I->getNumOperands()) {
3581 if (CmpInst *C = dyn_cast<CmpInst>(I))
3582 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3583 ConstOps[1], Q.DL, Q.TLI);
3584
3585 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3586 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003587 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003588
Manuel Jacobe9024592016-01-21 06:33:22 +00003589 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003590 }
3591 }
3592
3593 return nullptr;
3594}
3595
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003596/// Try to simplify a select instruction when its condition operand is an
3597/// integer comparison where one operand of the compare is a constant.
3598static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3599 const APInt *Y, bool TrueWhenUnset) {
3600 const APInt *C;
3601
3602 // (X & Y) == 0 ? X & ~Y : X --> X
3603 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3604 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3605 *Y == ~*C)
3606 return TrueWhenUnset ? FalseVal : TrueVal;
3607
3608 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3609 // (X & Y) != 0 ? X : X & ~Y --> X
3610 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3611 *Y == ~*C)
3612 return TrueWhenUnset ? FalseVal : TrueVal;
3613
3614 if (Y->isPowerOf2()) {
3615 // (X & Y) == 0 ? X | Y : X --> X | Y
3616 // (X & Y) != 0 ? X | Y : X --> X
3617 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3618 *Y == *C)
3619 return TrueWhenUnset ? TrueVal : FalseVal;
3620
3621 // (X & Y) == 0 ? X : X | Y --> X
3622 // (X & Y) != 0 ? X : X | Y --> X | Y
3623 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3624 *Y == *C)
3625 return TrueWhenUnset ? TrueVal : FalseVal;
3626 }
Matt Arsenault82606662017-01-11 00:57:54 +00003627
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003628 return nullptr;
3629}
3630
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003631/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3632/// eq/ne.
3633static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3634 Value *FalseVal,
3635 bool TrueWhenUnset) {
3636 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003637 if (!BitWidth)
3638 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003639
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003640 APInt MinSignedValue;
3641 Value *X;
3642 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3643 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3644 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3645 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3646 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3647 } else {
3648 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3649 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3650 X = CmpLHS;
3651 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3652 }
3653
3654 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3655 TrueWhenUnset))
3656 return V;
3657
3658 return nullptr;
3659}
3660
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003661/// Try to simplify a select instruction when its condition operand is an
3662/// integer comparison.
3663static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3664 Value *FalseVal, const Query &Q,
3665 unsigned MaxRecurse) {
3666 ICmpInst::Predicate Pred;
3667 Value *CmpLHS, *CmpRHS;
3668 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3669 return nullptr;
3670
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003671 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3672 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003673 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3674 Value *X;
3675 const APInt *Y;
3676 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3677 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3678 Pred == ICmpInst::ICMP_EQ))
3679 return V;
3680 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003681 // Comparing signed-less-than 0 checks if the sign bit is set.
3682 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3683 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003684 return V;
3685 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003686 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3687 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3688 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003689 return V;
3690 }
3691
3692 if (CondVal->hasOneUse()) {
3693 const APInt *C;
3694 if (match(CmpRHS, m_APInt(C))) {
3695 // X < MIN ? T : F --> F
3696 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3697 return FalseVal;
3698 // X < MIN ? T : F --> F
3699 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3700 return FalseVal;
3701 // X > MAX ? T : F --> F
3702 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3703 return FalseVal;
3704 // X > MAX ? T : F --> F
3705 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3706 return FalseVal;
3707 }
3708 }
3709
3710 // If we have an equality comparison, then we know the value in one of the
3711 // arms of the select. See if substituting this value into the arm and
3712 // simplifying the result yields the same value as the other arm.
3713 if (Pred == ICmpInst::ICMP_EQ) {
3714 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3715 TrueVal ||
3716 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3717 TrueVal)
3718 return FalseVal;
3719 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3720 FalseVal ||
3721 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3722 FalseVal)
3723 return FalseVal;
3724 } else if (Pred == ICmpInst::ICMP_NE) {
3725 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3726 FalseVal ||
3727 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3728 FalseVal)
3729 return TrueVal;
3730 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3731 TrueVal ||
3732 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3733 TrueVal)
3734 return TrueVal;
3735 }
3736
3737 return nullptr;
3738}
3739
Sanjay Patel472cc782016-01-11 22:14:42 +00003740/// Given operands for a SelectInst, see if we can fold the result.
3741/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003742static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3743 Value *FalseVal, const Query &Q,
3744 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003745 // select true, X, Y -> X
3746 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003747 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3748 if (CB->isAllOnesValue())
3749 return TrueVal;
3750 if (CB->isNullValue())
3751 return FalseVal;
3752 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003753
Chris Lattnerc707fa92010-04-20 05:32:14 +00003754 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003755 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003756 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003757
Chris Lattnerc707fa92010-04-20 05:32:14 +00003758 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3759 if (isa<Constant>(TrueVal))
3760 return TrueVal;
3761 return FalseVal;
3762 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003763 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3764 return FalseVal;
3765 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3766 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003767
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003768 if (Value *V =
3769 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3770 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003771
Craig Topper9f008862014-04-15 04:59:12 +00003772 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003773}
3774
Duncan Sandsb8cee002012-03-13 11:42:19 +00003775Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003776 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003777 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003778 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003779 const Instruction *CxtI) {
3780 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003781 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003782}
3783
Sanjay Patel472cc782016-01-11 22:14:42 +00003784/// Given operands for an GetElementPtrInst, see if we can fold the result.
3785/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003786static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3787 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003788 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003789 unsigned AS =
3790 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003791
Chris Lattner8574aba2009-11-27 00:29:05 +00003792 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003793 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003794 return Ops[0];
3795
Nico Weber48c82402014-08-27 20:06:19 +00003796 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003797 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003798 Type *GEPTy = PointerType::get(LastType, AS);
3799 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3800 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3801
3802 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003803 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003804
Jay Foadb992a632011-07-19 15:07:52 +00003805 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003806 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003807 if (match(Ops[1], m_Zero()))
3808 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003809
David Blaikie4a2e73b2015-04-02 18:55:32 +00003810 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003811 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003812 Value *P;
3813 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003814 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003815 // getelementptr P, N -> P if P points to a type of zero size.
3816 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003817 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003818
3819 // The following transforms are only safe if the ptrtoint cast
3820 // doesn't truncate the pointers.
3821 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003822 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003823 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3824 if (match(P, m_Zero()))
3825 return Constant::getNullValue(GEPTy);
3826 Value *Temp;
3827 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003828 if (Temp->getType() == GEPTy)
3829 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003830 return nullptr;
3831 };
3832
3833 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3834 if (TyAllocSize == 1 &&
3835 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3836 if (Value *R = PtrToIntOrZero(P))
3837 return R;
3838
3839 // getelementptr V, (ashr (sub P, V), C) -> Q
3840 // if P points to a type of size 1 << C.
3841 if (match(Ops[1],
3842 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3843 m_ConstantInt(C))) &&
3844 TyAllocSize == 1ULL << C)
3845 if (Value *R = PtrToIntOrZero(P))
3846 return R;
3847
3848 // getelementptr V, (sdiv (sub P, V), C) -> Q
3849 // if P points to a type of size C.
3850 if (match(Ops[1],
3851 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3852 m_SpecificInt(TyAllocSize))))
3853 if (Value *R = PtrToIntOrZero(P))
3854 return R;
3855 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003856 }
3857 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003858
David Majnemerd1501372016-08-07 07:58:12 +00003859 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3860 all_of(Ops.slice(1).drop_back(1),
3861 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3862 unsigned PtrWidth =
3863 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3864 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3865 APInt BasePtrOffset(PtrWidth, 0);
3866 Value *StrippedBasePtr =
3867 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3868 BasePtrOffset);
3869
David Majnemer5c5df622016-08-16 06:13:46 +00003870 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003871 if (match(Ops.back(),
3872 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3873 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3874 return ConstantExpr::getIntToPtr(CI, GEPTy);
3875 }
David Majnemer5c5df622016-08-16 06:13:46 +00003876 // gep (gep V, C), (xor V, -1) -> C-1
3877 if (match(Ops.back(),
3878 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3879 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3880 return ConstantExpr::getIntToPtr(CI, GEPTy);
3881 }
David Majnemerd1501372016-08-07 07:58:12 +00003882 }
3883 }
3884
Chris Lattner8574aba2009-11-27 00:29:05 +00003885 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003886 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003887 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003888 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003889
David Blaikie4a2e73b2015-04-02 18:55:32 +00003890 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3891 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003892}
3893
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003894Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3895 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003896 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003897 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003898 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003899 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003900 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003901}
3902
Sanjay Patel472cc782016-01-11 22:14:42 +00003903/// Given operands for an InsertValueInst, see if we can fold the result.
3904/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003905static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3906 ArrayRef<unsigned> Idxs, const Query &Q,
3907 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003908 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3909 if (Constant *CVal = dyn_cast<Constant>(Val))
3910 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3911
3912 // insertvalue x, undef, n -> x
3913 if (match(Val, m_Undef()))
3914 return Agg;
3915
3916 // insertvalue x, (extractvalue y, n), n
3917 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003918 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3919 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003920 // insertvalue undef, (extractvalue y, n), n -> y
3921 if (match(Agg, m_Undef()))
3922 return EV->getAggregateOperand();
3923
3924 // insertvalue y, (extractvalue y, n), n -> y
3925 if (Agg == EV->getAggregateOperand())
3926 return Agg;
3927 }
3928
Craig Topper9f008862014-04-15 04:59:12 +00003929 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003930}
3931
Chandler Carruth66b31302015-01-04 12:03:27 +00003932Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003933 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003934 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003935 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003936 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003937 RecursionLimit);
3938}
3939
Sanjay Patel472cc782016-01-11 22:14:42 +00003940/// Given operands for an ExtractValueInst, see if we can fold the result.
3941/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003942static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3943 const Query &, unsigned) {
3944 if (auto *CAgg = dyn_cast<Constant>(Agg))
3945 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3946
3947 // extractvalue x, (insertvalue y, elt, n), n -> elt
3948 unsigned NumIdxs = Idxs.size();
3949 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3950 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3951 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3952 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3953 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3954 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3955 Idxs.slice(0, NumCommonIdxs)) {
3956 if (NumIdxs == NumInsertValueIdxs)
3957 return IVI->getInsertedValueOperand();
3958 break;
3959 }
3960 }
3961
3962 return nullptr;
3963}
3964
3965Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3966 const DataLayout &DL,
3967 const TargetLibraryInfo *TLI,
3968 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003969 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003970 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003971 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003972 RecursionLimit);
3973}
3974
Sanjay Patel472cc782016-01-11 22:14:42 +00003975/// Given operands for an ExtractElementInst, see if we can fold the result.
3976/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003977static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3978 unsigned) {
3979 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3980 if (auto *CIdx = dyn_cast<Constant>(Idx))
3981 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3982
3983 // The index is not relevant if our vector is a splat.
3984 if (auto *Splat = CVec->getSplatValue())
3985 return Splat;
3986
3987 if (isa<UndefValue>(Vec))
3988 return UndefValue::get(Vec->getType()->getVectorElementType());
3989 }
3990
3991 // If extracting a specified index from the vector, see if we can recursively
3992 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003993 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3994 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003995 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003996
3997 return nullptr;
3998}
3999
4000Value *llvm::SimplifyExtractElementInst(
4001 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004002 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4003 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004004 RecursionLimit);
4005}
4006
Sanjay Patel472cc782016-01-11 22:14:42 +00004007/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004008static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004009 // If all of the PHI's incoming values are the same then replace the PHI node
4010 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004011 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004012 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004013 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004014 // If the incoming value is the phi node itself, it can safely be skipped.
4015 if (Incoming == PN) continue;
4016 if (isa<UndefValue>(Incoming)) {
4017 // Remember that we saw an undef value, but otherwise ignore them.
4018 HasUndefInput = true;
4019 continue;
4020 }
4021 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004022 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004023 CommonValue = Incoming;
4024 }
4025
4026 // If CommonValue is null then all of the incoming values were either undef or
4027 // equal to the phi node itself.
4028 if (!CommonValue)
4029 return UndefValue::get(PN->getType());
4030
4031 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4032 // instruction, we cannot return X as the result of the PHI node unless it
4033 // dominates the PHI block.
4034 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004035 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004036
4037 return CommonValue;
4038}
4039
David Majnemer6774d612016-07-26 17:58:05 +00004040static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4041 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004042 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004043 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004044
David Majnemer6774d612016-07-26 17:58:05 +00004045 if (auto *CI = dyn_cast<CastInst>(Op)) {
4046 auto *Src = CI->getOperand(0);
4047 Type *SrcTy = Src->getType();
4048 Type *MidTy = CI->getType();
4049 Type *DstTy = Ty;
4050 if (Src->getType() == Ty) {
4051 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4052 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4053 Type *SrcIntPtrTy =
4054 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4055 Type *MidIntPtrTy =
4056 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4057 Type *DstIntPtrTy =
4058 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4059 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4060 SrcIntPtrTy, MidIntPtrTy,
4061 DstIntPtrTy) == Instruction::BitCast)
4062 return Src;
4063 }
4064 }
David Majnemera90a6212016-07-26 05:52:29 +00004065
4066 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004067 if (CastOpc == Instruction::BitCast)
4068 if (Op->getType() == Ty)
4069 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004070
4071 return nullptr;
4072}
4073
David Majnemer6774d612016-07-26 17:58:05 +00004074Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4075 const DataLayout &DL,
4076 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004077 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004078 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004079 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004080 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004081}
4082
Chris Lattnera71e9d62009-11-10 00:55:12 +00004083//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004084
Sanjay Patel472cc782016-01-11 22:14:42 +00004085/// Given operands for a BinaryOperator, see if we can fold the result.
4086/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004087static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004088 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004089 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004090 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004091 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004092 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004093 case Instruction::FAdd:
4094 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4095
Chris Lattner9e4aa022011-02-09 17:15:04 +00004096 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004097 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004098 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004099 case Instruction::FSub:
4100 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4101
Duncan Sandsb8cee002012-03-13 11:42:19 +00004102 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004103 case Instruction::FMul:
4104 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004105 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4106 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004107 case Instruction::FDiv:
4108 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004109 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4110 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004111 case Instruction::FRem:
4112 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004113 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004114 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004115 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004116 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004117 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004118 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004119 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
4120 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4121 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
4122 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004123 default:
4124 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004125 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4126 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004127
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004128 // If the operation is associative, try some generic simplifications.
4129 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004130 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004131 return V;
4132
Duncan Sandsb8cee002012-03-13 11:42:19 +00004133 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004134 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004135 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004136 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004137 return V;
4138
4139 // If the operation is with the result of a phi instruction, check whether
4140 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004141 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004142 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004143 return V;
4144
Craig Topper9f008862014-04-15 04:59:12 +00004145 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004146 }
4147}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004148
Sanjay Patel472cc782016-01-11 22:14:42 +00004149/// Given operands for a BinaryOperator, see if we can fold the result.
4150/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004151/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4152/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4153static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4154 const FastMathFlags &FMF, const Query &Q,
4155 unsigned MaxRecurse) {
4156 switch (Opcode) {
4157 case Instruction::FAdd:
4158 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4159 case Instruction::FSub:
4160 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4161 case Instruction::FMul:
4162 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004163 case Instruction::FDiv:
4164 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004165 default:
4166 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4167 }
4168}
4169
Duncan Sands7e800d62010-11-14 11:23:23 +00004170Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004171 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004172 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004173 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004174 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004175 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004176}
4177
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004178Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004179 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004180 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004181 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004182 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004183 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004184 RecursionLimit);
4185}
4186
Sanjay Patel472cc782016-01-11 22:14:42 +00004187/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004188static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004189 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004190 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004191 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004192 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004193}
4194
4195Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004196 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004197 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004198 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004199 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004200 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004201}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004202
Michael Ilseman54857292013-02-07 19:26:05 +00004203static bool IsIdempotent(Intrinsic::ID ID) {
4204 switch (ID) {
4205 default: return false;
4206
4207 // Unary idempotent: f(f(x)) = f(x)
4208 case Intrinsic::fabs:
4209 case Intrinsic::floor:
4210 case Intrinsic::ceil:
4211 case Intrinsic::trunc:
4212 case Intrinsic::rint:
4213 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004214 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004215 return true;
4216 }
4217}
4218
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004219static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4220 const DataLayout &DL) {
4221 GlobalValue *PtrSym;
4222 APInt PtrOffset;
4223 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4224 return nullptr;
4225
4226 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4227 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4228 Type *Int32PtrTy = Int32Ty->getPointerTo();
4229 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4230
4231 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4232 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4233 return nullptr;
4234
4235 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4236 if (OffsetInt % 4 != 0)
4237 return nullptr;
4238
4239 Constant *C = ConstantExpr::getGetElementPtr(
4240 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4241 ConstantInt::get(Int64Ty, OffsetInt / 4));
4242 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4243 if (!Loaded)
4244 return nullptr;
4245
4246 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4247 if (!LoadedCE)
4248 return nullptr;
4249
4250 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4251 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4252 if (!LoadedCE)
4253 return nullptr;
4254 }
4255
4256 if (LoadedCE->getOpcode() != Instruction::Sub)
4257 return nullptr;
4258
4259 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4260 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4261 return nullptr;
4262 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4263
4264 Constant *LoadedRHS = LoadedCE->getOperand(1);
4265 GlobalValue *LoadedRHSSym;
4266 APInt LoadedRHSOffset;
4267 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4268 DL) ||
4269 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4270 return nullptr;
4271
4272 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4273}
4274
David Majnemer17a95aa2016-07-14 06:58:37 +00004275static bool maskIsAllZeroOrUndef(Value *Mask) {
4276 auto *ConstMask = dyn_cast<Constant>(Mask);
4277 if (!ConstMask)
4278 return false;
4279 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4280 return true;
4281 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4282 ++I) {
4283 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4284 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4285 continue;
4286 return false;
4287 }
4288 return true;
4289}
4290
Michael Ilseman54857292013-02-07 19:26:05 +00004291template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004292static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004293 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004294 Intrinsic::ID IID = F->getIntrinsicID();
4295 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004296
4297 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004298 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004299 // Perform idempotent optimizations
4300 if (IsIdempotent(IID)) {
4301 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4302 if (II->getIntrinsicID() == IID)
4303 return II;
4304 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004305 }
4306
4307 switch (IID) {
4308 case Intrinsic::fabs: {
4309 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4310 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004311 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004312 }
4313 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004314 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004315 }
4316 }
Michael Ilseman54857292013-02-07 19:26:05 +00004317
Matt Arsenault82606662017-01-11 00:57:54 +00004318 // Binary Ops
4319 if (NumOperands == 2) {
4320 Value *LHS = *ArgBegin;
4321 Value *RHS = *(ArgBegin + 1);
4322 Type *ReturnType = F->getReturnType();
4323
4324 switch (IID) {
4325 case Intrinsic::usub_with_overflow:
4326 case Intrinsic::ssub_with_overflow: {
4327 // X - X -> { 0, false }
4328 if (LHS == RHS)
4329 return Constant::getNullValue(ReturnType);
4330
4331 // X - undef -> undef
4332 // undef - X -> undef
4333 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4334 return UndefValue::get(ReturnType);
4335
4336 return nullptr;
4337 }
4338 case Intrinsic::uadd_with_overflow:
4339 case Intrinsic::sadd_with_overflow: {
4340 // X + undef -> undef
4341 if (isa<UndefValue>(RHS))
4342 return UndefValue::get(ReturnType);
4343
4344 return nullptr;
4345 }
4346 case Intrinsic::umul_with_overflow:
4347 case Intrinsic::smul_with_overflow: {
4348 // X * 0 -> { 0, false }
4349 if (match(RHS, m_Zero()))
4350 return Constant::getNullValue(ReturnType);
4351
4352 // X * undef -> { 0, false }
4353 if (match(RHS, m_Undef()))
4354 return Constant::getNullValue(ReturnType);
4355
4356 return nullptr;
4357 }
4358 case Intrinsic::load_relative: {
4359 Constant *C0 = dyn_cast<Constant>(LHS);
4360 Constant *C1 = dyn_cast<Constant>(RHS);
4361 if (C0 && C1)
4362 return SimplifyRelativeLoad(C0, C1, Q.DL);
4363 return nullptr;
4364 }
4365 default:
4366 return nullptr;
4367 }
4368 }
4369
4370 // Simplify calls to llvm.masked.load.*
4371 switch (IID) {
4372 case Intrinsic::masked_load: {
4373 Value *MaskArg = ArgBegin[2];
4374 Value *PassthruArg = ArgBegin[3];
4375 // If the mask is all zeros or undef, the "passthru" argument is the result.
4376 if (maskIsAllZeroOrUndef(MaskArg))
4377 return PassthruArg;
4378 return nullptr;
4379 }
4380 default:
4381 return nullptr;
4382 }
Michael Ilseman54857292013-02-07 19:26:05 +00004383}
4384
Chandler Carruth9dc35582012-12-28 11:30:55 +00004385template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004386static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004387 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004388 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004389 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4390 Ty = PTy->getElementType();
4391 FunctionType *FTy = cast<FunctionType>(Ty);
4392
Dan Gohman85977e62011-11-04 18:32:42 +00004393 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004394 // call null -> undef
4395 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004396 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004397
Chandler Carruthf6182152012-12-28 14:23:29 +00004398 Function *F = dyn_cast<Function>(V);
4399 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004400 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004401
David Majnemer15032582015-05-22 03:56:46 +00004402 if (F->isIntrinsic())
4403 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004404 return Ret;
4405
Chandler Carruthf6182152012-12-28 14:23:29 +00004406 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004407 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004408
4409 SmallVector<Constant *, 4> ConstantArgs;
4410 ConstantArgs.reserve(ArgEnd - ArgBegin);
4411 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4412 Constant *C = dyn_cast<Constant>(*I);
4413 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004414 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004415 ConstantArgs.push_back(C);
4416 }
4417
4418 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004419}
4420
Chandler Carruthf6182152012-12-28 14:23:29 +00004421Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004422 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004423 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004424 AssumptionCache *AC, const Instruction *CxtI) {
4425 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004426 RecursionLimit);
4427}
4428
Chandler Carruthf6182152012-12-28 14:23:29 +00004429Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004430 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004431 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004432 const Instruction *CxtI) {
4433 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004434 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004435}
4436
Sanjay Patel472cc782016-01-11 22:14:42 +00004437/// See if we can compute a simplified version of this instruction.
4438/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004439Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004440 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004441 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004442 Value *Result;
4443
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004444 switch (I->getOpcode()) {
4445 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004446 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004447 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004448 case Instruction::FAdd:
4449 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004450 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004451 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004452 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004453 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4454 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004455 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004456 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004457 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004458 case Instruction::FSub:
4459 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004460 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004461 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004462 case Instruction::Sub:
4463 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4464 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004465 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004466 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004467 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004468 case Instruction::FMul:
4469 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004470 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004471 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004472 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004473 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004474 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004475 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004476 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004477 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004478 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004479 break;
4480 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004481 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004482 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004483 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004484 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004485 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004486 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004487 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004488 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004489 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004490 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004491 break;
4492 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004493 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004494 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004495 break;
4496 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004497 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004498 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004499 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004500 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004501 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4502 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004503 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004504 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004505 break;
4506 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004507 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004508 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004509 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004510 break;
4511 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004512 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004513 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004514 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004515 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004516 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004517 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004518 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004519 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004520 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004521 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004522 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004523 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004524 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004525 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004526 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004527 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004528 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004529 Result =
4530 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004531 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004532 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004533 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004534 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4535 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004536 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004537 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004538 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004539 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004540 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004541 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004542 case Instruction::GetElementPtr: {
4543 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004544 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004545 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004546 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004547 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004548 case Instruction::InsertValue: {
4549 InsertValueInst *IV = cast<InsertValueInst>(I);
4550 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4551 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004552 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004553 break;
4554 }
David Majnemer25a796e2015-07-13 01:15:46 +00004555 case Instruction::ExtractValue: {
4556 auto *EVI = cast<ExtractValueInst>(I);
4557 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004558 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004559 break;
4560 }
David Majnemer599ca442015-07-13 01:15:53 +00004561 case Instruction::ExtractElement: {
4562 auto *EEI = cast<ExtractElementInst>(I);
4563 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004564 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004565 break;
4566 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004567 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004568 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004569 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004570 case Instruction::Call: {
4571 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004572 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004573 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004574 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004575 }
David Majnemer6774d612016-07-26 17:58:05 +00004576#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4577#include "llvm/IR/Instruction.def"
4578#undef HANDLE_CAST_INST
4579 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004580 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004581 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004582 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004583
Hal Finkelf2199b22015-10-23 20:37:08 +00004584 // In general, it is possible for computeKnownBits to determine all bits in a
4585 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004586 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004587 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4588 APInt KnownZero(BitWidth, 0);
4589 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004590 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
Hal Finkelf2199b22015-10-23 20:37:08 +00004591 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004592 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004593 }
4594
Duncan Sands64e41cf2010-11-17 08:35:29 +00004595 /// If called on unreachable code, the above logic may report that the
4596 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004597 /// detecting that case here, returning a safe value instead.
4598 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004599}
4600
Sanjay Patelf44bd382016-01-20 18:59:48 +00004601/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004602/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004603///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004604/// This is the common implementation of the recursive simplification routines.
4605/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4606/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4607/// instructions to process and attempt to simplify it using
4608/// InstructionSimplify.
4609///
4610/// This routine returns 'true' only when *it* simplifies something. The passed
4611/// in simplified value does not count toward this.
4612static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004613 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004614 const DominatorTree *DT,
4615 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004616 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004617 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004618 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004619
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004620 // If we have an explicit value to collapse to, do that round of the
4621 // simplification loop by hand initially.
4622 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004623 for (User *U : I->users())
4624 if (U != I)
4625 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004626
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004627 // Replace the instruction with its simplified value.
4628 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004629
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004630 // Gracefully handle edge cases where the instruction is not wired into any
4631 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004632 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4633 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004634 I->eraseFromParent();
4635 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004636 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004637 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004638
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004639 // Note that we must test the size on each iteration, the worklist can grow.
4640 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4641 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004642
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004643 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004644 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004645 if (!SimpleV)
4646 continue;
4647
4648 Simplified = true;
4649
4650 // Stash away all the uses of the old instruction so we can check them for
4651 // recursive simplifications after a RAUW. This is cheaper than checking all
4652 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004653 for (User *U : I->users())
4654 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004655
4656 // Replace the instruction with its simplified value.
4657 I->replaceAllUsesWith(SimpleV);
4658
4659 // Gracefully handle edge cases where the instruction is not wired into any
4660 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004661 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4662 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004663 I->eraseFromParent();
4664 }
4665 return Simplified;
4666}
4667
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004668bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004669 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004670 const DominatorTree *DT,
4671 AssumptionCache *AC) {
4672 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004673}
4674
4675bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004676 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004677 const DominatorTree *DT,
4678 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004679 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4680 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004681 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004682}