blob: 039d8286ecb803a01b904da17df48324a89772d7 [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"
Chris Lattner084a1b52009-11-09 22:57:59 +000023#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000036
Chandler Carruthf1221bd2014-04-22 02:48:03 +000037#define DEBUG_TYPE "instsimplify"
38
Chris Lattner9e4aa022011-02-09 17:15:04 +000039enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000040
Duncan Sands3547d2e2010-12-22 09:40:51 +000041STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000042STATISTIC(NumReassoc, "Number of reassociations");
43
Benjamin Kramercfd8d902014-09-12 08:56:53 +000044namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000045struct Query {
Rafael Espindola37dc9e12014-02-21 00:06:31 +000046 const DataLayout *DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000047 const TargetLibraryInfo *TLI;
48 const DominatorTree *DT;
Hal Finkel60db0582014-09-07 18:57:58 +000049 AssumptionTracker *AT;
50 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000051
Rafael Espindola37dc9e12014-02-21 00:06:31 +000052 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
Hal Finkel60db0582014-09-07 18:57:58 +000053 const DominatorTree *dt, AssumptionTracker *at = nullptr,
54 const Instruction *cxti = nullptr)
55 : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000056};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000057} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000058
59static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
60static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000061 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000062static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000063 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000064static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
65static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000066static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000067
Duncan Sandsc1c92712011-07-26 15:03:53 +000068/// getFalse - For a boolean type, or a vector of boolean type, return false, or
69/// a vector with every element false, as appropriate for the type.
70static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000071 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000072 "Expected i1 type or a vector of i1!");
73 return Constant::getNullValue(Ty);
74}
75
76/// getTrue - For a boolean type, or a vector of boolean type, return true, or
77/// a vector with every element true, as appropriate for the type.
78static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000079 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000080 "Expected i1 type or a vector of i1!");
81 return Constant::getAllOnesValue(Ty);
82}
83
Duncan Sands3d5692a2011-10-30 19:56:36 +000084/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
85static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
86 Value *RHS) {
87 CmpInst *Cmp = dyn_cast<CmpInst>(V);
88 if (!Cmp)
89 return false;
90 CmpInst::Predicate CPred = Cmp->getPredicate();
91 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
92 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
93 return true;
94 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
95 CRHS == LHS;
96}
97
Duncan Sands5ffc2982010-11-16 12:16:38 +000098/// ValueDominatesPHI - Does the given value dominate the specified phi node?
99static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
100 Instruction *I = dyn_cast<Instruction>(V);
101 if (!I)
102 // Arguments and constants dominate all instructions.
103 return true;
104
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000105 // If we are processing instructions (and/or basic blocks) that have not been
106 // fully added to a function, the parent nodes may still be null. Simply
107 // return the conservative answer in these cases.
108 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
109 return false;
110
Duncan Sands5ffc2982010-11-16 12:16:38 +0000111 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000112 if (DT) {
113 if (!DT->isReachableFromEntry(P->getParent()))
114 return true;
115 if (!DT->isReachableFromEntry(I->getParent()))
116 return false;
117 return DT->dominates(I, P);
118 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000119
120 // Otherwise, if the instruction is in the entry block, and is not an invoke,
121 // then it obviously dominates all phi nodes.
122 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
123 !isa<InvokeInst>(I))
124 return true;
125
126 return false;
127}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000128
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000129/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
130/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
131/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
132/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
133/// Returns the simplified value, or null if no simplification was performed.
134static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000135 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000136 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000137 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000138 // Recursion is always used, so bail out at once if we already hit the limit.
139 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000140 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000141
142 // Check whether the expression has the form "(A op' B) op C".
143 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
144 if (Op0->getOpcode() == OpcodeToExpand) {
145 // It does! Try turning it into "(A op C) op' (B op C)".
146 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
147 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000148 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
149 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000150 // They do! Return "L op' R" if it simplifies or is already available.
151 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000152 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
153 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000154 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000155 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000156 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000157 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000158 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000159 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000160 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000161 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000162 }
163 }
164
165 // Check whether the expression has the form "A op (B op' C)".
166 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
167 if (Op1->getOpcode() == OpcodeToExpand) {
168 // It does! Try turning it into "(A op B) op' (A op C)".
169 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
170 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000171 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
172 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000173 // They do! Return "L op' R" if it simplifies or is already available.
174 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000175 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
176 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000177 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000178 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000179 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000180 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000181 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000182 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000184 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000185 }
186 }
187
Craig Topper9f008862014-04-15 04:59:12 +0000188 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189}
190
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000191/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
192/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000193static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000194 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000195 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000196 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
197
198 // Recursion is always used, so bail out at once if we already hit the limit.
199 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000200 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000201
202 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
203 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
204
205 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
206 if (Op0 && Op0->getOpcode() == Opcode) {
207 Value *A = Op0->getOperand(0);
208 Value *B = Op0->getOperand(1);
209 Value *C = RHS;
210
211 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000212 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000213 // It does! Return "A op V" if it simplifies or is already available.
214 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000215 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000216 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000217 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000218 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000219 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000220 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000221 }
222 }
223
224 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
225 if (Op1 && Op1->getOpcode() == Opcode) {
226 Value *A = LHS;
227 Value *B = Op1->getOperand(0);
228 Value *C = Op1->getOperand(1);
229
230 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000231 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000232 // It does! Return "V op C" if it simplifies or is already available.
233 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000234 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000235 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000236 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000237 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000238 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000239 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000240 }
241 }
242
243 // The remaining transforms require commutativity as well as associativity.
244 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000245 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000246
247 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
248 if (Op0 && Op0->getOpcode() == Opcode) {
249 Value *A = Op0->getOperand(0);
250 Value *B = Op0->getOperand(1);
251 Value *C = RHS;
252
253 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000254 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000255 // It does! Return "V op B" if it simplifies or is already available.
256 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000257 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000258 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000259 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000260 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000261 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000262 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000263 }
264 }
265
266 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
267 if (Op1 && Op1->getOpcode() == Opcode) {
268 Value *A = LHS;
269 Value *B = Op1->getOperand(0);
270 Value *C = Op1->getOperand(1);
271
272 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000273 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000274 // It does! Return "B op V" if it simplifies or is already available.
275 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000276 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000277 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000278 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000279 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000281 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000282 }
283 }
284
Craig Topper9f008862014-04-15 04:59:12 +0000285 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286}
287
Duncan Sandsb0579e92010-11-10 13:00:08 +0000288/// ThreadBinOpOverSelect - In the case of a binary operation with a select
289/// instruction as an operand, try to simplify the binop by seeing whether
290/// evaluating it on both branches of the select results in the same value.
291/// Returns the common value if so, otherwise returns null.
292static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000293 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000294 // Recursion is always used, so bail out at once if we already hit the limit.
295 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000296 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000297
Duncan Sandsb0579e92010-11-10 13:00:08 +0000298 SelectInst *SI;
299 if (isa<SelectInst>(LHS)) {
300 SI = cast<SelectInst>(LHS);
301 } else {
302 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
303 SI = cast<SelectInst>(RHS);
304 }
305
306 // Evaluate the BinOp on the true and false branches of the select.
307 Value *TV;
308 Value *FV;
309 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000310 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
311 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000312 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000313 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
314 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000315 }
316
Duncan Sandse3c53952011-01-01 16:12:09 +0000317 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000318 // If they both failed to simplify then return null.
319 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000320 return TV;
321
322 // If one branch simplified to undef, return the other one.
323 if (TV && isa<UndefValue>(TV))
324 return FV;
325 if (FV && isa<UndefValue>(FV))
326 return TV;
327
328 // If applying the operation did not change the true and false select values,
329 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000330 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000331 return SI;
332
333 // If one branch simplified and the other did not, and the simplified
334 // value is equal to the unsimplified one, return the simplified value.
335 // For example, select (cond, X, X & Z) & Z -> X & Z.
336 if ((FV && !TV) || (TV && !FV)) {
337 // Check that the simplified value has the form "X op Y" where "op" is the
338 // same as the original operation.
339 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
340 if (Simplified && Simplified->getOpcode() == Opcode) {
341 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
342 // We already know that "op" is the same as for the simplified value. See
343 // if the operands match too. If so, return the simplified value.
344 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
345 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
346 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000347 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
348 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000349 return Simplified;
350 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000351 Simplified->getOperand(1) == UnsimplifiedLHS &&
352 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000353 return Simplified;
354 }
355 }
356
Craig Topper9f008862014-04-15 04:59:12 +0000357 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000358}
359
360/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
361/// try to simplify the comparison by seeing whether both branches of the select
362/// result in the same value. Returns the common value if so, otherwise returns
363/// null.
364static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000365 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000366 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000367 // Recursion is always used, so bail out at once if we already hit the limit.
368 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000369 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000370
Duncan Sandsb0579e92010-11-10 13:00:08 +0000371 // Make sure the select is on the LHS.
372 if (!isa<SelectInst>(LHS)) {
373 std::swap(LHS, RHS);
374 Pred = CmpInst::getSwappedPredicate(Pred);
375 }
376 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
377 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000378 Value *Cond = SI->getCondition();
379 Value *TV = SI->getTrueValue();
380 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000381
Duncan Sands06504022011-02-03 09:37:39 +0000382 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000383 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000384 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000385 if (TCmp == Cond) {
386 // It not only simplified, it simplified to the select condition. Replace
387 // it with 'true'.
388 TCmp = getTrue(Cond->getType());
389 } else if (!TCmp) {
390 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
391 // condition then we can replace it with 'true'. Otherwise give up.
392 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000393 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000394 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000395 }
396
Duncan Sands3d5692a2011-10-30 19:56:36 +0000397 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000398 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 if (FCmp == Cond) {
400 // It not only simplified, it simplified to the select condition. Replace
401 // it with 'false'.
402 FCmp = getFalse(Cond->getType());
403 } else if (!FCmp) {
404 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
405 // condition then we can replace it with 'false'. Otherwise give up.
406 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000407 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000408 FCmp = getFalse(Cond->getType());
409 }
410
411 // If both sides simplified to the same value, then use it as the result of
412 // the original comparison.
413 if (TCmp == FCmp)
414 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000415
416 // The remaining cases only make sense if the select condition has the same
417 // type as the result of the comparison, so bail out if this is not so.
418 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000419 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000420 // If the false value simplified to false, then the result of the compare
421 // is equal to "Cond && TCmp". This also catches the case when the false
422 // value simplified to false and the true value to true, returning "Cond".
423 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000424 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000425 return V;
426 // If the true value simplified to true, then the result of the compare
427 // is equal to "Cond || FCmp".
428 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000429 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000430 return V;
431 // Finally, if the false value simplified to true and the true value to
432 // false, then the result of the compare is equal to "!Cond".
433 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
434 if (Value *V =
435 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000436 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000437 return V;
438
Craig Topper9f008862014-04-15 04:59:12 +0000439 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000440}
441
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000442/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
443/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
444/// it on the incoming phi values yields the same result for every value. If so
445/// returns the common value, otherwise returns null.
446static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000447 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000448 // Recursion is always used, so bail out at once if we already hit the limit.
449 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000450 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000451
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000452 PHINode *PI;
453 if (isa<PHINode>(LHS)) {
454 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000455 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000456 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000457 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000458 } else {
459 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
460 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000461 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000462 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000463 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000464 }
465
466 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000467 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000468 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000469 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000470 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000471 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000472 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000473 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
474 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000475 // If the operation failed to simplify, or simplified to a different value
476 // to previously, then give up.
477 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000478 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000479 CommonValue = V;
480 }
481
482 return CommonValue;
483}
484
485/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
486/// try to simplify the comparison by seeing whether comparing with all of the
487/// incoming phi values yields the same result every time. If so returns the
488/// common result, otherwise returns null.
489static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000490 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000491 // Recursion is always used, so bail out at once if we already hit the limit.
492 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000493 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000494
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000495 // Make sure the phi is on the LHS.
496 if (!isa<PHINode>(LHS)) {
497 std::swap(LHS, RHS);
498 Pred = CmpInst::getSwappedPredicate(Pred);
499 }
500 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
501 PHINode *PI = cast<PHINode>(LHS);
502
Duncan Sands5ffc2982010-11-16 12:16:38 +0000503 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000504 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000505 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000506
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000507 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000508 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000509 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000510 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000511 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000512 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000513 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000514 // If the operation failed to simplify, or simplified to a different value
515 // to previously, then give up.
516 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000517 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000518 CommonValue = V;
519 }
520
521 return CommonValue;
522}
523
Chris Lattner3d9823b2009-11-27 17:42:22 +0000524/// SimplifyAddInst - Given operands for an Add, see if we can
525/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000526static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000527 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000528 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
529 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
530 Constant *Ops[] = { CLHS, CRHS };
Duncan Sandsb8cee002012-03-13 11:42:19 +0000531 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000532 Q.DL, Q.TLI);
Chris Lattner3d9823b2009-11-27 17:42:22 +0000533 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000534
Chris Lattner3d9823b2009-11-27 17:42:22 +0000535 // Canonicalize the constant to the RHS.
536 std::swap(Op0, Op1);
537 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000540 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000541 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + 0 -> X
544 if (match(Op1, m_Zero()))
545 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + (Y - X) -> Y
548 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000549 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000550 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000553 return Y;
554
555 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000556 if (match(Op0, m_Not(m_Specific(Op1))) ||
557 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000558 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000559
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000560 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000561 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000562 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000563 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000564
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000565 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000566 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000567 MaxRecurse))
568 return V;
569
Duncan Sandsb238de02010-11-19 09:20:39 +0000570 // Threading Add over selects and phi nodes is pointless, so don't bother.
571 // Threading over the select in "A + select(cond, B, C)" means evaluating
572 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573 // only if B and C are equal. If B and C are equal then (since we assume
574 // that operands have already been simplified) "select(cond, B, C)" should
575 // have been simplified to the common value of B and C already. Analysing
576 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
577 // for threading over phi nodes.
578
Craig Topper9f008862014-04-15 04:59:12 +0000579 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000580}
581
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000582Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000583 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000584 const DominatorTree *DT, AssumptionTracker *AT,
585 const Instruction *CxtI) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
587 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000588}
589
Chandler Carrutha0796552012-03-12 11:19:31 +0000590/// \brief Compute the base pointer and cumulative constant offsets for V.
591///
592/// This strips all constant offsets off of V, leaving it the base pointer, and
593/// accumulates the total constant offset applied in the returned constant. It
594/// returns 0 if V is not a pointer, and returns the constant '0' if there are
595/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000596///
597/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599/// folding.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000600static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000601 Value *&V,
602 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000603 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000604
Dan Gohman18c77a12013-01-31 02:50:36 +0000605 // Without DataLayout, just be conservative for now. Theoretically, more could
606 // be done in this case.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000607 if (!DL)
Dan Gohman18c77a12013-01-31 02:50:36 +0000608 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
609
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000610 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000611 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000612
613 // Even though we don't look through PHI nodes, we could be called on an
614 // instruction in an unreachable block, which may be on a cycle.
615 SmallPtrSet<Value *, 4> Visited;
616 Visited.insert(V);
617 do {
618 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000619 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000620 !GEP->accumulateConstantOffset(*DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000621 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 V = GEP->getPointerOperand();
623 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000624 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000625 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
626 if (GA->mayBeOverridden())
627 break;
628 V = GA->getAliasee();
629 } else {
630 break;
631 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000632 assert(V->getType()->getScalarType()->isPointerTy() &&
633 "Unexpected operand type!");
Chandler Carrutha0796552012-03-12 11:19:31 +0000634 } while (Visited.insert(V));
635
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000636 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637 if (V->getType()->isVectorTy())
638 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
639 OffsetIntPtr);
640 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000641}
642
643/// \brief Compute the constant difference between two pointer values.
644/// If the difference is not a constant, returns zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000645static Constant *computePointerDifference(const DataLayout *DL,
Chandler Carrutha0796552012-03-12 11:19:31 +0000646 Value *LHS, Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000647 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000649
650 // If LHS and RHS are not related via constant offsets to the same base
651 // value, there is nothing we can do here.
652 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000653 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000654
655 // Otherwise, the difference of LHS - RHS can be computed as:
656 // LHS - RHS
657 // = (LHSOffset + Base) - (RHSOffset + Base)
658 // = LHSOffset - RHSOffset
659 return ConstantExpr::getSub(LHSOffset, RHSOffset);
660}
661
Duncan Sands0a2c41682010-12-15 14:07:39 +0000662/// SimplifySubInst - Given operands for a Sub, see if we can
663/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000664static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000665 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000666 if (Constant *CLHS = dyn_cast<Constant>(Op0))
667 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
668 Constant *Ops[] = { CLHS, CRHS };
669 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000670 Ops, Q.DL, Q.TLI);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000671 }
672
673 // X - undef -> undef
674 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000675 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000676 return UndefValue::get(Op0->getType());
677
678 // X - 0 -> X
679 if (match(Op1, m_Zero()))
680 return Op0;
681
682 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000683 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000684 return Constant::getNullValue(Op0->getType());
685
David Majnemercd4fbcd2014-07-31 04:49:18 +0000686 // X - (0 - Y) -> X if the second sub is NUW.
687 // If Y != 0, 0 - Y is a poison value.
688 // If Y == 0, 0 - Y simplifies to 0.
689 if (BinaryOperator::isNeg(Op1)) {
690 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
691 assert(BO->getOpcode() == Instruction::Sub &&
692 "Expected a subtraction operator!");
693 if (BO->hasNoUnsignedWrap())
694 return Op0;
695 }
696 }
697
Duncan Sands99589d02011-01-18 11:50:19 +0000698 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
699 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000700 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000701 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
702 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000703 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000704 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000705 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000706 // It does, we successfully reassociated!
707 ++NumReassoc;
708 return W;
709 }
710 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000711 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000712 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000713 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000714 // It does, we successfully reassociated!
715 ++NumReassoc;
716 return W;
717 }
718 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000719
Duncan Sands99589d02011-01-18 11:50:19 +0000720 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
721 // For example, X - (X + 1) -> -1
722 X = Op0;
723 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
724 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000725 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000726 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000727 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000728 // It does, we successfully reassociated!
729 ++NumReassoc;
730 return W;
731 }
732 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000733 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000734 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000736 // It does, we successfully reassociated!
737 ++NumReassoc;
738 return W;
739 }
740 }
741
742 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
743 // For example, X - (X - Y) -> Y.
744 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000745 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
746 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000747 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000748 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000749 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000750 // It does, we successfully reassociated!
751 ++NumReassoc;
752 return W;
753 }
754
Duncan Sands395ac42d2012-03-13 14:07:05 +0000755 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
756 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
757 match(Op1, m_Trunc(m_Value(Y))))
758 if (X->getType() == Y->getType())
759 // See if "V === X - Y" simplifies.
760 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
761 // It does! Now see if "trunc V" simplifies.
762 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
763 // It does, return the simplified "trunc V".
764 return W;
765
766 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000767 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000768 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000769 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000770 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
771
Duncan Sands99589d02011-01-18 11:50:19 +0000772 // i1 sub -> xor.
773 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000774 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000775 return V;
776
Duncan Sands0a2c41682010-12-15 14:07:39 +0000777 // Threading Sub over selects and phi nodes is pointless, so don't bother.
778 // Threading over the select in "A - select(cond, B, C)" means evaluating
779 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
780 // only if B and C are equal. If B and C are equal then (since we assume
781 // that operands have already been simplified) "select(cond, B, C)" should
782 // have been simplified to the common value of B and C already. Analysing
783 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
784 // for threading over phi nodes.
785
Craig Topper9f008862014-04-15 04:59:12 +0000786 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000787}
788
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000789Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000790 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000791 const DominatorTree *DT, AssumptionTracker *AT,
792 const Instruction *CxtI) {
793 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
794 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000795}
796
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000797/// Given operands for an FAdd, see if we can fold the result. If not, this
798/// returns null.
799static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
800 const Query &Q, unsigned MaxRecurse) {
801 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
802 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
803 Constant *Ops[] = { CLHS, CRHS };
804 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000805 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000806 }
807
808 // Canonicalize the constant to the RHS.
809 std::swap(Op0, Op1);
810 }
811
812 // fadd X, -0 ==> X
813 if (match(Op1, m_NegZero()))
814 return Op0;
815
816 // fadd X, 0 ==> X, when we know X is not -0
817 if (match(Op1, m_Zero()) &&
818 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
819 return Op0;
820
821 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
822 // where nnan and ninf have to occur at least once somewhere in this
823 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000824 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000825 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
826 SubOp = Op1;
827 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
828 SubOp = Op0;
829 if (SubOp) {
830 Instruction *FSub = cast<Instruction>(SubOp);
831 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
832 (FMF.noInfs() || FSub->hasNoInfs()))
833 return Constant::getNullValue(Op0->getType());
834 }
835
Craig Topper9f008862014-04-15 04:59:12 +0000836 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000837}
838
839/// Given operands for an FSub, see if we can fold the result. If not, this
840/// returns null.
841static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
842 const Query &Q, unsigned MaxRecurse) {
843 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
844 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
845 Constant *Ops[] = { CLHS, CRHS };
846 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000847 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000848 }
849 }
850
851 // fsub X, 0 ==> X
852 if (match(Op1, m_Zero()))
853 return Op0;
854
855 // fsub X, -0 ==> X, when we know X is not -0
856 if (match(Op1, m_NegZero()) &&
857 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
858 return Op0;
859
860 // fsub 0, (fsub -0.0, X) ==> X
861 Value *X;
862 if (match(Op0, m_AnyZero())) {
863 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
864 return X;
865 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
866 return X;
867 }
868
869 // fsub nnan ninf x, x ==> 0.0
870 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
871 return Constant::getNullValue(Op0->getType());
872
Craig Topper9f008862014-04-15 04:59:12 +0000873 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000874}
875
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000876/// Given the operands for an FMul, see if we can fold the result
877static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
878 FastMathFlags FMF,
879 const Query &Q,
880 unsigned MaxRecurse) {
881 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
882 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
883 Constant *Ops[] = { CLHS, CRHS };
884 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000885 Ops, Q.DL, Q.TLI);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000886 }
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000887
888 // Canonicalize the constant to the RHS.
889 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000890 }
891
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000892 // fmul X, 1.0 ==> X
893 if (match(Op1, m_FPOne()))
894 return Op0;
895
896 // fmul nnan nsz X, 0 ==> 0
897 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
898 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000899
Craig Topper9f008862014-04-15 04:59:12 +0000900 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000901}
902
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000903/// SimplifyMulInst - Given operands for a Mul, see if we can
904/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000905static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
906 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000907 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
908 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
909 Constant *Ops[] = { CLHS, CRHS };
910 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000911 Ops, Q.DL, Q.TLI);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000912 }
913
914 // Canonicalize the constant to the RHS.
915 std::swap(Op0, Op1);
916 }
917
918 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000919 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000920 return Constant::getNullValue(Op0->getType());
921
922 // X * 0 -> 0
923 if (match(Op1, m_Zero()))
924 return Op1;
925
926 // X * 1 -> X
927 if (match(Op1, m_One()))
928 return Op0;
929
Duncan Sandsb67edc62011-01-30 18:03:50 +0000930 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000931 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000932 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
933 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
934 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000935
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000936 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000937 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000938 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000939 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000940
941 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000942 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000943 MaxRecurse))
944 return V;
945
946 // Mul distributes over Add. Try some generic simplifications based on this.
947 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000948 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000949 return V;
950
951 // If the operation is with the result of a select instruction, check whether
952 // operating on either branch of the select always yields the same value.
953 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000954 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000955 MaxRecurse))
956 return V;
957
958 // If the operation is with the result of a phi instruction, check whether
959 // operating on all incoming values of the phi always yields the same value.
960 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000961 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000962 MaxRecurse))
963 return V;
964
Craig Topper9f008862014-04-15 04:59:12 +0000965 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000966}
967
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000968Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000969 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000970 const DominatorTree *DT, AssumptionTracker *AT,
971 const Instruction *CxtI) {
972 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
973 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000974}
975
976Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000977 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000978 const DominatorTree *DT, AssumptionTracker *AT,
979 const Instruction *CxtI) {
980 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
981 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000982}
983
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000984Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
985 FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000986 const DataLayout *DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000987 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000988 const DominatorTree *DT,
989 AssumptionTracker *AT,
990 const Instruction *CxtI) {
991 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
992 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000993}
994
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000995Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000996 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +0000997 const DominatorTree *DT, AssumptionTracker *AT,
998 const Instruction *CxtI) {
999 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1000 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001001}
1002
Duncan Sands771e82a2011-01-28 16:51:11 +00001003/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1004/// fold the result. If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001005static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001006 const Query &Q, unsigned MaxRecurse) {
Duncan Sands771e82a2011-01-28 16:51:11 +00001007 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1008 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1009 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001010 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands771e82a2011-01-28 16:51:11 +00001011 }
1012 }
1013
Duncan Sands65995fa2011-01-28 18:50:50 +00001014 bool isSigned = Opcode == Instruction::SDiv;
1015
Duncan Sands771e82a2011-01-28 16:51:11 +00001016 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001017 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001018 return Op1;
1019
1020 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001021 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 return Constant::getNullValue(Op0->getType());
1023
1024 // 0 / X -> 0, we don't need to preserve faults!
1025 if (match(Op0, m_Zero()))
1026 return Op0;
1027
1028 // X / 1 -> X
1029 if (match(Op1, m_One()))
1030 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001031
1032 if (Op0->getType()->isIntegerTy(1))
1033 // It can't be division by zero, hence it must be division by one.
1034 return Op0;
1035
1036 // X / X -> 1
1037 if (Op0 == Op1)
1038 return ConstantInt::get(Op0->getType(), 1);
1039
1040 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001041 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001042 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1043 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001044 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001045 // If the Mul knows it does not overflow, then we are good to go.
1046 if ((isSigned && Mul->hasNoSignedWrap()) ||
1047 (!isSigned && Mul->hasNoUnsignedWrap()))
1048 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001049 // If X has the form X = A / Y then X * Y cannot overflow.
1050 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1051 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1052 return X;
1053 }
1054
Duncan Sands65995fa2011-01-28 18:50:50 +00001055 // (X rem Y) / Y -> 0
1056 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1057 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1058 return Constant::getNullValue(Op0->getType());
1059
1060 // If the operation is with the result of a select instruction, check whether
1061 // operating on either branch of the select always yields the same value.
1062 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001063 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001064 return V;
1065
1066 // If the operation is with the result of a phi instruction, check whether
1067 // operating on all incoming values of the phi always yields the same value.
1068 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001069 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001070 return V;
1071
Craig Topper9f008862014-04-15 04:59:12 +00001072 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001073}
1074
1075/// SimplifySDivInst - Given operands for an SDiv, see if we can
1076/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001077static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1078 unsigned MaxRecurse) {
1079 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001080 return V;
1081
Craig Topper9f008862014-04-15 04:59:12 +00001082 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001083}
1084
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001085Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001086 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001087 const DominatorTree *DT,
1088 AssumptionTracker *AT,
1089 const Instruction *CxtI) {
1090 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1091 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001092}
1093
1094/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1095/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001096static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1097 unsigned MaxRecurse) {
1098 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001099 return V;
1100
Craig Topper9f008862014-04-15 04:59:12 +00001101 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001102}
1103
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001104Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001105 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001106 const DominatorTree *DT,
1107 AssumptionTracker *AT,
1108 const Instruction *CxtI) {
1109 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1110 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001111}
1112
Duncan Sandsb8cee002012-03-13 11:42:19 +00001113static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1114 unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001115 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001116 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001117 return Op0;
1118
1119 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001120 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001121 return Op1;
1122
Craig Topper9f008862014-04-15 04:59:12 +00001123 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001124}
1125
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001126Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001127 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001128 const DominatorTree *DT,
1129 AssumptionTracker *AT,
1130 const Instruction *CxtI) {
1131 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1132 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001133}
1134
Duncan Sandsa3e36992011-05-02 16:27:02 +00001135/// SimplifyRem - Given operands for an SRem or URem, see if we can
1136/// fold the result. If not, this returns null.
1137static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001138 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001139 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1140 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1141 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001142 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001143 }
1144 }
1145
Duncan Sandsa3e36992011-05-02 16:27:02 +00001146 // X % undef -> undef
1147 if (match(Op1, m_Undef()))
1148 return Op1;
1149
1150 // undef % X -> 0
1151 if (match(Op0, m_Undef()))
1152 return Constant::getNullValue(Op0->getType());
1153
1154 // 0 % X -> 0, we don't need to preserve faults!
1155 if (match(Op0, m_Zero()))
1156 return Op0;
1157
1158 // X % 0 -> undef, we don't need to preserve faults!
1159 if (match(Op1, m_Zero()))
1160 return UndefValue::get(Op0->getType());
1161
1162 // X % 1 -> 0
1163 if (match(Op1, m_One()))
1164 return Constant::getNullValue(Op0->getType());
1165
1166 if (Op0->getType()->isIntegerTy(1))
1167 // It can't be remainder by zero, hence it must be remainder by one.
1168 return Constant::getNullValue(Op0->getType());
1169
1170 // X % X -> 0
1171 if (Op0 == Op1)
1172 return Constant::getNullValue(Op0->getType());
1173
David Majnemerac717f02014-09-17 03:34:34 +00001174 // ((X % Y) % Y) -> (X % Y)
1175 if (match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) {
1176 return Op0;
1177 }
1178
Duncan Sandsa3e36992011-05-02 16:27:02 +00001179 // If the operation is with the result of a select instruction, check whether
1180 // operating on either branch of the select always yields the same value.
1181 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001182 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001183 return V;
1184
1185 // If the operation is with the result of a phi instruction, check whether
1186 // operating on all incoming values of the phi always yields the same value.
1187 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001188 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001189 return V;
1190
Craig Topper9f008862014-04-15 04:59:12 +00001191 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001192}
1193
1194/// SimplifySRemInst - Given operands for an SRem, see if we can
1195/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001196static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1197 unsigned MaxRecurse) {
1198 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001199 return V;
1200
Craig Topper9f008862014-04-15 04:59:12 +00001201 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001202}
1203
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001204Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001205 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001206 const DominatorTree *DT,
1207 AssumptionTracker *AT,
1208 const Instruction *CxtI) {
1209 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1210 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001211}
1212
1213/// SimplifyURemInst - Given operands for a URem, see if we can
1214/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001215static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001216 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001217 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001218 return V;
1219
Craig Topper9f008862014-04-15 04:59:12 +00001220 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001221}
1222
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001223Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001224 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001225 const DominatorTree *DT,
1226 AssumptionTracker *AT,
1227 const Instruction *CxtI) {
1228 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1229 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230}
1231
Duncan Sandsb8cee002012-03-13 11:42:19 +00001232static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001233 unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001234 // undef % X -> undef (the undef could be a snan).
1235 if (match(Op0, m_Undef()))
1236 return Op0;
1237
1238 // X % undef -> undef
1239 if (match(Op1, m_Undef()))
1240 return Op1;
1241
Craig Topper9f008862014-04-15 04:59:12 +00001242 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001243}
1244
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001245Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001246 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001247 const DominatorTree *DT,
1248 AssumptionTracker *AT,
1249 const Instruction *CxtI) {
1250 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1251 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001252}
1253
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001254/// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1255static bool isUndefShift(Value *Amount) {
1256 Constant *C = dyn_cast<Constant>(Amount);
1257 if (!C)
1258 return false;
1259
1260 // X shift by undef -> undef because it may shift by the bitwidth.
1261 if (isa<UndefValue>(C))
1262 return true;
1263
1264 // Shifting by the bitwidth or more is undefined.
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1266 if (CI->getValue().getLimitedValue() >=
1267 CI->getType()->getScalarSizeInBits())
1268 return true;
1269
1270 // If all lanes of a vector shift are undefined the whole shift is.
1271 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1272 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1273 if (!isUndefShift(C->getAggregateElement(I)))
1274 return false;
1275 return true;
1276 }
1277
1278 return false;
1279}
1280
Duncan Sands571fd9a2011-01-14 14:44:12 +00001281/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sands7f60dc12011-01-14 00:37:45 +00001282/// fold the result. If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001283static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001284 const Query &Q, unsigned MaxRecurse) {
Duncan Sands7f60dc12011-01-14 00:37:45 +00001285 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1286 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1287 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001288 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001289 }
1290 }
1291
Duncan Sands571fd9a2011-01-14 14:44:12 +00001292 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001293 if (match(Op0, m_Zero()))
1294 return Op0;
1295
Duncan Sands571fd9a2011-01-14 14:44:12 +00001296 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001297 if (match(Op1, m_Zero()))
1298 return Op0;
1299
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001300 // Fold undefined shifts.
1301 if (isUndefShift(Op1))
1302 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001303
Duncan Sands571fd9a2011-01-14 14:44:12 +00001304 // If the operation is with the result of a select instruction, check whether
1305 // operating on either branch of the select always yields the same value.
1306 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001307 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001308 return V;
1309
1310 // If the operation is with the result of a phi instruction, check whether
1311 // operating on all incoming values of the phi always yields the same value.
1312 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001313 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001314 return V;
1315
Craig Topper9f008862014-04-15 04:59:12 +00001316 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001317}
1318
1319/// SimplifyShlInst - Given operands for an Shl, see if we can
1320/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001321static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001322 const Query &Q, unsigned MaxRecurse) {
1323 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001324 return V;
1325
1326 // undef << X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001327 if (match(Op0, m_Undef()))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001328 return Constant::getNullValue(Op0->getType());
1329
Chris Lattner9e4aa022011-02-09 17:15:04 +00001330 // (X >> A) << A -> X
1331 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001332 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001333 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001334 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001335}
1336
Chris Lattner9e4aa022011-02-09 17:15:04 +00001337Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001338 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001339 const DominatorTree *DT, AssumptionTracker *AT,
1340 const Instruction *CxtI) {
1341 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001342 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001343}
1344
1345/// SimplifyLShrInst - Given operands for an LShr, see if we can
1346/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001347static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001348 const Query &Q, unsigned MaxRecurse) {
1349 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001350 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001351
David Majnemera80fed72013-07-09 22:01:22 +00001352 // X >> X -> 0
1353 if (Op0 == Op1)
1354 return Constant::getNullValue(Op0->getType());
1355
Duncan Sands7f60dc12011-01-14 00:37:45 +00001356 // undef >>l X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001357 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001358 return Constant::getNullValue(Op0->getType());
1359
Chris Lattner9e4aa022011-02-09 17:15:04 +00001360 // (X << A) >> A -> X
1361 Value *X;
1362 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1363 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1364 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001365
Craig Topper9f008862014-04-15 04:59:12 +00001366 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001367}
1368
Chris Lattner9e4aa022011-02-09 17:15:04 +00001369Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001370 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001371 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001372 const DominatorTree *DT,
1373 AssumptionTracker *AT,
1374 const Instruction *CxtI) {
1375 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001376 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001377}
1378
1379/// SimplifyAShrInst - Given operands for an AShr, see if we can
1380/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001381static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001382 const Query &Q, unsigned MaxRecurse) {
1383 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001384 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001385
David Majnemera80fed72013-07-09 22:01:22 +00001386 // X >> X -> 0
1387 if (Op0 == Op1)
1388 return Constant::getNullValue(Op0->getType());
1389
Duncan Sands7f60dc12011-01-14 00:37:45 +00001390 // all ones >>a X -> all ones
1391 if (match(Op0, m_AllOnes()))
1392 return Op0;
1393
1394 // undef >>a X -> all ones
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001395 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001396 return Constant::getAllOnesValue(Op0->getType());
1397
Chris Lattner9e4aa022011-02-09 17:15:04 +00001398 // (X << A) >> A -> X
1399 Value *X;
1400 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1401 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1402 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001403
Suyog Sarda68862412014-07-17 06:28:15 +00001404 // Arithmetic shifting an all-sign-bit value is a no-op.
Hal Finkel60db0582014-09-07 18:57:58 +00001405 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001406 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1407 return Op0;
1408
Craig Topper9f008862014-04-15 04:59:12 +00001409 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001410}
1411
Chris Lattner9e4aa022011-02-09 17:15:04 +00001412Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001413 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001414 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001415 const DominatorTree *DT,
1416 AssumptionTracker *AT,
1417 const Instruction *CxtI) {
1418 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001419 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001420}
1421
David Majnemera315bd82014-09-15 08:15:28 +00001422// Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1423// of possible values cannot be satisfied.
1424static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1425 ICmpInst::Predicate Pred0, Pred1;
1426 ConstantInt *CI1, *CI2;
1427 Value *V;
1428 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1429 m_ConstantInt(CI2))))
1430 return nullptr;
1431
1432 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1433 return nullptr;
1434
1435 Type *ITy = Op0->getType();
1436
1437 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1438 bool isNSW = AddInst->hasNoSignedWrap();
1439 bool isNUW = AddInst->hasNoUnsignedWrap();
1440
1441 const APInt &CI1V = CI1->getValue();
1442 const APInt &CI2V = CI2->getValue();
1443 const APInt Delta = CI2V - CI1V;
1444 if (CI1V.isStrictlyPositive()) {
1445 if (Delta == 2) {
1446 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1447 return getFalse(ITy);
1448 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1449 return getFalse(ITy);
1450 }
1451 if (Delta == 1) {
1452 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1453 return getFalse(ITy);
1454 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1455 return getFalse(ITy);
1456 }
1457 }
1458 if (CI1V.getBoolValue() && isNUW) {
1459 if (Delta == 2)
1460 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1461 return getFalse(ITy);
1462 if (Delta == 1)
1463 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1464 return getFalse(ITy);
1465 }
1466
1467 return nullptr;
1468}
1469
Chris Lattnera71e9d62009-11-10 00:55:12 +00001470/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner084a1b52009-11-09 22:57:59 +00001471/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001472static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001473 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001474 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1475 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1476 Constant *Ops[] = { CLHS, CRHS };
1477 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001478 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001479 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001480
Chris Lattnera71e9d62009-11-10 00:55:12 +00001481 // Canonicalize the constant to the RHS.
1482 std::swap(Op0, Op1);
1483 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001484
Chris Lattnera71e9d62009-11-10 00:55:12 +00001485 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001486 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001487 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001488
Chris Lattnera71e9d62009-11-10 00:55:12 +00001489 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001490 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001491 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001492
Duncan Sandsc89ac072010-11-17 18:52:15 +00001493 // X & 0 = 0
1494 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001495 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001496
Duncan Sandsc89ac072010-11-17 18:52:15 +00001497 // X & -1 = X
1498 if (match(Op1, m_AllOnes()))
1499 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001500
Chris Lattnera71e9d62009-11-10 00:55:12 +00001501 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001502 if (match(Op0, m_Not(m_Specific(Op1))) ||
1503 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001504 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001505
Chris Lattnera71e9d62009-11-10 00:55:12 +00001506 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001507 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001508 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001509 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001510 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001511
Chris Lattnera71e9d62009-11-10 00:55:12 +00001512 // A & (A | ?) = A
1513 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001514 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001515 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001516
Duncan Sandsba286d72011-10-26 20:55:21 +00001517 // A & (-A) = A if A is a power of two or zero.
1518 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1519 match(Op1, m_Neg(m_Specific(Op0)))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001520 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001521 return Op0;
Hal Finkel60db0582014-09-07 18:57:58 +00001522 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001523 return Op1;
1524 }
1525
David Majnemera315bd82014-09-15 08:15:28 +00001526 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1527 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1528 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1529 return V;
1530 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1531 return V;
1532 }
1533 }
1534
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001535 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001536 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1537 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001538 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001539
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001540 // And distributes over Or. Try some generic simplifications based on this.
1541 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001542 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001543 return V;
1544
1545 // And distributes over Xor. Try some generic simplifications based on this.
1546 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001547 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001548 return V;
1549
Duncan Sandsb0579e92010-11-10 13:00:08 +00001550 // If the operation is with the result of a select instruction, check whether
1551 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001552 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001553 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1554 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001555 return V;
1556
1557 // If the operation is with the result of a phi instruction, check whether
1558 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001559 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001560 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001561 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001562 return V;
1563
Craig Topper9f008862014-04-15 04:59:12 +00001564 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001565}
1566
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001567Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001568 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001569 const DominatorTree *DT, AssumptionTracker *AT,
1570 const Instruction *CxtI) {
1571 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1572 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001573}
1574
David Majnemera315bd82014-09-15 08:15:28 +00001575// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1576// contains all possible values.
1577static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1578 ICmpInst::Predicate Pred0, Pred1;
1579 ConstantInt *CI1, *CI2;
1580 Value *V;
1581 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1582 m_ConstantInt(CI2))))
1583 return nullptr;
1584
1585 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1586 return nullptr;
1587
1588 Type *ITy = Op0->getType();
1589
1590 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1591 bool isNSW = AddInst->hasNoSignedWrap();
1592 bool isNUW = AddInst->hasNoUnsignedWrap();
1593
1594 const APInt &CI1V = CI1->getValue();
1595 const APInt &CI2V = CI2->getValue();
1596 const APInt Delta = CI2V - CI1V;
1597 if (CI1V.isStrictlyPositive()) {
1598 if (Delta == 2) {
1599 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1600 return getTrue(ITy);
1601 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1602 return getTrue(ITy);
1603 }
1604 if (Delta == 1) {
1605 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1606 return getTrue(ITy);
1607 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1608 return getTrue(ITy);
1609 }
1610 }
1611 if (CI1V.getBoolValue() && isNUW) {
1612 if (Delta == 2)
1613 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1614 return getTrue(ITy);
1615 if (Delta == 1)
1616 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1617 return getTrue(ITy);
1618 }
1619
1620 return nullptr;
1621}
1622
Chris Lattnera71e9d62009-11-10 00:55:12 +00001623/// SimplifyOrInst - Given operands for an Or, see if we can
1624/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001625static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1626 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001627 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1628 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1629 Constant *Ops[] = { CLHS, CRHS };
1630 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001631 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001632 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001633
Chris Lattnera71e9d62009-11-10 00:55:12 +00001634 // Canonicalize the constant to the RHS.
1635 std::swap(Op0, Op1);
1636 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001637
Chris Lattnera71e9d62009-11-10 00:55:12 +00001638 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001639 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001640 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001641
Chris Lattnera71e9d62009-11-10 00:55:12 +00001642 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001643 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001644 return Op0;
1645
Duncan Sandsc89ac072010-11-17 18:52:15 +00001646 // X | 0 = X
1647 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001648 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001649
Duncan Sandsc89ac072010-11-17 18:52:15 +00001650 // X | -1 = -1
1651 if (match(Op1, m_AllOnes()))
1652 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001653
Chris Lattnera71e9d62009-11-10 00:55:12 +00001654 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001655 if (match(Op0, m_Not(m_Specific(Op1))) ||
1656 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001657 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001658
Chris Lattnera71e9d62009-11-10 00:55:12 +00001659 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001660 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001661 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001662 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001663 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001664
Chris Lattnera71e9d62009-11-10 00:55:12 +00001665 // A | (A & ?) = A
1666 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001667 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001668 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001669
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001670 // ~(A & ?) | A = -1
1671 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1672 (A == Op1 || B == Op1))
1673 return Constant::getAllOnesValue(Op1->getType());
1674
1675 // A | ~(A & ?) = -1
1676 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1677 (A == Op0 || B == Op0))
1678 return Constant::getAllOnesValue(Op0->getType());
1679
David Majnemera315bd82014-09-15 08:15:28 +00001680 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1681 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1682 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1683 return V;
1684 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1685 return V;
1686 }
1687 }
1688
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001689 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001690 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1691 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001692 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001693
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001694 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001695 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1696 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001697 return V;
1698
Duncan Sandsb0579e92010-11-10 13:00:08 +00001699 // If the operation is with the result of a select instruction, check whether
1700 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001701 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001702 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001703 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001704 return V;
1705
Nick Lewycky8561a492014-06-19 03:51:46 +00001706 // (A & C)|(B & D)
1707 Value *C = nullptr, *D = nullptr;
1708 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1709 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1710 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1711 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1712 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1713 // (A & C1)|(B & C2)
1714 // If we have: ((V + N) & C1) | (V & C2)
1715 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1716 // replace with V+N.
1717 Value *V1, *V2;
1718 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1719 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1720 // Add commutes, try both ways.
Hal Finkel60db0582014-09-07 18:57:58 +00001721 if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
1722 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001723 return A;
Hal Finkel60db0582014-09-07 18:57:58 +00001724 if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
1725 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001726 return A;
1727 }
1728 // Or commutes, try both ways.
1729 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1730 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1731 // Add commutes, try both ways.
Hal Finkel60db0582014-09-07 18:57:58 +00001732 if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
1733 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001734 return B;
Hal Finkel60db0582014-09-07 18:57:58 +00001735 if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
1736 0, Q.AT, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001737 return B;
1738 }
1739 }
1740 }
1741
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001742 // If the operation is with the result of a phi instruction, check whether
1743 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001744 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001745 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001746 return V;
1747
Craig Topper9f008862014-04-15 04:59:12 +00001748 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001749}
1750
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001751Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001752 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001753 const DominatorTree *DT, AssumptionTracker *AT,
1754 const Instruction *CxtI) {
1755 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1756 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001757}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001758
Duncan Sandsc89ac072010-11-17 18:52:15 +00001759/// SimplifyXorInst - Given operands for a Xor, see if we can
1760/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001761static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1762 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001763 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1764 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1765 Constant *Ops[] = { CLHS, CRHS };
1766 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001767 Ops, Q.DL, Q.TLI);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001768 }
1769
1770 // Canonicalize the constant to the RHS.
1771 std::swap(Op0, Op1);
1772 }
1773
1774 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001775 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001776 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001777
1778 // A ^ 0 = A
1779 if (match(Op1, m_Zero()))
1780 return Op0;
1781
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001782 // A ^ A = 0
1783 if (Op0 == Op1)
1784 return Constant::getNullValue(Op0->getType());
1785
Duncan Sandsc89ac072010-11-17 18:52:15 +00001786 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001787 if (match(Op0, m_Not(m_Specific(Op1))) ||
1788 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001789 return Constant::getAllOnesValue(Op0->getType());
1790
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001791 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001792 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1793 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001794 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001795
Duncan Sandsb238de02010-11-19 09:20:39 +00001796 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1797 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1798 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1799 // only if B and C are equal. If B and C are equal then (since we assume
1800 // that operands have already been simplified) "select(cond, B, C)" should
1801 // have been simplified to the common value of B and C already. Analysing
1802 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1803 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001804
Craig Topper9f008862014-04-15 04:59:12 +00001805 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001806}
1807
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001808Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001809 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00001810 const DominatorTree *DT, AssumptionTracker *AT,
1811 const Instruction *CxtI) {
1812 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1813 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001814}
1815
Chris Lattner229907c2011-07-18 04:54:35 +00001816static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001817 return CmpInst::makeCmpResultType(Op->getType());
1818}
1819
Duncan Sandsaf327282011-05-07 16:56:49 +00001820/// ExtractEquivalentCondition - Rummage around inside V looking for something
1821/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1822/// otherwise return null. Helper function for analyzing max/min idioms.
1823static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1824 Value *LHS, Value *RHS) {
1825 SelectInst *SI = dyn_cast<SelectInst>(V);
1826 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001827 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001828 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1829 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001830 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001831 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1832 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1833 return Cmp;
1834 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1835 LHS == CmpRHS && RHS == CmpLHS)
1836 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001837 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001838}
1839
Dan Gohman9631d902013-02-01 00:49:06 +00001840// A significant optimization not implemented here is assuming that alloca
1841// addresses are not equal to incoming argument values. They don't *alias*,
1842// as we say, but that doesn't mean they aren't equal, so we take a
1843// conservative approach.
1844//
1845// This is inspired in part by C++11 5.10p1:
1846// "Two pointers of the same type compare equal if and only if they are both
1847// null, both point to the same function, or both represent the same
1848// address."
1849//
1850// This is pretty permissive.
1851//
1852// It's also partly due to C11 6.5.9p6:
1853// "Two pointers compare equal if and only if both are null pointers, both are
1854// pointers to the same object (including a pointer to an object and a
1855// subobject at its beginning) or function, both are pointers to one past the
1856// last element of the same array object, or one is a pointer to one past the
1857// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001858// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001859// object in the address space.)
1860//
1861// C11's version is more restrictive, however there's no reason why an argument
1862// couldn't be a one-past-the-end value for a stack object in the caller and be
1863// equal to the beginning of a stack object in the callee.
1864//
1865// If the C and C++ standards are ever made sufficiently restrictive in this
1866// area, it may be possible to update LLVM's semantics accordingly and reinstate
1867// this optimization.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001868static Constant *computePointerICmp(const DataLayout *DL,
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001869 const TargetLibraryInfo *TLI,
Chandler Carruth8059c842012-03-25 21:28:14 +00001870 CmpInst::Predicate Pred,
1871 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001872 // First, skip past any trivial no-ops.
1873 LHS = LHS->stripPointerCasts();
1874 RHS = RHS->stripPointerCasts();
1875
1876 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001877 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001878 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1879 return ConstantInt::get(GetCompareTy(LHS),
1880 !CmpInst::isTrueWhenEqual(Pred));
1881
Chandler Carruth8059c842012-03-25 21:28:14 +00001882 // We can only fold certain predicates on pointer comparisons.
1883 switch (Pred) {
1884 default:
Craig Topper9f008862014-04-15 04:59:12 +00001885 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001886
1887 // Equality comaprisons are easy to fold.
1888 case CmpInst::ICMP_EQ:
1889 case CmpInst::ICMP_NE:
1890 break;
1891
1892 // We can only handle unsigned relational comparisons because 'inbounds' on
1893 // a GEP only protects against unsigned wrapping.
1894 case CmpInst::ICMP_UGT:
1895 case CmpInst::ICMP_UGE:
1896 case CmpInst::ICMP_ULT:
1897 case CmpInst::ICMP_ULE:
1898 // However, we have to switch them to their signed variants to handle
1899 // negative indices from the base pointer.
1900 Pred = ICmpInst::getSignedPredicate(Pred);
1901 break;
1902 }
1903
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001904 // Strip off any constant offsets so that we can reason about them.
1905 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1906 // here and compare base addresses like AliasAnalysis does, however there are
1907 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1908 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1909 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001910 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1911 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001912
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001913 // If LHS and RHS are related via constant offsets to the same base
1914 // value, we can replace it with an icmp which just compares the offsets.
1915 if (LHS == RHS)
1916 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001917
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001918 // Various optimizations for (in)equality comparisons.
1919 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1920 // Different non-empty allocations that exist at the same time have
1921 // different addresses (if the program can tell). Global variables always
1922 // exist, so they always exist during the lifetime of each other and all
1923 // allocas. Two different allocas usually have different addresses...
1924 //
1925 // However, if there's an @llvm.stackrestore dynamically in between two
1926 // allocas, they may have the same address. It's tempting to reduce the
1927 // scope of the problem by only looking at *static* allocas here. That would
1928 // cover the majority of allocas while significantly reducing the likelihood
1929 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1930 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1931 // an entry block. Also, if we have a block that's not attached to a
1932 // function, we can't tell if it's "static" under the current definition.
1933 // Theoretically, this problem could be fixed by creating a new kind of
1934 // instruction kind specifically for static allocas. Such a new instruction
1935 // could be required to be at the top of the entry block, thus preventing it
1936 // from being subject to a @llvm.stackrestore. Instcombine could even
1937 // convert regular allocas into these special allocas. It'd be nifty.
1938 // However, until then, this problem remains open.
1939 //
1940 // So, we'll assume that two non-empty allocas have different addresses
1941 // for now.
1942 //
1943 // With all that, if the offsets are within the bounds of their allocations
1944 // (and not one-past-the-end! so we can't use inbounds!), and their
1945 // allocations aren't the same, the pointers are not equal.
1946 //
1947 // Note that it's not necessary to check for LHS being a global variable
1948 // address, due to canonicalization and constant folding.
1949 if (isa<AllocaInst>(LHS) &&
1950 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001951 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1952 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001953 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001954 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001955 getObjectSize(LHS, LHSSize, DL, TLI) &&
1956 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001957 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1958 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001959 if (!LHSOffsetValue.isNegative() &&
1960 !RHSOffsetValue.isNegative() &&
1961 LHSOffsetValue.ult(LHSSize) &&
1962 RHSOffsetValue.ult(RHSSize)) {
1963 return ConstantInt::get(GetCompareTy(LHS),
1964 !CmpInst::isTrueWhenEqual(Pred));
1965 }
1966 }
1967
1968 // Repeat the above check but this time without depending on DataLayout
1969 // or being able to compute a precise size.
1970 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1971 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1972 LHSOffset->isNullValue() &&
1973 RHSOffset->isNullValue())
1974 return ConstantInt::get(GetCompareTy(LHS),
1975 !CmpInst::isTrueWhenEqual(Pred));
1976 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001977
1978 // Even if an non-inbounds GEP occurs along the path we can still optimize
1979 // equality comparisons concerning the result. We avoid walking the whole
1980 // chain again by starting where the last calls to
1981 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001982 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1983 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001984 if (LHS == RHS)
1985 return ConstantExpr::getICmp(Pred,
1986 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1987 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001988 }
1989
1990 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00001991 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001992}
Chris Lattner01990f02012-02-24 19:01:58 +00001993
Chris Lattnerc1f19072009-11-09 23:28:39 +00001994/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1995/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001996static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001997 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00001998 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00001999 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002000
Chris Lattnera71e9d62009-11-10 00:55:12 +00002001 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002002 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002003 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002004
2005 // If we have a constant, make sure it is on the RHS.
2006 std::swap(LHS, RHS);
2007 Pred = CmpInst::getSwappedPredicate(Pred);
2008 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002009
Chris Lattner229907c2011-07-18 04:54:35 +00002010 Type *ITy = GetCompareTy(LHS); // The return type.
2011 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002012
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002013 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002014 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2015 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002016 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002017 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002018
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002019 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00002020 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002021 switch (Pred) {
2022 default: break;
2023 case ICmpInst::ICMP_EQ:
2024 // X == 1 -> X
2025 if (match(RHS, m_One()))
2026 return LHS;
2027 break;
2028 case ICmpInst::ICMP_NE:
2029 // X != 0 -> X
2030 if (match(RHS, m_Zero()))
2031 return LHS;
2032 break;
2033 case ICmpInst::ICMP_UGT:
2034 // X >u 0 -> X
2035 if (match(RHS, m_Zero()))
2036 return LHS;
2037 break;
2038 case ICmpInst::ICMP_UGE:
2039 // X >=u 1 -> X
2040 if (match(RHS, m_One()))
2041 return LHS;
2042 break;
2043 case ICmpInst::ICMP_SLT:
2044 // X <s 0 -> X
2045 if (match(RHS, m_Zero()))
2046 return LHS;
2047 break;
2048 case ICmpInst::ICMP_SLE:
2049 // X <=s -1 -> X
2050 if (match(RHS, m_One()))
2051 return LHS;
2052 break;
2053 }
2054 }
2055
Duncan Sandsd3951082011-01-25 09:38:29 +00002056 // If we are comparing with zero then try hard since this is a common case.
2057 if (match(RHS, m_Zero())) {
2058 bool LHSKnownNonNegative, LHSKnownNegative;
2059 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002060 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00002061 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002062 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002063 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002064 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002065 case ICmpInst::ICMP_EQ:
2066 case ICmpInst::ICMP_ULE:
Hal Finkel60db0582014-09-07 18:57:58 +00002067 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002068 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002069 break;
2070 case ICmpInst::ICMP_NE:
2071 case ICmpInst::ICMP_UGT:
Hal Finkel60db0582014-09-07 18:57:58 +00002072 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002073 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002074 break;
2075 case ICmpInst::ICMP_SLT:
Hal Finkel60db0582014-09-07 18:57:58 +00002076 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2077 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002078 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002079 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002080 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002081 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002082 break;
2083 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00002084 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2085 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002086 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002087 return getTrue(ITy);
Hal Finkel60db0582014-09-07 18:57:58 +00002088 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
2089 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002090 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002091 break;
2092 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00002093 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2094 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002095 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002096 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002097 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002098 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002099 break;
2100 case ICmpInst::ICMP_SGT:
Hal Finkel60db0582014-09-07 18:57:58 +00002101 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2102 0, Q.AT, Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002103 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002104 return getFalse(ITy);
Hal Finkel60db0582014-09-07 18:57:58 +00002105 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
2106 0, Q.AT, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002107 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002108 break;
2109 }
2110 }
2111
2112 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002113 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002114 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2115 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2116 if (RHS_CR.isEmptySet())
2117 return ConstantInt::getFalse(CI->getContext());
2118 if (RHS_CR.isFullSet())
2119 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002120
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002121 // Many binary operators with constant RHS have easy to compute constant
2122 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002123 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002124 APInt Lower = APInt(Width, 0);
2125 APInt Upper = APInt(Width, 0);
2126 ConstantInt *CI2;
2127 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2128 // 'urem x, CI2' produces [0, CI2).
2129 Upper = CI2->getValue();
2130 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2131 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2132 Upper = CI2->getValue().abs();
2133 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002134 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2135 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002136 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002137 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2138 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2139 APInt NegOne = APInt::getAllOnesValue(Width);
2140 if (!CI2->isZero())
2141 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002142 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00002143 if (CI2->isMinSignedValue()) {
2144 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2145 Lower = CI2->getValue();
2146 Upper = Lower.lshr(1) + 1;
2147 } else {
2148 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2149 Upper = CI2->getValue().abs() + 1;
2150 Lower = (-Upper) + 1;
2151 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002152 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002153 APInt IntMin = APInt::getSignedMinValue(Width);
2154 APInt IntMax = APInt::getSignedMaxValue(Width);
David Majnemeraf9180f2014-07-14 20:38:45 +00002155 APInt Val = CI2->getValue();
2156 if (Val.isAllOnesValue()) {
2157 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2158 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2159 Lower = IntMin + 1;
2160 Upper = IntMax + 1;
2161 } else if (Val.countLeadingZeros() < Width - 1) {
2162 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2163 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002164 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00002165 Upper = IntMax.sdiv(Val);
2166 if (Lower.sgt(Upper))
2167 std::swap(Lower, Upper);
2168 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00002169 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002170 }
David Majnemerd6d16712014-08-27 18:03:46 +00002171 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2172 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2173 Lower = CI2->getValue();
2174 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2175 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2176 if (CI2->isNegative()) {
2177 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2178 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2179 Lower = CI2->getValue().shl(ShiftAmount);
2180 Upper = CI2->getValue() + 1;
2181 } else {
2182 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2183 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2184 Lower = CI2->getValue();
2185 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2186 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002187 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2188 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2189 APInt NegOne = APInt::getAllOnesValue(Width);
2190 if (CI2->getValue().ult(Width))
2191 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002192 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2193 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2194 unsigned ShiftAmount = Width - 1;
2195 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2196 ShiftAmount = CI2->getValue().countTrailingZeros();
2197 Lower = CI2->getValue().lshr(ShiftAmount);
2198 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002199 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2200 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2201 APInt IntMin = APInt::getSignedMinValue(Width);
2202 APInt IntMax = APInt::getSignedMaxValue(Width);
2203 if (CI2->getValue().ult(Width)) {
2204 Lower = IntMin.ashr(CI2->getValue());
2205 Upper = IntMax.ashr(CI2->getValue()) + 1;
2206 }
David Majnemer78910fc2014-05-16 17:14:03 +00002207 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2208 unsigned ShiftAmount = Width - 1;
2209 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2210 ShiftAmount = CI2->getValue().countTrailingZeros();
2211 if (CI2->isNegative()) {
2212 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2213 Lower = CI2->getValue();
2214 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2215 } else {
2216 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2217 Lower = CI2->getValue().ashr(ShiftAmount);
2218 Upper = CI2->getValue() + 1;
2219 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002220 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2221 // 'or x, CI2' produces [CI2, UINT_MAX].
2222 Lower = CI2->getValue();
2223 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2224 // 'and x, CI2' produces [0, CI2].
2225 Upper = CI2->getValue() + 1;
2226 }
2227 if (Lower != Upper) {
2228 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2229 if (RHS_CR.contains(LHS_CR))
2230 return ConstantInt::getTrue(RHS->getContext());
2231 if (RHS_CR.inverse().contains(LHS_CR))
2232 return ConstantInt::getFalse(RHS->getContext());
2233 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002234 }
2235
Duncan Sands8fb2c382011-01-20 13:21:55 +00002236 // Compare of cast, for example (zext X) != 0 -> X != 0
2237 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2238 Instruction *LI = cast<CastInst>(LHS);
2239 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002240 Type *SrcTy = SrcOp->getType();
2241 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002242
2243 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2244 // if the integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002245 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2246 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002247 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2248 // Transfer the cast to the constant.
2249 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2250 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002251 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002252 return V;
2253 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2254 if (RI->getOperand(0)->getType() == SrcTy)
2255 // Compare without the cast.
2256 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002257 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002258 return V;
2259 }
2260 }
2261
2262 if (isa<ZExtInst>(LHS)) {
2263 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2264 // same type.
2265 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2266 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2267 // Compare X and Y. Note that signed predicates become unsigned.
2268 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002269 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002270 MaxRecurse-1))
2271 return V;
2272 }
2273 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2274 // too. If not, then try to deduce the result of the comparison.
2275 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2276 // Compute the constant that would happen if we truncated to SrcTy then
2277 // reextended to DstTy.
2278 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2279 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2280
2281 // If the re-extended constant didn't change then this is effectively
2282 // also a case of comparing two zero-extended values.
2283 if (RExt == CI && MaxRecurse)
2284 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002285 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002286 return V;
2287
2288 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2289 // there. Use this to work out the result of the comparison.
2290 if (RExt != CI) {
2291 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002292 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002293 // LHS <u RHS.
2294 case ICmpInst::ICMP_EQ:
2295 case ICmpInst::ICMP_UGT:
2296 case ICmpInst::ICMP_UGE:
2297 return ConstantInt::getFalse(CI->getContext());
2298
2299 case ICmpInst::ICMP_NE:
2300 case ICmpInst::ICMP_ULT:
2301 case ICmpInst::ICMP_ULE:
2302 return ConstantInt::getTrue(CI->getContext());
2303
2304 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2305 // is non-negative then LHS <s RHS.
2306 case ICmpInst::ICMP_SGT:
2307 case ICmpInst::ICMP_SGE:
2308 return CI->getValue().isNegative() ?
2309 ConstantInt::getTrue(CI->getContext()) :
2310 ConstantInt::getFalse(CI->getContext());
2311
2312 case ICmpInst::ICMP_SLT:
2313 case ICmpInst::ICMP_SLE:
2314 return CI->getValue().isNegative() ?
2315 ConstantInt::getFalse(CI->getContext()) :
2316 ConstantInt::getTrue(CI->getContext());
2317 }
2318 }
2319 }
2320 }
2321
2322 if (isa<SExtInst>(LHS)) {
2323 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2324 // same type.
2325 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2326 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2327 // Compare X and Y. Note that the predicate does not change.
2328 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002329 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002330 return V;
2331 }
2332 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2333 // too. If not, then try to deduce the result of the comparison.
2334 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2335 // Compute the constant that would happen if we truncated to SrcTy then
2336 // reextended to DstTy.
2337 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2338 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2339
2340 // If the re-extended constant didn't change then this is effectively
2341 // also a case of comparing two sign-extended values.
2342 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002343 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002344 return V;
2345
2346 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2347 // bits there. Use this to work out the result of the comparison.
2348 if (RExt != CI) {
2349 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002350 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002351 case ICmpInst::ICMP_EQ:
2352 return ConstantInt::getFalse(CI->getContext());
2353 case ICmpInst::ICMP_NE:
2354 return ConstantInt::getTrue(CI->getContext());
2355
2356 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2357 // LHS >s RHS.
2358 case ICmpInst::ICMP_SGT:
2359 case ICmpInst::ICMP_SGE:
2360 return CI->getValue().isNegative() ?
2361 ConstantInt::getTrue(CI->getContext()) :
2362 ConstantInt::getFalse(CI->getContext());
2363 case ICmpInst::ICMP_SLT:
2364 case ICmpInst::ICMP_SLE:
2365 return CI->getValue().isNegative() ?
2366 ConstantInt::getFalse(CI->getContext()) :
2367 ConstantInt::getTrue(CI->getContext());
2368
2369 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2370 // LHS >u RHS.
2371 case ICmpInst::ICMP_UGT:
2372 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002373 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002374 if (MaxRecurse)
2375 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2376 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002377 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002378 return V;
2379 break;
2380 case ICmpInst::ICMP_ULT:
2381 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002382 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002383 if (MaxRecurse)
2384 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2385 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002386 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002387 return V;
2388 break;
2389 }
2390 }
2391 }
2392 }
2393 }
2394
Nick Lewyckyc9610302014-06-19 03:35:49 +00002395 // If a bit is known to be zero for A and known to be one for B,
2396 // then A and B cannot be equal.
2397 if (ICmpInst::isEquality(Pred)) {
2398 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2399 uint32_t BitWidth = CI->getBitWidth();
2400 APInt LHSKnownZero(BitWidth, 0);
2401 APInt LHSKnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00002402 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
2403 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewyckyc9610302014-06-19 03:35:49 +00002404 APInt RHSKnownZero(BitWidth, 0);
2405 APInt RHSKnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00002406 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
2407 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewyckyc9610302014-06-19 03:35:49 +00002408 if (((LHSKnownOne & RHSKnownZero) != 0) ||
2409 ((LHSKnownZero & RHSKnownOne) != 0))
2410 return (Pred == ICmpInst::ICMP_EQ)
2411 ? ConstantInt::getFalse(CI->getContext())
2412 : ConstantInt::getTrue(CI->getContext());
2413 }
2414 }
2415
Duncan Sandsd114ab32011-02-13 17:15:40 +00002416 // Special logic for binary operators.
2417 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2418 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2419 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002420 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002421 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002422 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2423 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2424 if (LBO && LBO->getOpcode() == Instruction::Add) {
2425 A = LBO->getOperand(0); B = LBO->getOperand(1);
2426 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2427 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2428 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2429 }
2430 if (RBO && RBO->getOpcode() == Instruction::Add) {
2431 C = RBO->getOperand(0); D = RBO->getOperand(1);
2432 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2433 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2434 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2435 }
2436
2437 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2438 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2439 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2440 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002441 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002442 return V;
2443
2444 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2445 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2446 if (Value *V = SimplifyICmpInst(Pred,
2447 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002448 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002449 return V;
2450
2451 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2452 if (A && C && (A == C || A == D || B == C || B == D) &&
2453 NoLHSWrapProblem && NoRHSWrapProblem) {
2454 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002455 Value *Y, *Z;
2456 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002457 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002458 Y = B;
2459 Z = D;
2460 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002461 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002462 Y = B;
2463 Z = C;
2464 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002465 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002466 Y = A;
2467 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002468 } else {
2469 assert(B == D);
2470 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002471 Y = A;
2472 Z = C;
2473 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002474 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002475 return V;
2476 }
2477 }
2478
David Majnemer2d6c0232014-05-14 20:16:28 +00002479 // 0 - (zext X) pred C
2480 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2481 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2482 if (RHSC->getValue().isStrictlyPositive()) {
2483 if (Pred == ICmpInst::ICMP_SLT)
2484 return ConstantInt::getTrue(RHSC->getContext());
2485 if (Pred == ICmpInst::ICMP_SGE)
2486 return ConstantInt::getFalse(RHSC->getContext());
2487 if (Pred == ICmpInst::ICMP_EQ)
2488 return ConstantInt::getFalse(RHSC->getContext());
2489 if (Pred == ICmpInst::ICMP_NE)
2490 return ConstantInt::getTrue(RHSC->getContext());
2491 }
2492 if (RHSC->getValue().isNonNegative()) {
2493 if (Pred == ICmpInst::ICMP_SLE)
2494 return ConstantInt::getTrue(RHSC->getContext());
2495 if (Pred == ICmpInst::ICMP_SGT)
2496 return ConstantInt::getFalse(RHSC->getContext());
2497 }
2498 }
2499 }
2500
Nick Lewycky35aeea92013-07-12 23:42:57 +00002501 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002502 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002503 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002504 switch (Pred) {
2505 default:
2506 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002507 case ICmpInst::ICMP_SGT:
2508 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00002509 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2510 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002511 if (!KnownNonNegative)
2512 break;
2513 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002514 case ICmpInst::ICMP_EQ:
2515 case ICmpInst::ICMP_UGT:
2516 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002517 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002518 case ICmpInst::ICMP_SLT:
2519 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00002520 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2521 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002522 if (!KnownNonNegative)
2523 break;
2524 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002525 case ICmpInst::ICMP_NE:
2526 case ICmpInst::ICMP_ULT:
2527 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002528 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002529 }
2530 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002531
2532 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002533 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2534 bool KnownNonNegative, KnownNegative;
2535 switch (Pred) {
2536 default:
2537 break;
2538 case ICmpInst::ICMP_SGT:
2539 case ICmpInst::ICMP_SGE:
Hal Finkel60db0582014-09-07 18:57:58 +00002540 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2541 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002542 if (!KnownNonNegative)
2543 break;
2544 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002545 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002546 case ICmpInst::ICMP_UGT:
2547 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002548 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002549 case ICmpInst::ICMP_SLT:
2550 case ICmpInst::ICMP_SLE:
Hal Finkel60db0582014-09-07 18:57:58 +00002551 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2552 0, Q.AT, Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002553 if (!KnownNonNegative)
2554 break;
2555 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002556 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002557 case ICmpInst::ICMP_ULT:
2558 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002559 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002560 }
2561 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002562
Duncan Sands92af0a82011-10-28 18:17:44 +00002563 // x udiv y <=u x.
2564 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2565 // icmp pred (X /u Y), X
2566 if (Pred == ICmpInst::ICMP_UGT)
2567 return getFalse(ITy);
2568 if (Pred == ICmpInst::ICMP_ULE)
2569 return getTrue(ITy);
2570 }
2571
David Majnemer76d06bc2014-08-28 03:34:28 +00002572 // handle:
2573 // CI2 << X == CI
2574 // CI2 << X != CI
2575 //
2576 // where CI2 is a power of 2 and CI isn't
2577 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2578 const APInt *CI2Val, *CIVal = &CI->getValue();
2579 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2580 CI2Val->isPowerOf2()) {
2581 if (!CIVal->isPowerOf2()) {
2582 // CI2 << X can equal zero in some circumstances,
2583 // this simplification is unsafe if CI is zero.
2584 //
2585 // We know it is safe if:
2586 // - The shift is nsw, we can't shift out the one bit.
2587 // - The shift is nuw, we can't shift out the one bit.
2588 // - CI2 is one
2589 // - CI isn't zero
2590 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2591 *CI2Val == 1 || !CI->isZero()) {
2592 if (Pred == ICmpInst::ICMP_EQ)
2593 return ConstantInt::getFalse(RHS->getContext());
2594 if (Pred == ICmpInst::ICMP_NE)
2595 return ConstantInt::getTrue(RHS->getContext());
2596 }
2597 }
2598 if (CIVal->isSignBit() && *CI2Val == 1) {
2599 if (Pred == ICmpInst::ICMP_UGT)
2600 return ConstantInt::getFalse(RHS->getContext());
2601 if (Pred == ICmpInst::ICMP_ULE)
2602 return ConstantInt::getTrue(RHS->getContext());
2603 }
2604 }
2605 }
2606
Nick Lewycky9719a712011-03-05 05:19:11 +00002607 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2608 LBO->getOperand(1) == RBO->getOperand(1)) {
2609 switch (LBO->getOpcode()) {
2610 default: break;
2611 case Instruction::UDiv:
2612 case Instruction::LShr:
2613 if (ICmpInst::isSigned(Pred))
2614 break;
2615 // fall-through
2616 case Instruction::SDiv:
2617 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002618 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002619 break;
2620 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002621 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002622 return V;
2623 break;
2624 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002625 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002626 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2627 if (!NUW && !NSW)
2628 break;
2629 if (!NSW && ICmpInst::isSigned(Pred))
2630 break;
2631 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002632 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002633 return V;
2634 break;
2635 }
2636 }
2637 }
2638
Duncan Sands0a9c1242011-05-03 19:53:10 +00002639 // Simplify comparisons involving max/min.
2640 Value *A, *B;
2641 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002642 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002643
Duncan Sandsa2287852011-05-04 16:05:05 +00002644 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002645 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2646 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002647 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002648 // We analyze this as smax(A, B) pred A.
2649 P = Pred;
2650 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2651 (A == LHS || B == LHS)) {
2652 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002653 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002654 // We analyze this as smax(A, B) swapped-pred A.
2655 P = CmpInst::getSwappedPredicate(Pred);
2656 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2657 (A == RHS || B == RHS)) {
2658 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002659 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002660 // We analyze this as smax(-A, -B) swapped-pred -A.
2661 // Note that we do not need to actually form -A or -B thanks to EqP.
2662 P = CmpInst::getSwappedPredicate(Pred);
2663 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2664 (A == LHS || B == LHS)) {
2665 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002666 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002667 // We analyze this as smax(-A, -B) pred -A.
2668 // Note that we do not need to actually form -A or -B thanks to EqP.
2669 P = Pred;
2670 }
2671 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2672 // Cases correspond to "max(A, B) p A".
2673 switch (P) {
2674 default:
2675 break;
2676 case CmpInst::ICMP_EQ:
2677 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002678 // Equivalent to "A EqP B". This may be the same as the condition tested
2679 // in the max/min; if so, we can just return that.
2680 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2681 return V;
2682 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2683 return V;
2684 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002685 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002686 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002687 return V;
2688 break;
2689 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002690 case CmpInst::ICMP_SGT: {
2691 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2692 // Equivalent to "A InvEqP B". This may be the same as the condition
2693 // tested in the max/min; if so, we can just return that.
2694 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2695 return V;
2696 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2697 return V;
2698 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002699 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002700 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002701 return V;
2702 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002703 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002704 case CmpInst::ICMP_SGE:
2705 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002706 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002707 case CmpInst::ICMP_SLT:
2708 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002709 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002710 }
2711 }
2712
Duncan Sandsa2287852011-05-04 16:05:05 +00002713 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002714 P = CmpInst::BAD_ICMP_PREDICATE;
2715 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2716 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002717 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002718 // We analyze this as umax(A, B) pred A.
2719 P = Pred;
2720 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2721 (A == LHS || B == LHS)) {
2722 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002723 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002724 // We analyze this as umax(A, B) swapped-pred A.
2725 P = CmpInst::getSwappedPredicate(Pred);
2726 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2727 (A == RHS || B == RHS)) {
2728 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002729 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002730 // We analyze this as umax(-A, -B) swapped-pred -A.
2731 // Note that we do not need to actually form -A or -B thanks to EqP.
2732 P = CmpInst::getSwappedPredicate(Pred);
2733 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2734 (A == LHS || B == LHS)) {
2735 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002736 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002737 // We analyze this as umax(-A, -B) pred -A.
2738 // Note that we do not need to actually form -A or -B thanks to EqP.
2739 P = Pred;
2740 }
2741 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2742 // Cases correspond to "max(A, B) p A".
2743 switch (P) {
2744 default:
2745 break;
2746 case CmpInst::ICMP_EQ:
2747 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002748 // Equivalent to "A EqP B". This may be the same as the condition tested
2749 // in the max/min; if so, we can just return that.
2750 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2751 return V;
2752 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2753 return V;
2754 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002755 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002756 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002757 return V;
2758 break;
2759 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002760 case CmpInst::ICMP_UGT: {
2761 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2762 // Equivalent to "A InvEqP B". This may be the same as the condition
2763 // tested in the max/min; if so, we can just return that.
2764 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2765 return V;
2766 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2767 return V;
2768 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002769 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002770 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002771 return V;
2772 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002773 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002774 case CmpInst::ICMP_UGE:
2775 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002776 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002777 case CmpInst::ICMP_ULT:
2778 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002779 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002780 }
2781 }
2782
Duncan Sandsa2287852011-05-04 16:05:05 +00002783 // Variants on "max(x,y) >= min(x,z)".
2784 Value *C, *D;
2785 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2786 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2787 (A == C || A == D || B == C || B == D)) {
2788 // max(x, ?) pred min(x, ?).
2789 if (Pred == CmpInst::ICMP_SGE)
2790 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002791 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002792 if (Pred == CmpInst::ICMP_SLT)
2793 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002794 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002795 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2796 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2797 (A == C || A == D || B == C || B == D)) {
2798 // min(x, ?) pred max(x, ?).
2799 if (Pred == CmpInst::ICMP_SLE)
2800 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002801 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002802 if (Pred == CmpInst::ICMP_SGT)
2803 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002804 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002805 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2806 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2807 (A == C || A == D || B == C || B == D)) {
2808 // max(x, ?) pred min(x, ?).
2809 if (Pred == CmpInst::ICMP_UGE)
2810 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002811 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002812 if (Pred == CmpInst::ICMP_ULT)
2813 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002814 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002815 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2816 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2817 (A == C || A == D || B == C || B == D)) {
2818 // min(x, ?) pred max(x, ?).
2819 if (Pred == CmpInst::ICMP_ULE)
2820 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002821 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002822 if (Pred == CmpInst::ICMP_UGT)
2823 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002824 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002825 }
2826
Chandler Carruth8059c842012-03-25 21:28:14 +00002827 // Simplify comparisons of related pointers using a powerful, recursive
2828 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00002829 if (LHS->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002830 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00002831 return C;
2832
Nick Lewycky3db143e2012-02-26 02:09:49 +00002833 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2834 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2835 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2836 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2837 (ICmpInst::isEquality(Pred) ||
2838 (GLHS->isInBounds() && GRHS->isInBounds() &&
2839 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2840 // The bases are equal and the indices are constant. Build a constant
2841 // expression GEP with the same indices and a null base pointer to see
2842 // what constant folding can make out of it.
2843 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2844 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2845 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2846
2847 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2848 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2849 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2850 }
2851 }
2852 }
2853
Duncan Sandsf532d312010-11-07 16:12:23 +00002854 // If the comparison is with the result of a select instruction, check whether
2855 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002856 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002857 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002858 return V;
2859
2860 // If the comparison is with the result of a phi instruction, check whether
2861 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002862 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002863 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002864 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00002865
Craig Topper9f008862014-04-15 04:59:12 +00002866 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00002867}
2868
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002869Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002870 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002871 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002872 const DominatorTree *DT,
2873 AssumptionTracker *AT,
2874 Instruction *CxtI) {
2875 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002876 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002877}
2878
Chris Lattnerc1f19072009-11-09 23:28:39 +00002879/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2880/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002881static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002882 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002883 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2884 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2885
Chris Lattnera71e9d62009-11-10 00:55:12 +00002886 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002887 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002888 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00002889
Chris Lattnera71e9d62009-11-10 00:55:12 +00002890 // If we have a constant, make sure it is on the RHS.
2891 std::swap(LHS, RHS);
2892 Pred = CmpInst::getSwappedPredicate(Pred);
2893 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002894
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002895 // Fold trivial predicates.
2896 if (Pred == FCmpInst::FCMP_FALSE)
2897 return ConstantInt::get(GetCompareTy(LHS), 0);
2898 if (Pred == FCmpInst::FCMP_TRUE)
2899 return ConstantInt::get(GetCompareTy(LHS), 1);
2900
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002901 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2902 return UndefValue::get(GetCompareTy(LHS));
2903
2904 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00002905 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002906 if (CmpInst::isTrueWhenEqual(Pred))
2907 return ConstantInt::get(GetCompareTy(LHS), 1);
2908 if (CmpInst::isFalseWhenEqual(Pred))
2909 return ConstantInt::get(GetCompareTy(LHS), 0);
2910 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002911
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002912 // Handle fcmp with constant RHS
2913 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2914 // If the constant is a nan, see if we can fold the comparison based on it.
2915 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2916 if (CFP->getValueAPF().isNaN()) {
2917 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2918 return ConstantInt::getFalse(CFP->getContext());
2919 assert(FCmpInst::isUnordered(Pred) &&
2920 "Comparison must be either ordered or unordered!");
2921 // True if unordered.
2922 return ConstantInt::getTrue(CFP->getContext());
2923 }
Dan Gohman754e4a92010-02-22 04:06:03 +00002924 // Check whether the constant is an infinity.
2925 if (CFP->getValueAPF().isInfinity()) {
2926 if (CFP->getValueAPF().isNegative()) {
2927 switch (Pred) {
2928 case FCmpInst::FCMP_OLT:
2929 // No value is ordered and less than negative infinity.
2930 return ConstantInt::getFalse(CFP->getContext());
2931 case FCmpInst::FCMP_UGE:
2932 // All values are unordered with or at least negative infinity.
2933 return ConstantInt::getTrue(CFP->getContext());
2934 default:
2935 break;
2936 }
2937 } else {
2938 switch (Pred) {
2939 case FCmpInst::FCMP_OGT:
2940 // No value is ordered and greater than infinity.
2941 return ConstantInt::getFalse(CFP->getContext());
2942 case FCmpInst::FCMP_ULE:
2943 // All values are unordered with and at most infinity.
2944 return ConstantInt::getTrue(CFP->getContext());
2945 default:
2946 break;
2947 }
2948 }
2949 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002950 }
2951 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002952
Duncan Sandsa620bd12010-11-07 16:46:25 +00002953 // If the comparison is with the result of a select instruction, check whether
2954 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002955 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002956 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002957 return V;
2958
2959 // If the comparison is with the result of a phi instruction, check whether
2960 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002961 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002962 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002963 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00002964
Craig Topper9f008862014-04-15 04:59:12 +00002965 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002966}
2967
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002968Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002969 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002970 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00002971 const DominatorTree *DT,
2972 AssumptionTracker *AT,
2973 const Instruction *CxtI) {
2974 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002975 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002976}
2977
Chris Lattnerc707fa92010-04-20 05:32:14 +00002978/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2979/// the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002980static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2981 Value *FalseVal, const Query &Q,
2982 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00002983 // select true, X, Y -> X
2984 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002985 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2986 if (CB->isAllOnesValue())
2987 return TrueVal;
2988 if (CB->isNullValue())
2989 return FalseVal;
2990 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002991
Chris Lattnerc707fa92010-04-20 05:32:14 +00002992 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00002993 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00002994 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002995
Chris Lattnerc707fa92010-04-20 05:32:14 +00002996 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2997 if (isa<Constant>(TrueVal))
2998 return TrueVal;
2999 return FalseVal;
3000 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003001 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3002 return FalseVal;
3003 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3004 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003005
Craig Topper9f008862014-04-15 04:59:12 +00003006 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003007}
3008
Duncan Sandsb8cee002012-03-13 11:42:19 +00003009Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003010 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003011 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003012 const DominatorTree *DT,
3013 AssumptionTracker *AT,
3014 const Instruction *CxtI) {
3015 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3016 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003017}
3018
Chris Lattner8574aba2009-11-27 00:29:05 +00003019/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
3020/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003021static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003022 // The type of the GEP pointer operand.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003023 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
Nico Weber48c82402014-08-27 20:06:19 +00003024 unsigned AS = PtrTy->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003025
Chris Lattner8574aba2009-11-27 00:29:05 +00003026 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003027 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003028 return Ops[0];
3029
Nico Weber48c82402014-08-27 20:06:19 +00003030 // Compute the (pointer) type returned by the GEP instruction.
3031 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
3032 Type *GEPTy = PointerType::get(LastType, AS);
3033 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3034 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3035
3036 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003037 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003038
Jay Foadb992a632011-07-19 15:07:52 +00003039 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003040 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003041 if (match(Ops[1], m_Zero()))
3042 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003043
3044 Type *Ty = PtrTy->getElementType();
3045 if (Q.DL && Ty->isSized()) {
3046 Value *P;
3047 uint64_t C;
3048 uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
3049 // getelementptr P, N -> P if P points to a type of zero size.
3050 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003051 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003052
3053 // The following transforms are only safe if the ptrtoint cast
3054 // doesn't truncate the pointers.
3055 if (Ops[1]->getType()->getScalarSizeInBits() ==
3056 Q.DL->getPointerSizeInBits(AS)) {
3057 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3058 if (match(P, m_Zero()))
3059 return Constant::getNullValue(GEPTy);
3060 Value *Temp;
3061 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003062 if (Temp->getType() == GEPTy)
3063 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003064 return nullptr;
3065 };
3066
3067 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3068 if (TyAllocSize == 1 &&
3069 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3070 if (Value *R = PtrToIntOrZero(P))
3071 return R;
3072
3073 // getelementptr V, (ashr (sub P, V), C) -> Q
3074 // if P points to a type of size 1 << C.
3075 if (match(Ops[1],
3076 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3077 m_ConstantInt(C))) &&
3078 TyAllocSize == 1ULL << C)
3079 if (Value *R = PtrToIntOrZero(P))
3080 return R;
3081
3082 // getelementptr V, (sdiv (sub P, V), C) -> Q
3083 // if P points to a type of size C.
3084 if (match(Ops[1],
3085 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3086 m_SpecificInt(TyAllocSize))))
3087 if (Value *R = PtrToIntOrZero(P))
3088 return R;
3089 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003090 }
3091 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003092
Chris Lattner8574aba2009-11-27 00:29:05 +00003093 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003094 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003095 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003096 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003097
Jay Foaded8db7d2011-07-21 14:31:17 +00003098 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003099}
3100
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003101Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003102 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003103 const DominatorTree *DT, AssumptionTracker *AT,
3104 const Instruction *CxtI) {
3105 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003106}
3107
Duncan Sandsfd26a952011-09-05 06:52:48 +00003108/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
3109/// can fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003110static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3111 ArrayRef<unsigned> Idxs, const Query &Q,
3112 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003113 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3114 if (Constant *CVal = dyn_cast<Constant>(Val))
3115 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3116
3117 // insertvalue x, undef, n -> x
3118 if (match(Val, m_Undef()))
3119 return Agg;
3120
3121 // insertvalue x, (extractvalue y, n), n
3122 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003123 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3124 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003125 // insertvalue undef, (extractvalue y, n), n -> y
3126 if (match(Agg, m_Undef()))
3127 return EV->getAggregateOperand();
3128
3129 // insertvalue y, (extractvalue y, n), n -> y
3130 if (Agg == EV->getAggregateOperand())
3131 return Agg;
3132 }
3133
Craig Topper9f008862014-04-15 04:59:12 +00003134 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003135}
3136
Duncan Sandsb8cee002012-03-13 11:42:19 +00003137Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3138 ArrayRef<unsigned> Idxs,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003139 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003140 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003141 const DominatorTree *DT,
3142 AssumptionTracker *AT,
3143 const Instruction *CxtI) {
3144 return ::SimplifyInsertValueInst(Agg, Val, Idxs,
3145 Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003146 RecursionLimit);
3147}
3148
Duncan Sands7412f6e2010-11-17 04:30:22 +00003149/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003150static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003151 // If all of the PHI's incoming values are the same then replace the PHI node
3152 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003153 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003154 bool HasUndefInput = false;
3155 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3156 Value *Incoming = PN->getIncomingValue(i);
3157 // If the incoming value is the phi node itself, it can safely be skipped.
3158 if (Incoming == PN) continue;
3159 if (isa<UndefValue>(Incoming)) {
3160 // Remember that we saw an undef value, but otherwise ignore them.
3161 HasUndefInput = true;
3162 continue;
3163 }
3164 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003165 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003166 CommonValue = Incoming;
3167 }
3168
3169 // If CommonValue is null then all of the incoming values were either undef or
3170 // equal to the phi node itself.
3171 if (!CommonValue)
3172 return UndefValue::get(PN->getType());
3173
3174 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3175 // instruction, we cannot return X as the result of the PHI node unless it
3176 // dominates the PHI block.
3177 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003178 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003179
3180 return CommonValue;
3181}
3182
Duncan Sands395ac42d2012-03-13 14:07:05 +00003183static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3184 if (Constant *C = dyn_cast<Constant>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003185 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003186
Craig Topper9f008862014-04-15 04:59:12 +00003187 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00003188}
3189
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003190Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00003191 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003192 const DominatorTree *DT,
3193 AssumptionTracker *AT,
3194 const Instruction *CxtI) {
3195 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
3196 RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003197}
3198
Chris Lattnera71e9d62009-11-10 00:55:12 +00003199//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003200
Chris Lattnera71e9d62009-11-10 00:55:12 +00003201/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
3202/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003203static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003204 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003205 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003206 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003207 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003208 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003209 case Instruction::FAdd:
3210 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3211
Chris Lattner9e4aa022011-02-09 17:15:04 +00003212 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003213 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003214 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003215 case Instruction::FSub:
3216 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3217
Duncan Sandsb8cee002012-03-13 11:42:19 +00003218 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003219 case Instruction::FMul:
3220 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003221 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3222 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3223 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
3224 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3225 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3226 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003227 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003228 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003229 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003230 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003231 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003232 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003233 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3234 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3235 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3236 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003237 default:
3238 if (Constant *CLHS = dyn_cast<Constant>(LHS))
3239 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3240 Constant *COps[] = {CLHS, CRHS};
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003241 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003242 Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003243 }
Duncan Sandsb0579e92010-11-10 13:00:08 +00003244
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003245 // If the operation is associative, try some generic simplifications.
3246 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003247 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003248 return V;
3249
Duncan Sandsb8cee002012-03-13 11:42:19 +00003250 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003251 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003252 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003253 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003254 return V;
3255
3256 // If the operation is with the result of a phi instruction, check whether
3257 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003258 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003259 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003260 return V;
3261
Craig Topper9f008862014-04-15 04:59:12 +00003262 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003263 }
3264}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003265
Duncan Sands7e800d62010-11-14 11:23:23 +00003266Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003267 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003268 const DominatorTree *DT, AssumptionTracker *AT,
3269 const Instruction *CxtI) {
3270 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3271 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003272}
3273
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003274/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3275/// fold the result.
3276static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003277 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003278 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003279 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3280 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003281}
3282
3283Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003284 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003285 const DominatorTree *DT, AssumptionTracker *AT,
3286 const Instruction *CxtI) {
3287 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003288 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003289}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003290
Michael Ilseman54857292013-02-07 19:26:05 +00003291static bool IsIdempotent(Intrinsic::ID ID) {
3292 switch (ID) {
3293 default: return false;
3294
3295 // Unary idempotent: f(f(x)) = f(x)
3296 case Intrinsic::fabs:
3297 case Intrinsic::floor:
3298 case Intrinsic::ceil:
3299 case Intrinsic::trunc:
3300 case Intrinsic::rint:
3301 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003302 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003303 return true;
3304 }
3305}
3306
3307template <typename IterTy>
3308static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3309 const Query &Q, unsigned MaxRecurse) {
3310 // Perform idempotent optimizations
3311 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003312 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003313
3314 // Unary Ops
3315 if (std::distance(ArgBegin, ArgEnd) == 1)
3316 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3317 if (II->getIntrinsicID() == IID)
3318 return II;
3319
Craig Topper9f008862014-04-15 04:59:12 +00003320 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003321}
3322
Chandler Carruth9dc35582012-12-28 11:30:55 +00003323template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003324static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003325 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003326 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003327 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3328 Ty = PTy->getElementType();
3329 FunctionType *FTy = cast<FunctionType>(Ty);
3330
Dan Gohman85977e62011-11-04 18:32:42 +00003331 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003332 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003333 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003334
Chandler Carruthf6182152012-12-28 14:23:29 +00003335 Function *F = dyn_cast<Function>(V);
3336 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00003337 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003338
Michael Ilseman54857292013-02-07 19:26:05 +00003339 if (unsigned IID = F->getIntrinsicID())
3340 if (Value *Ret =
3341 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3342 return Ret;
3343
Chandler Carruthf6182152012-12-28 14:23:29 +00003344 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00003345 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003346
3347 SmallVector<Constant *, 4> ConstantArgs;
3348 ConstantArgs.reserve(ArgEnd - ArgBegin);
3349 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3350 Constant *C = dyn_cast<Constant>(*I);
3351 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00003352 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003353 ConstantArgs.push_back(C);
3354 }
3355
3356 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00003357}
3358
Chandler Carruthf6182152012-12-28 14:23:29 +00003359Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003360 User::op_iterator ArgEnd, const DataLayout *DL,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003361 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003362 const DominatorTree *DT, AssumptionTracker *AT,
3363 const Instruction *CxtI) {
3364 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003365 RecursionLimit);
3366}
3367
Chandler Carruthf6182152012-12-28 14:23:29 +00003368Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003369 const DataLayout *DL, const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003370 const DominatorTree *DT, AssumptionTracker *AT,
3371 const Instruction *CxtI) {
3372 return ::SimplifyCall(V, Args.begin(), Args.end(),
3373 Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00003374}
3375
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003376/// SimplifyInstruction - See if we can compute a simplified version of this
3377/// instruction. If not, this returns null.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003378Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003379 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003380 const DominatorTree *DT,
3381 AssumptionTracker *AT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00003382 Value *Result;
3383
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003384 switch (I->getOpcode()) {
3385 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003386 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003387 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003388 case Instruction::FAdd:
3389 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003390 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003391 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00003392 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003393 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3394 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3395 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003396 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003397 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003398 case Instruction::FSub:
3399 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003400 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003401 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00003402 case Instruction::Sub:
3403 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3404 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3405 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003406 DL, TLI, DT, AT, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00003407 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003408 case Instruction::FMul:
3409 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003410 I->getFastMathFlags(), DL, TLI, DT, AT, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003411 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003412 case Instruction::Mul:
Hal Finkel60db0582014-09-07 18:57:58 +00003413 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
3414 DL, TLI, DT, AT, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003415 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00003416 case Instruction::SDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003417 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
3418 DL, TLI, DT, AT, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00003419 break;
3420 case Instruction::UDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003421 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
3422 DL, TLI, DT, AT, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00003423 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00003424 case Instruction::FDiv:
Hal Finkel60db0582014-09-07 18:57:58 +00003425 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3426 DL, TLI, DT, AT, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00003427 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00003428 case Instruction::SRem:
Hal Finkel60db0582014-09-07 18:57:58 +00003429 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
3430 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003431 break;
3432 case Instruction::URem:
Hal Finkel60db0582014-09-07 18:57:58 +00003433 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
3434 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003435 break;
3436 case Instruction::FRem:
Hal Finkel60db0582014-09-07 18:57:58 +00003437 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3438 DL, TLI, DT, AT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003439 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00003440 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003441 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3442 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3443 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Hal Finkel60db0582014-09-07 18:57:58 +00003444 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003445 break;
3446 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003447 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3448 cast<BinaryOperator>(I)->isExact(),
Hal Finkel60db0582014-09-07 18:57:58 +00003449 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003450 break;
3451 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003452 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3453 cast<BinaryOperator>(I)->isExact(),
Hal Finkel60db0582014-09-07 18:57:58 +00003454 DL, TLI, DT, AT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003455 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003456 case Instruction::And:
Hal Finkel60db0582014-09-07 18:57:58 +00003457 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
3458 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003459 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003460 case Instruction::Or:
Hal Finkel60db0582014-09-07 18:57:58 +00003461 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3462 AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003463 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00003464 case Instruction::Xor:
Hal Finkel60db0582014-09-07 18:57:58 +00003465 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
3466 DL, TLI, DT, AT, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00003467 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003468 case Instruction::ICmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003469 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Hal Finkel60db0582014-09-07 18:57:58 +00003470 I->getOperand(0), I->getOperand(1),
3471 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003472 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003473 case Instruction::FCmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003474 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Hal Finkel60db0582014-09-07 18:57:58 +00003475 I->getOperand(0), I->getOperand(1),
3476 DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003477 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003478 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003479 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Hal Finkel60db0582014-09-07 18:57:58 +00003480 I->getOperand(2), DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003481 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003482 case Instruction::GetElementPtr: {
3483 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Hal Finkel60db0582014-09-07 18:57:58 +00003484 Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003485 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003486 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00003487 case Instruction::InsertValue: {
3488 InsertValueInst *IV = cast<InsertValueInst>(I);
3489 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3490 IV->getInsertedValueOperand(),
Hal Finkel60db0582014-09-07 18:57:58 +00003491 IV->getIndices(), DL, TLI, DT, AT, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00003492 break;
3493 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00003494 case Instruction::PHI:
Hal Finkel60db0582014-09-07 18:57:58 +00003495 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00003496 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003497 case Instruction::Call: {
3498 CallSite CS(cast<CallInst>(I));
3499 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
Hal Finkel60db0582014-09-07 18:57:58 +00003500 DL, TLI, DT, AT, I);
Dan Gohman85977e62011-11-04 18:32:42 +00003501 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003502 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00003503 case Instruction::Trunc:
Hal Finkel60db0582014-09-07 18:57:58 +00003504 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
3505 AT, I);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003506 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003507 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00003508
3509 /// If called on unreachable code, the above logic may report that the
3510 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00003511 /// detecting that case here, returning a safe value instead.
3512 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003513}
3514
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003515/// \brief Implementation of recursive simplification through an instructions
3516/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00003517///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003518/// This is the common implementation of the recursive simplification routines.
3519/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3520/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3521/// instructions to process and attempt to simplify it using
3522/// InstructionSimplify.
3523///
3524/// This routine returns 'true' only when *it* simplifies something. The passed
3525/// in simplified value does not count toward this.
3526static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003527 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003528 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003529 const DominatorTree *DT,
3530 AssumptionTracker *AT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003531 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003532 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands7e800d62010-11-14 11:23:23 +00003533
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003534 // If we have an explicit value to collapse to, do that round of the
3535 // simplification loop by hand initially.
3536 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003537 for (User *U : I->users())
3538 if (U != I)
3539 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00003540
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003541 // Replace the instruction with its simplified value.
3542 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00003543
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003544 // Gracefully handle edge cases where the instruction is not wired into any
3545 // parent block.
3546 if (I->getParent())
3547 I->eraseFromParent();
3548 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003549 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00003550 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003551
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003552 // Note that we must test the size on each iteration, the worklist can grow.
3553 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3554 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00003555
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003556 // See if this instruction simplifies.
Hal Finkel60db0582014-09-07 18:57:58 +00003557 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003558 if (!SimpleV)
3559 continue;
3560
3561 Simplified = true;
3562
3563 // Stash away all the uses of the old instruction so we can check them for
3564 // recursive simplifications after a RAUW. This is cheaper than checking all
3565 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003566 for (User *U : I->users())
3567 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003568
3569 // Replace the instruction with its simplified value.
3570 I->replaceAllUsesWith(SimpleV);
3571
3572 // Gracefully handle edge cases where the instruction is not wired into any
3573 // parent block.
3574 if (I->getParent())
3575 I->eraseFromParent();
3576 }
3577 return Simplified;
3578}
3579
3580bool llvm::recursivelySimplifyInstruction(Instruction *I,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003581 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003582 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003583 const DominatorTree *DT,
3584 AssumptionTracker *AT) {
3585 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003586}
3587
3588bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003589 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003590 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00003591 const DominatorTree *DT,
3592 AssumptionTracker *AT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003593 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3594 assert(SimpleV && "Must provide a simplified value.");
Hal Finkel60db0582014-09-07 18:57:58 +00003595 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);
Chris Lattner852d6d62009-11-10 22:26:15 +00003596}