blob: 3684fda854fc49cd43b0650df79603fa377f8a9f [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");
42STATISTIC(NumFactor , "Number of factorizations");
43STATISTIC(NumReassoc, "Number of reassociations");
44
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;
49
Rafael Espindola37dc9e12014-02-21 00:06:31 +000050 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
51 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000052};
53
54static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
55static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000056 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000057static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000058 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000059static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
60static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000061static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000062
Duncan Sandsc1c92712011-07-26 15:03:53 +000063/// getFalse - For a boolean type, or a vector of boolean type, return false, or
64/// a vector with every element false, as appropriate for the type.
65static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000066 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000067 "Expected i1 type or a vector of i1!");
68 return Constant::getNullValue(Ty);
69}
70
71/// getTrue - For a boolean type, or a vector of boolean type, return true, or
72/// a vector with every element true, as appropriate for the type.
73static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000074 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000075 "Expected i1 type or a vector of i1!");
76 return Constant::getAllOnesValue(Ty);
77}
78
Duncan Sands3d5692a2011-10-30 19:56:36 +000079/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
80static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
81 Value *RHS) {
82 CmpInst *Cmp = dyn_cast<CmpInst>(V);
83 if (!Cmp)
84 return false;
85 CmpInst::Predicate CPred = Cmp->getPredicate();
86 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
87 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
88 return true;
89 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
90 CRHS == LHS;
91}
92
Duncan Sands5ffc2982010-11-16 12:16:38 +000093/// ValueDominatesPHI - Does the given value dominate the specified phi node?
94static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
95 Instruction *I = dyn_cast<Instruction>(V);
96 if (!I)
97 // Arguments and constants dominate all instructions.
98 return true;
99
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000100 // If we are processing instructions (and/or basic blocks) that have not been
101 // fully added to a function, the parent nodes may still be null. Simply
102 // return the conservative answer in these cases.
103 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
104 return false;
105
Duncan Sands5ffc2982010-11-16 12:16:38 +0000106 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000107 if (DT) {
108 if (!DT->isReachableFromEntry(P->getParent()))
109 return true;
110 if (!DT->isReachableFromEntry(I->getParent()))
111 return false;
112 return DT->dominates(I, P);
113 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000114
115 // Otherwise, if the instruction is in the entry block, and is not an invoke,
116 // then it obviously dominates all phi nodes.
117 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
118 !isa<InvokeInst>(I))
119 return true;
120
121 return false;
122}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000123
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000124/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
125/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
126/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
127/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
128/// Returns the simplified value, or null if no simplification was performed.
129static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000130 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000131 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000132 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000133 // Recursion is always used, so bail out at once if we already hit the limit.
134 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000135 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000136
137 // Check whether the expression has the form "(A op' B) op C".
138 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
139 if (Op0->getOpcode() == OpcodeToExpand) {
140 // It does! Try turning it into "(A op C) op' (B op C)".
141 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
142 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000143 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
144 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000145 // They do! Return "L op' R" if it simplifies or is already available.
146 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000147 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
148 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000149 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000150 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000151 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000152 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000153 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000154 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000155 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000156 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000157 }
158 }
159
160 // Check whether the expression has the form "A op (B op' C)".
161 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
162 if (Op1->getOpcode() == OpcodeToExpand) {
163 // It does! Try turning it into "(A op B) op' (A op C)".
164 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
165 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000166 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
167 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000168 // They do! Return "L op' R" if it simplifies or is already available.
169 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000170 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
171 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000172 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000173 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000174 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000175 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000176 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000177 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000178 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000179 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000180 }
181 }
182
Craig Topper9f008862014-04-15 04:59:12 +0000183 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000184}
185
186/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
187/// using the operation OpCodeToExtract. For example, when Opcode is Add and
188/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
189/// Returns the simplified value, or null if no simplification was performed.
190static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000191 unsigned OpcToExtract, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000192 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000193 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000194 // Recursion is always used, so bail out at once if we already hit the limit.
195 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000196 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000197
198 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
199 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
200
201 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
202 !Op1 || Op1->getOpcode() != OpcodeToExtract)
Craig Topper9f008862014-04-15 04:59:12 +0000203 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000204
205 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000206 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
207 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000208
209 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
210 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
211 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands772749a2011-01-01 20:08:02 +0000212 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
213 Value *DD = A == C ? D : C;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000214 // Form "A op' (B op DD)" if it simplifies completely.
215 // Does "B op DD" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000216 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000217 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sandsa45cfbd2010-12-22 17:15:25 +0000218 // If V equals B then "A op' V" is just the LHS. If V equals DD then
219 // "A op' V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000220 if (V == B || V == DD) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000221 ++NumFactor;
Duncan Sands772749a2011-01-01 20:08:02 +0000222 return V == B ? LHS : RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000223 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000224 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000225 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000226 ++NumFactor;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000227 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000228 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000229 }
230 }
231
232 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
233 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
234 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands772749a2011-01-01 20:08:02 +0000235 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
236 Value *CC = B == D ? C : D;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000237 // Form "(A op CC) op' B" if it simplifies completely..
238 // Does "A op CC" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000239 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000240 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sandsa45cfbd2010-12-22 17:15:25 +0000241 // If V equals A then "V op' B" is just the LHS. If V equals CC then
242 // "V op' B" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000243 if (V == A || V == CC) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000244 ++NumFactor;
Duncan Sands772749a2011-01-01 20:08:02 +0000245 return V == A ? LHS : RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000246 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000247 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000248 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000249 ++NumFactor;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000250 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000251 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000252 }
253 }
254
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000256}
257
258/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
259/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000260static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000261 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000262 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000263 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
264
265 // Recursion is always used, so bail out at once if we already hit the limit.
266 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000267 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268
269 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
270 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
271
272 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
273 if (Op0 && Op0->getOpcode() == Opcode) {
274 Value *A = Op0->getOperand(0);
275 Value *B = Op0->getOperand(1);
276 Value *C = RHS;
277
278 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000279 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280 // It does! Return "A op V" if it simplifies or is already available.
281 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000282 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000284 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000285 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000287 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000288 }
289 }
290
291 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
292 if (Op1 && Op1->getOpcode() == Opcode) {
293 Value *A = LHS;
294 Value *B = Op1->getOperand(0);
295 Value *C = Op1->getOperand(1);
296
297 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000298 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000299 // It does! Return "V op C" if it simplifies or is already available.
300 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000301 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000302 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000303 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000304 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000305 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000306 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000307 }
308 }
309
310 // The remaining transforms require commutativity as well as associativity.
311 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000312 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000313
314 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
315 if (Op0 && Op0->getOpcode() == Opcode) {
316 Value *A = Op0->getOperand(0);
317 Value *B = Op0->getOperand(1);
318 Value *C = RHS;
319
320 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000321 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000322 // It does! Return "V op B" if it simplifies or is already available.
323 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000324 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000325 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000326 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000327 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000328 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000329 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000330 }
331 }
332
333 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
334 if (Op1 && Op1->getOpcode() == Opcode) {
335 Value *A = LHS;
336 Value *B = Op1->getOperand(0);
337 Value *C = Op1->getOperand(1);
338
339 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000340 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000341 // It does! Return "B op V" if it simplifies or is already available.
342 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000343 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000344 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000345 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000346 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000347 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000348 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000349 }
350 }
351
Craig Topper9f008862014-04-15 04:59:12 +0000352 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000353}
354
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355/// ThreadBinOpOverSelect - In the case of a binary operation with a select
356/// instruction as an operand, try to simplify the binop by seeing whether
357/// evaluating it on both branches of the select results in the same value.
358/// Returns the common value if so, otherwise returns null.
359static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000360 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000361 // Recursion is always used, so bail out at once if we already hit the limit.
362 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000364
Duncan Sandsb0579e92010-11-10 13:00:08 +0000365 SelectInst *SI;
366 if (isa<SelectInst>(LHS)) {
367 SI = cast<SelectInst>(LHS);
368 } else {
369 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
370 SI = cast<SelectInst>(RHS);
371 }
372
373 // Evaluate the BinOp on the true and false branches of the select.
374 Value *TV;
375 Value *FV;
376 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000377 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
378 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000379 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000380 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
381 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000382 }
383
Duncan Sandse3c53952011-01-01 16:12:09 +0000384 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000385 // If they both failed to simplify then return null.
386 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000387 return TV;
388
389 // If one branch simplified to undef, return the other one.
390 if (TV && isa<UndefValue>(TV))
391 return FV;
392 if (FV && isa<UndefValue>(FV))
393 return TV;
394
395 // If applying the operation did not change the true and false select values,
396 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000397 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000398 return SI;
399
400 // If one branch simplified and the other did not, and the simplified
401 // value is equal to the unsimplified one, return the simplified value.
402 // For example, select (cond, X, X & Z) & Z -> X & Z.
403 if ((FV && !TV) || (TV && !FV)) {
404 // Check that the simplified value has the form "X op Y" where "op" is the
405 // same as the original operation.
406 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
407 if (Simplified && Simplified->getOpcode() == Opcode) {
408 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
409 // We already know that "op" is the same as for the simplified value. See
410 // if the operands match too. If so, return the simplified value.
411 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
412 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
413 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000414 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
415 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000416 return Simplified;
417 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000418 Simplified->getOperand(1) == UnsimplifiedLHS &&
419 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000420 return Simplified;
421 }
422 }
423
Craig Topper9f008862014-04-15 04:59:12 +0000424 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000425}
426
427/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
428/// try to simplify the comparison by seeing whether both branches of the select
429/// result in the same value. Returns the common value if so, otherwise returns
430/// null.
431static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000432 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000433 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000434 // Recursion is always used, so bail out at once if we already hit the limit.
435 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000436 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000437
Duncan Sandsb0579e92010-11-10 13:00:08 +0000438 // Make sure the select is on the LHS.
439 if (!isa<SelectInst>(LHS)) {
440 std::swap(LHS, RHS);
441 Pred = CmpInst::getSwappedPredicate(Pred);
442 }
443 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
444 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000445 Value *Cond = SI->getCondition();
446 Value *TV = SI->getTrueValue();
447 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000448
Duncan Sands06504022011-02-03 09:37:39 +0000449 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000450 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000451 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000452 if (TCmp == Cond) {
453 // It not only simplified, it simplified to the select condition. Replace
454 // it with 'true'.
455 TCmp = getTrue(Cond->getType());
456 } else if (!TCmp) {
457 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
458 // condition then we can replace it with 'true'. Otherwise give up.
459 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000460 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000461 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000462 }
463
Duncan Sands3d5692a2011-10-30 19:56:36 +0000464 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000465 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000466 if (FCmp == Cond) {
467 // It not only simplified, it simplified to the select condition. Replace
468 // it with 'false'.
469 FCmp = getFalse(Cond->getType());
470 } else if (!FCmp) {
471 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
472 // condition then we can replace it with 'false'. Otherwise give up.
473 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000474 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000475 FCmp = getFalse(Cond->getType());
476 }
477
478 // If both sides simplified to the same value, then use it as the result of
479 // the original comparison.
480 if (TCmp == FCmp)
481 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000482
483 // The remaining cases only make sense if the select condition has the same
484 // type as the result of the comparison, so bail out if this is not so.
485 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000486 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000487 // If the false value simplified to false, then the result of the compare
488 // is equal to "Cond && TCmp". This also catches the case when the false
489 // value simplified to false and the true value to true, returning "Cond".
490 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000491 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000492 return V;
493 // If the true value simplified to true, then the result of the compare
494 // is equal to "Cond || FCmp".
495 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000496 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000497 return V;
498 // Finally, if the false value simplified to true and the true value to
499 // false, then the result of the compare is equal to "!Cond".
500 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
501 if (Value *V =
502 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000503 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000504 return V;
505
Craig Topper9f008862014-04-15 04:59:12 +0000506 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000507}
508
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000509/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
510/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
511/// it on the incoming phi values yields the same result for every value. If so
512/// returns the common value, otherwise returns null.
513static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000514 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000515 // Recursion is always used, so bail out at once if we already hit the limit.
516 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000517 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000518
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000519 PHINode *PI;
520 if (isa<PHINode>(LHS)) {
521 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000522 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000523 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000524 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000525 } else {
526 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
527 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000528 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000529 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000530 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000531 }
532
533 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000534 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000535 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000536 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000537 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000538 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000539 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000540 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
541 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000542 // If the operation failed to simplify, or simplified to a different value
543 // to previously, then give up.
544 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000545 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000546 CommonValue = V;
547 }
548
549 return CommonValue;
550}
551
552/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
553/// try to simplify the comparison by seeing whether comparing with all of the
554/// incoming phi values yields the same result every time. If so returns the
555/// common result, otherwise returns null.
556static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000557 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000558 // Recursion is always used, so bail out at once if we already hit the limit.
559 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000560 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000561
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000562 // Make sure the phi is on the LHS.
563 if (!isa<PHINode>(LHS)) {
564 std::swap(LHS, RHS);
565 Pred = CmpInst::getSwappedPredicate(Pred);
566 }
567 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
568 PHINode *PI = cast<PHINode>(LHS);
569
Duncan Sands5ffc2982010-11-16 12:16:38 +0000570 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000571 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000572 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000573
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000574 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000575 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000576 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000577 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000578 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000579 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000580 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000581 // If the operation failed to simplify, or simplified to a different value
582 // to previously, then give up.
583 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000584 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000585 CommonValue = V;
586 }
587
588 return CommonValue;
589}
590
Chris Lattner3d9823b2009-11-27 17:42:22 +0000591/// SimplifyAddInst - Given operands for an Add, see if we can
592/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000593static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000594 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000595 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
596 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
597 Constant *Ops[] = { CLHS, CRHS };
Duncan Sandsb8cee002012-03-13 11:42:19 +0000598 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000599 Q.DL, Q.TLI);
Chris Lattner3d9823b2009-11-27 17:42:22 +0000600 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000601
Chris Lattner3d9823b2009-11-27 17:42:22 +0000602 // Canonicalize the constant to the RHS.
603 std::swap(Op0, Op1);
604 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000605
Duncan Sands0a2c41682010-12-15 14:07:39 +0000606 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000607 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000608 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000609
Duncan Sands0a2c41682010-12-15 14:07:39 +0000610 // X + 0 -> X
611 if (match(Op1, m_Zero()))
612 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000613
Duncan Sands0a2c41682010-12-15 14:07:39 +0000614 // X + (Y - X) -> Y
615 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000616 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000617 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000618 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
619 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000620 return Y;
621
622 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000623 if (match(Op0, m_Not(m_Specific(Op1))) ||
624 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000625 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000626
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000627 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000628 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000629 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000630 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000631
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000632 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000633 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000634 MaxRecurse))
635 return V;
636
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000637 // Mul distributes over Add. Try some generic simplifications based on this.
638 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000639 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000640 return V;
641
Duncan Sandsb238de02010-11-19 09:20:39 +0000642 // Threading Add over selects and phi nodes is pointless, so don't bother.
643 // Threading over the select in "A + select(cond, B, C)" means evaluating
644 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
645 // only if B and C are equal. If B and C are equal then (since we assume
646 // that operands have already been simplified) "select(cond, B, C)" should
647 // have been simplified to the common value of B and C already. Analysing
648 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
649 // for threading over phi nodes.
650
Craig Topper9f008862014-04-15 04:59:12 +0000651 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000652}
653
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000654Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000655 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000656 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000657 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000658 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000659}
660
Chandler Carrutha0796552012-03-12 11:19:31 +0000661/// \brief Compute the base pointer and cumulative constant offsets for V.
662///
663/// This strips all constant offsets off of V, leaving it the base pointer, and
664/// accumulates the total constant offset applied in the returned constant. It
665/// returns 0 if V is not a pointer, and returns the constant '0' if there are
666/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000667///
668/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
669/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
670/// folding.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000671static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000672 Value *&V,
673 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000674 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000675
Dan Gohman18c77a12013-01-31 02:50:36 +0000676 // Without DataLayout, just be conservative for now. Theoretically, more could
677 // be done in this case.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000678 if (!DL)
Dan Gohman18c77a12013-01-31 02:50:36 +0000679 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
680
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000681 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000682 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000683
684 // Even though we don't look through PHI nodes, we could be called on an
685 // instruction in an unreachable block, which may be on a cycle.
686 SmallPtrSet<Value *, 4> Visited;
687 Visited.insert(V);
688 do {
689 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000690 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000691 !GEP->accumulateConstantOffset(*DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000692 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000693 V = GEP->getPointerOperand();
694 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000695 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000696 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
697 if (GA->mayBeOverridden())
698 break;
699 V = GA->getAliasee();
700 } else {
701 break;
702 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000703 assert(V->getType()->getScalarType()->isPointerTy() &&
704 "Unexpected operand type!");
Chandler Carrutha0796552012-03-12 11:19:31 +0000705 } while (Visited.insert(V));
706
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000707 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
708 if (V->getType()->isVectorTy())
709 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
710 OffsetIntPtr);
711 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000712}
713
714/// \brief Compute the constant difference between two pointer values.
715/// If the difference is not a constant, returns zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000716static Constant *computePointerDifference(const DataLayout *DL,
Chandler Carrutha0796552012-03-12 11:19:31 +0000717 Value *LHS, Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000718 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
719 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000720
721 // If LHS and RHS are not related via constant offsets to the same base
722 // value, there is nothing we can do here.
723 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000724 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000725
726 // Otherwise, the difference of LHS - RHS can be computed as:
727 // LHS - RHS
728 // = (LHSOffset + Base) - (RHSOffset + Base)
729 // = LHSOffset - RHSOffset
730 return ConstantExpr::getSub(LHSOffset, RHSOffset);
731}
732
Duncan Sands0a2c41682010-12-15 14:07:39 +0000733/// SimplifySubInst - Given operands for a Sub, see if we can
734/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000735static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000736 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000737 if (Constant *CLHS = dyn_cast<Constant>(Op0))
738 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
739 Constant *Ops[] = { CLHS, CRHS };
740 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000741 Ops, Q.DL, Q.TLI);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000742 }
743
744 // X - undef -> undef
745 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000746 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000747 return UndefValue::get(Op0->getType());
748
749 // X - 0 -> X
750 if (match(Op1, m_Zero()))
751 return Op0;
752
753 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000754 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000755 return Constant::getNullValue(Op0->getType());
756
Duncan Sands9b8e2bd2011-01-18 09:24:58 +0000757 // (X*2) - X -> X
758 // (X<<1) - X -> X
Craig Topper9f008862014-04-15 04:59:12 +0000759 Value *X = nullptr;
Duncan Sands9b8e2bd2011-01-18 09:24:58 +0000760 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
761 match(Op0, m_Shl(m_Specific(Op1), m_One())))
762 return Op1;
763
Duncan Sands99589d02011-01-18 11:50:19 +0000764 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
765 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Craig Topper9f008862014-04-15 04:59:12 +0000766 Value *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000767 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
768 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000769 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000770 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000771 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000772 // It does, we successfully reassociated!
773 ++NumReassoc;
774 return W;
775 }
776 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000777 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000778 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000779 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000780 // It does, we successfully reassociated!
781 ++NumReassoc;
782 return W;
783 }
784 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000785
Duncan Sands99589d02011-01-18 11:50:19 +0000786 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
787 // For example, X - (X + 1) -> -1
788 X = Op0;
789 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
790 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000791 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000792 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000793 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000794 // It does, we successfully reassociated!
795 ++NumReassoc;
796 return W;
797 }
798 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000799 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000800 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000801 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000802 // It does, we successfully reassociated!
803 ++NumReassoc;
804 return W;
805 }
806 }
807
808 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
809 // For example, X - (X - Y) -> Y.
810 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000811 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
812 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000813 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000814 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000815 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000816 // It does, we successfully reassociated!
817 ++NumReassoc;
818 return W;
819 }
820
Duncan Sands395ac42d2012-03-13 14:07:05 +0000821 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
822 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
823 match(Op1, m_Trunc(m_Value(Y))))
824 if (X->getType() == Y->getType())
825 // See if "V === X - Y" simplifies.
826 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
827 // It does! Now see if "trunc V" simplifies.
828 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
829 // It does, return the simplified "trunc V".
830 return W;
831
832 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000833 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000834 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000835 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000836 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
837
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000838 // Mul distributes over Sub. Try some generic simplifications based on this.
839 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000840 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000841 return V;
842
Duncan Sands99589d02011-01-18 11:50:19 +0000843 // i1 sub -> xor.
844 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000845 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000846 return V;
847
Duncan Sands0a2c41682010-12-15 14:07:39 +0000848 // Threading Sub over selects and phi nodes is pointless, so don't bother.
849 // Threading over the select in "A - select(cond, B, C)" means evaluating
850 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
851 // only if B and C are equal. If B and C are equal then (since we assume
852 // that operands have already been simplified) "select(cond, B, C)" should
853 // have been simplified to the common value of B and C already. Analysing
854 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
855 // for threading over phi nodes.
856
Craig Topper9f008862014-04-15 04:59:12 +0000857 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000858}
859
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000860Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000861 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000862 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000863 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000864 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000865}
866
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000867/// Given operands for an FAdd, see if we can fold the result. If not, this
868/// returns null.
869static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
870 const Query &Q, unsigned MaxRecurse) {
871 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
872 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
873 Constant *Ops[] = { CLHS, CRHS };
874 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000875 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000876 }
877
878 // Canonicalize the constant to the RHS.
879 std::swap(Op0, Op1);
880 }
881
882 // fadd X, -0 ==> X
883 if (match(Op1, m_NegZero()))
884 return Op0;
885
886 // fadd X, 0 ==> X, when we know X is not -0
887 if (match(Op1, m_Zero()) &&
888 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
889 return Op0;
890
891 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
892 // where nnan and ninf have to occur at least once somewhere in this
893 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000894 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000895 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
896 SubOp = Op1;
897 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
898 SubOp = Op0;
899 if (SubOp) {
900 Instruction *FSub = cast<Instruction>(SubOp);
901 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
902 (FMF.noInfs() || FSub->hasNoInfs()))
903 return Constant::getNullValue(Op0->getType());
904 }
905
Craig Topper9f008862014-04-15 04:59:12 +0000906 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000907}
908
909/// Given operands for an FSub, see if we can fold the result. If not, this
910/// returns null.
911static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
912 const Query &Q, unsigned MaxRecurse) {
913 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
914 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
915 Constant *Ops[] = { CLHS, CRHS };
916 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000917 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000918 }
919 }
920
921 // fsub X, 0 ==> X
922 if (match(Op1, m_Zero()))
923 return Op0;
924
925 // fsub X, -0 ==> X, when we know X is not -0
926 if (match(Op1, m_NegZero()) &&
927 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
928 return Op0;
929
930 // fsub 0, (fsub -0.0, X) ==> X
931 Value *X;
932 if (match(Op0, m_AnyZero())) {
933 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
934 return X;
935 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
936 return X;
937 }
938
939 // fsub nnan ninf x, x ==> 0.0
940 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
941 return Constant::getNullValue(Op0->getType());
942
Craig Topper9f008862014-04-15 04:59:12 +0000943 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000944}
945
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000946/// Given the operands for an FMul, see if we can fold the result
947static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
948 FastMathFlags FMF,
949 const Query &Q,
950 unsigned MaxRecurse) {
951 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
952 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
953 Constant *Ops[] = { CLHS, CRHS };
954 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000955 Ops, Q.DL, Q.TLI);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000956 }
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000957
958 // Canonicalize the constant to the RHS.
959 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000960 }
961
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000962 // fmul X, 1.0 ==> X
963 if (match(Op1, m_FPOne()))
964 return Op0;
965
966 // fmul nnan nsz X, 0 ==> 0
967 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
968 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000969
Craig Topper9f008862014-04-15 04:59:12 +0000970 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000971}
972
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000973/// SimplifyMulInst - Given operands for a Mul, see if we can
974/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000975static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
976 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000977 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
978 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
979 Constant *Ops[] = { CLHS, CRHS };
980 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000981 Ops, Q.DL, Q.TLI);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000982 }
983
984 // Canonicalize the constant to the RHS.
985 std::swap(Op0, Op1);
986 }
987
988 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000989 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000990 return Constant::getNullValue(Op0->getType());
991
992 // X * 0 -> 0
993 if (match(Op1, m_Zero()))
994 return Op1;
995
996 // X * 1 -> X
997 if (match(Op1, m_One()))
998 return Op0;
999
Duncan Sandsb67edc62011-01-30 18:03:50 +00001000 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +00001001 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001002 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1003 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
1004 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +00001005
Nick Lewyckyb89d9a42011-01-29 19:55:23 +00001006 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +00001007 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001008 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +00001009 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001010
1011 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001012 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001013 MaxRecurse))
1014 return V;
1015
1016 // Mul distributes over Add. Try some generic simplifications based on this.
1017 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001018 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001019 return V;
1020
1021 // If the operation is with the result of a select instruction, check whether
1022 // operating on either branch of the select always yields the same value.
1023 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001024 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001025 MaxRecurse))
1026 return V;
1027
1028 // If the operation is with the result of a phi instruction, check whether
1029 // operating on all incoming values of the phi always yields the same value.
1030 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001031 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001032 MaxRecurse))
1033 return V;
1034
Craig Topper9f008862014-04-15 04:59:12 +00001035 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001036}
1037
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001038Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001039 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001040 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001041 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001042}
1043
1044Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001045 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001046 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001047 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001048}
1049
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001050Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1051 FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001052 const DataLayout *DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001053 const TargetLibraryInfo *TLI,
1054 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001055 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001056}
1057
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001058Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001059 const TargetLibraryInfo *TLI,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001060 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001061 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001062}
1063
Duncan Sands771e82a2011-01-28 16:51:11 +00001064/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1065/// fold the result. If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001066static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001067 const Query &Q, unsigned MaxRecurse) {
Duncan Sands771e82a2011-01-28 16:51:11 +00001068 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1069 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1070 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001071 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands771e82a2011-01-28 16:51:11 +00001072 }
1073 }
1074
Duncan Sands65995fa2011-01-28 18:50:50 +00001075 bool isSigned = Opcode == Instruction::SDiv;
1076
Duncan Sands771e82a2011-01-28 16:51:11 +00001077 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001078 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001079 return Op1;
1080
1081 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001082 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001083 return Constant::getNullValue(Op0->getType());
1084
1085 // 0 / X -> 0, we don't need to preserve faults!
1086 if (match(Op0, m_Zero()))
1087 return Op0;
1088
1089 // X / 1 -> X
1090 if (match(Op1, m_One()))
1091 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001092
1093 if (Op0->getType()->isIntegerTy(1))
1094 // It can't be division by zero, hence it must be division by one.
1095 return Op0;
1096
1097 // X / X -> 1
1098 if (Op0 == Op1)
1099 return ConstantInt::get(Op0->getType(), 1);
1100
1101 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001102 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001103 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1104 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001105 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001106 // If the Mul knows it does not overflow, then we are good to go.
1107 if ((isSigned && Mul->hasNoSignedWrap()) ||
1108 (!isSigned && Mul->hasNoUnsignedWrap()))
1109 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001110 // If X has the form X = A / Y then X * Y cannot overflow.
1111 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1112 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1113 return X;
1114 }
1115
Duncan Sands65995fa2011-01-28 18:50:50 +00001116 // (X rem Y) / Y -> 0
1117 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1118 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1119 return Constant::getNullValue(Op0->getType());
1120
1121 // If the operation is with the result of a select instruction, check whether
1122 // operating on either branch of the select always yields the same value.
1123 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001124 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001125 return V;
1126
1127 // If the operation is with the result of a phi instruction, check whether
1128 // operating on all incoming values of the phi always yields the same value.
1129 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001130 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001131 return V;
1132
Craig Topper9f008862014-04-15 04:59:12 +00001133 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001134}
1135
1136/// SimplifySDivInst - Given operands for an SDiv, see if we can
1137/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001138static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1139 unsigned MaxRecurse) {
1140 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001141 return V;
1142
Craig Topper9f008862014-04-15 04:59:12 +00001143 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001144}
1145
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001146Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001147 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001148 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001149 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001150}
1151
1152/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1153/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001154static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1155 unsigned MaxRecurse) {
1156 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001157 return V;
1158
Craig Topper9f008862014-04-15 04:59:12 +00001159 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001160}
1161
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001162Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001163 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001164 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001165 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001166}
1167
Duncan Sandsb8cee002012-03-13 11:42:19 +00001168static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1169 unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001170 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001171 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001172 return Op0;
1173
1174 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001175 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001176 return Op1;
1177
Craig Topper9f008862014-04-15 04:59:12 +00001178 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001179}
1180
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001181Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001182 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001183 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001184 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001185}
1186
Duncan Sandsa3e36992011-05-02 16:27:02 +00001187/// SimplifyRem - Given operands for an SRem or URem, see if we can
1188/// fold the result. If not, this returns null.
1189static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001190 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001191 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1192 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1193 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001194 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001195 }
1196 }
1197
Duncan Sandsa3e36992011-05-02 16:27:02 +00001198 // X % undef -> undef
1199 if (match(Op1, m_Undef()))
1200 return Op1;
1201
1202 // undef % X -> 0
1203 if (match(Op0, m_Undef()))
1204 return Constant::getNullValue(Op0->getType());
1205
1206 // 0 % X -> 0, we don't need to preserve faults!
1207 if (match(Op0, m_Zero()))
1208 return Op0;
1209
1210 // X % 0 -> undef, we don't need to preserve faults!
1211 if (match(Op1, m_Zero()))
1212 return UndefValue::get(Op0->getType());
1213
1214 // X % 1 -> 0
1215 if (match(Op1, m_One()))
1216 return Constant::getNullValue(Op0->getType());
1217
1218 if (Op0->getType()->isIntegerTy(1))
1219 // It can't be remainder by zero, hence it must be remainder by one.
1220 return Constant::getNullValue(Op0->getType());
1221
1222 // X % X -> 0
1223 if (Op0 == Op1)
1224 return Constant::getNullValue(Op0->getType());
1225
1226 // If the operation is with the result of a select instruction, check whether
1227 // operating on either branch of the select always yields the same value.
1228 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001229 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230 return V;
1231
1232 // If the operation is with the result of a phi instruction, check whether
1233 // operating on all incoming values of the phi always yields the same value.
1234 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001235 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001236 return V;
1237
Craig Topper9f008862014-04-15 04:59:12 +00001238 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001239}
1240
1241/// SimplifySRemInst - Given operands for an SRem, see if we can
1242/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001243static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1244 unsigned MaxRecurse) {
1245 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001246 return V;
1247
Craig Topper9f008862014-04-15 04:59:12 +00001248 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001249}
1250
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001251Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001252 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001253 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001254 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001255}
1256
1257/// SimplifyURemInst - Given operands for a URem, see if we can
1258/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001259static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001260 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001261 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001262 return V;
1263
Craig Topper9f008862014-04-15 04:59:12 +00001264 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001265}
1266
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001267Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001268 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001269 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001270 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001271}
1272
Duncan Sandsb8cee002012-03-13 11:42:19 +00001273static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001274 unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001275 // undef % X -> undef (the undef could be a snan).
1276 if (match(Op0, m_Undef()))
1277 return Op0;
1278
1279 // X % undef -> undef
1280 if (match(Op1, m_Undef()))
1281 return Op1;
1282
Craig Topper9f008862014-04-15 04:59:12 +00001283 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001284}
1285
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001286Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001287 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001288 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001289 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001290}
1291
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001292/// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1293static bool isUndefShift(Value *Amount) {
1294 Constant *C = dyn_cast<Constant>(Amount);
1295 if (!C)
1296 return false;
1297
1298 // X shift by undef -> undef because it may shift by the bitwidth.
1299 if (isa<UndefValue>(C))
1300 return true;
1301
1302 // Shifting by the bitwidth or more is undefined.
1303 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1304 if (CI->getValue().getLimitedValue() >=
1305 CI->getType()->getScalarSizeInBits())
1306 return true;
1307
1308 // If all lanes of a vector shift are undefined the whole shift is.
1309 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1310 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1311 if (!isUndefShift(C->getAggregateElement(I)))
1312 return false;
1313 return true;
1314 }
1315
1316 return false;
1317}
1318
Duncan Sands571fd9a2011-01-14 14:44:12 +00001319/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sands7f60dc12011-01-14 00:37:45 +00001320/// fold the result. If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001321static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001322 const Query &Q, unsigned MaxRecurse) {
Duncan Sands7f60dc12011-01-14 00:37:45 +00001323 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1324 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1325 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001326 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001327 }
1328 }
1329
Duncan Sands571fd9a2011-01-14 14:44:12 +00001330 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001331 if (match(Op0, m_Zero()))
1332 return Op0;
1333
Duncan Sands571fd9a2011-01-14 14:44:12 +00001334 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001335 if (match(Op1, m_Zero()))
1336 return Op0;
1337
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001338 // Fold undefined shifts.
1339 if (isUndefShift(Op1))
1340 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001341
Duncan Sands571fd9a2011-01-14 14:44:12 +00001342 // If the operation is with the result of a select instruction, check whether
1343 // operating on either branch of the select always yields the same value.
1344 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001345 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001346 return V;
1347
1348 // If the operation is with the result of a phi instruction, check whether
1349 // operating on all incoming values of the phi always yields the same value.
1350 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001351 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001352 return V;
1353
Craig Topper9f008862014-04-15 04:59:12 +00001354 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001355}
1356
1357/// SimplifyShlInst - Given operands for an Shl, see if we can
1358/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001359static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001360 const Query &Q, unsigned MaxRecurse) {
1361 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001362 return V;
1363
1364 // undef << X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001365 if (match(Op0, m_Undef()))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001366 return Constant::getNullValue(Op0->getType());
1367
Chris Lattner9e4aa022011-02-09 17:15:04 +00001368 // (X >> A) << A -> X
1369 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001370 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001371 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001372 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001373}
1374
Chris Lattner9e4aa022011-02-09 17:15:04 +00001375Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001376 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001377 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001378 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001379 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001380}
1381
1382/// SimplifyLShrInst - Given operands for an LShr, see if we can
1383/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001384static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001385 const Query &Q, unsigned MaxRecurse) {
1386 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001387 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001388
David Majnemera80fed72013-07-09 22:01:22 +00001389 // X >> X -> 0
1390 if (Op0 == Op1)
1391 return Constant::getNullValue(Op0->getType());
1392
Duncan Sands7f60dc12011-01-14 00:37:45 +00001393 // undef >>l X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001394 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001395 return Constant::getNullValue(Op0->getType());
1396
Chris Lattner9e4aa022011-02-09 17:15:04 +00001397 // (X << A) >> A -> X
1398 Value *X;
1399 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1400 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1401 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001402
Craig Topper9f008862014-04-15 04:59:12 +00001403 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001404}
1405
Chris Lattner9e4aa022011-02-09 17:15:04 +00001406Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001407 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001408 const TargetLibraryInfo *TLI,
1409 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001410 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001411 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001412}
1413
1414/// SimplifyAShrInst - Given operands for an AShr, see if we can
1415/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001416static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001417 const Query &Q, unsigned MaxRecurse) {
1418 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001419 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001420
David Majnemera80fed72013-07-09 22:01:22 +00001421 // X >> X -> 0
1422 if (Op0 == Op1)
1423 return Constant::getNullValue(Op0->getType());
1424
Duncan Sands7f60dc12011-01-14 00:37:45 +00001425 // all ones >>a X -> all ones
1426 if (match(Op0, m_AllOnes()))
1427 return Op0;
1428
1429 // undef >>a X -> all ones
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001430 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001431 return Constant::getAllOnesValue(Op0->getType());
1432
Chris Lattner9e4aa022011-02-09 17:15:04 +00001433 // (X << A) >> A -> X
1434 Value *X;
1435 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1436 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1437 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001438
Craig Topper9f008862014-04-15 04:59:12 +00001439 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001440}
1441
Chris Lattner9e4aa022011-02-09 17:15:04 +00001442Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001443 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001444 const TargetLibraryInfo *TLI,
1445 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001446 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001447 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001448}
1449
Chris Lattnera71e9d62009-11-10 00:55:12 +00001450/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner084a1b52009-11-09 22:57:59 +00001451/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001452static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001453 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001454 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1455 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1456 Constant *Ops[] = { CLHS, CRHS };
1457 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001458 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001459 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001460
Chris Lattnera71e9d62009-11-10 00:55:12 +00001461 // Canonicalize the constant to the RHS.
1462 std::swap(Op0, Op1);
1463 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001464
Chris Lattnera71e9d62009-11-10 00:55:12 +00001465 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001466 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001467 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001468
Chris Lattnera71e9d62009-11-10 00:55:12 +00001469 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001470 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001471 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001472
Duncan Sandsc89ac072010-11-17 18:52:15 +00001473 // X & 0 = 0
1474 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001475 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001476
Duncan Sandsc89ac072010-11-17 18:52:15 +00001477 // X & -1 = X
1478 if (match(Op1, m_AllOnes()))
1479 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001480
Chris Lattnera71e9d62009-11-10 00:55:12 +00001481 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001482 if (match(Op0, m_Not(m_Specific(Op1))) ||
1483 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001484 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001485
Chris Lattnera71e9d62009-11-10 00:55:12 +00001486 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001487 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001488 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001489 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001490 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001491
Chris Lattnera71e9d62009-11-10 00:55:12 +00001492 // A & (A | ?) = A
1493 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001494 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001495 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001496
Duncan Sandsba286d72011-10-26 20:55:21 +00001497 // A & (-A) = A if A is a power of two or zero.
1498 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1499 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindola319f74c2012-12-13 03:37:24 +00001500 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001501 return Op0;
Rafael Espindola319f74c2012-12-13 03:37:24 +00001502 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001503 return Op1;
1504 }
1505
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001506 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001507 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1508 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001509 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001510
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001511 // And distributes over Or. Try some generic simplifications based on this.
1512 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001513 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001514 return V;
1515
1516 // And distributes over Xor. Try some generic simplifications based on this.
1517 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001518 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001519 return V;
1520
1521 // Or distributes over And. Try some generic simplifications based on this.
1522 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001523 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001524 return V;
1525
Duncan Sandsb0579e92010-11-10 13:00:08 +00001526 // If the operation is with the result of a select instruction, check whether
1527 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001528 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001529 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1530 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001531 return V;
1532
1533 // If the operation is with the result of a phi instruction, check whether
1534 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001535 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001536 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001537 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001538 return V;
1539
Craig Topper9f008862014-04-15 04:59:12 +00001540 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001541}
1542
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001543Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001544 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001545 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001546 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001547}
1548
Chris Lattnera71e9d62009-11-10 00:55:12 +00001549/// SimplifyOrInst - Given operands for an Or, see if we can
1550/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001551static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1552 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001553 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1554 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1555 Constant *Ops[] = { CLHS, CRHS };
1556 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001557 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001558 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001559
Chris Lattnera71e9d62009-11-10 00:55:12 +00001560 // Canonicalize the constant to the RHS.
1561 std::swap(Op0, Op1);
1562 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001563
Chris Lattnera71e9d62009-11-10 00:55:12 +00001564 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001565 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001566 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001567
Chris Lattnera71e9d62009-11-10 00:55:12 +00001568 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001569 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001570 return Op0;
1571
Duncan Sandsc89ac072010-11-17 18:52:15 +00001572 // X | 0 = X
1573 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001574 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001575
Duncan Sandsc89ac072010-11-17 18:52:15 +00001576 // X | -1 = -1
1577 if (match(Op1, m_AllOnes()))
1578 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001579
Chris Lattnera71e9d62009-11-10 00:55:12 +00001580 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001581 if (match(Op0, m_Not(m_Specific(Op1))) ||
1582 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001583 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001584
Chris Lattnera71e9d62009-11-10 00:55:12 +00001585 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001586 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001587 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001588 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001589 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001590
Chris Lattnera71e9d62009-11-10 00:55:12 +00001591 // A | (A & ?) = A
1592 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001593 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001594 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001595
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001596 // ~(A & ?) | A = -1
1597 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1598 (A == Op1 || B == Op1))
1599 return Constant::getAllOnesValue(Op1->getType());
1600
1601 // A | ~(A & ?) = -1
1602 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1603 (A == Op0 || B == Op0))
1604 return Constant::getAllOnesValue(Op0->getType());
1605
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001606 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001607 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1608 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001609 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001610
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001611 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001612 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1613 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001614 return V;
1615
1616 // And distributes over Or. Try some generic simplifications based on this.
1617 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001618 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001619 return V;
1620
Duncan Sandsb0579e92010-11-10 13:00:08 +00001621 // If the operation is with the result of a select instruction, check whether
1622 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001623 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001624 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001625 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001626 return V;
1627
1628 // If the operation is with the result of a phi instruction, check whether
1629 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001630 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001631 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001632 return V;
1633
Craig Topper9f008862014-04-15 04:59:12 +00001634 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001635}
1636
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001637Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001638 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001639 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001640 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001641}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001642
Duncan Sandsc89ac072010-11-17 18:52:15 +00001643/// SimplifyXorInst - Given operands for a Xor, see if we can
1644/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001645static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1646 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001647 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1648 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1649 Constant *Ops[] = { CLHS, CRHS };
1650 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001651 Ops, Q.DL, Q.TLI);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001652 }
1653
1654 // Canonicalize the constant to the RHS.
1655 std::swap(Op0, Op1);
1656 }
1657
1658 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001659 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001660 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001661
1662 // A ^ 0 = A
1663 if (match(Op1, m_Zero()))
1664 return Op0;
1665
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001666 // A ^ A = 0
1667 if (Op0 == Op1)
1668 return Constant::getNullValue(Op0->getType());
1669
Duncan Sandsc89ac072010-11-17 18:52:15 +00001670 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001671 if (match(Op0, m_Not(m_Specific(Op1))) ||
1672 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001673 return Constant::getAllOnesValue(Op0->getType());
1674
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001675 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001676 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1677 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001678 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001679
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001680 // And distributes over Xor. Try some generic simplifications based on this.
1681 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001682 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001683 return V;
1684
Duncan Sandsb238de02010-11-19 09:20:39 +00001685 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1686 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1687 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1688 // only if B and C are equal. If B and C are equal then (since we assume
1689 // that operands have already been simplified) "select(cond, B, C)" should
1690 // have been simplified to the common value of B and C already. Analysing
1691 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1692 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001693
Craig Topper9f008862014-04-15 04:59:12 +00001694 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001695}
1696
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001697Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001698 const TargetLibraryInfo *TLI,
Duncan Sandsc89ac072010-11-17 18:52:15 +00001699 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001700 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001701}
1702
Chris Lattner229907c2011-07-18 04:54:35 +00001703static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001704 return CmpInst::makeCmpResultType(Op->getType());
1705}
1706
Duncan Sandsaf327282011-05-07 16:56:49 +00001707/// ExtractEquivalentCondition - Rummage around inside V looking for something
1708/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1709/// otherwise return null. Helper function for analyzing max/min idioms.
1710static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1711 Value *LHS, Value *RHS) {
1712 SelectInst *SI = dyn_cast<SelectInst>(V);
1713 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001714 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001715 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1716 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001717 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001718 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1719 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1720 return Cmp;
1721 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1722 LHS == CmpRHS && RHS == CmpLHS)
1723 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001724 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001725}
1726
Dan Gohman9631d902013-02-01 00:49:06 +00001727// A significant optimization not implemented here is assuming that alloca
1728// addresses are not equal to incoming argument values. They don't *alias*,
1729// as we say, but that doesn't mean they aren't equal, so we take a
1730// conservative approach.
1731//
1732// This is inspired in part by C++11 5.10p1:
1733// "Two pointers of the same type compare equal if and only if they are both
1734// null, both point to the same function, or both represent the same
1735// address."
1736//
1737// This is pretty permissive.
1738//
1739// It's also partly due to C11 6.5.9p6:
1740// "Two pointers compare equal if and only if both are null pointers, both are
1741// pointers to the same object (including a pointer to an object and a
1742// subobject at its beginning) or function, both are pointers to one past the
1743// last element of the same array object, or one is a pointer to one past the
1744// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001745// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001746// object in the address space.)
1747//
1748// C11's version is more restrictive, however there's no reason why an argument
1749// couldn't be a one-past-the-end value for a stack object in the caller and be
1750// equal to the beginning of a stack object in the callee.
1751//
1752// If the C and C++ standards are ever made sufficiently restrictive in this
1753// area, it may be possible to update LLVM's semantics accordingly and reinstate
1754// this optimization.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001755static Constant *computePointerICmp(const DataLayout *DL,
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001756 const TargetLibraryInfo *TLI,
Chandler Carruth8059c842012-03-25 21:28:14 +00001757 CmpInst::Predicate Pred,
1758 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001759 // First, skip past any trivial no-ops.
1760 LHS = LHS->stripPointerCasts();
1761 RHS = RHS->stripPointerCasts();
1762
1763 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001764 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001765 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1766 return ConstantInt::get(GetCompareTy(LHS),
1767 !CmpInst::isTrueWhenEqual(Pred));
1768
Chandler Carruth8059c842012-03-25 21:28:14 +00001769 // We can only fold certain predicates on pointer comparisons.
1770 switch (Pred) {
1771 default:
Craig Topper9f008862014-04-15 04:59:12 +00001772 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001773
1774 // Equality comaprisons are easy to fold.
1775 case CmpInst::ICMP_EQ:
1776 case CmpInst::ICMP_NE:
1777 break;
1778
1779 // We can only handle unsigned relational comparisons because 'inbounds' on
1780 // a GEP only protects against unsigned wrapping.
1781 case CmpInst::ICMP_UGT:
1782 case CmpInst::ICMP_UGE:
1783 case CmpInst::ICMP_ULT:
1784 case CmpInst::ICMP_ULE:
1785 // However, we have to switch them to their signed variants to handle
1786 // negative indices from the base pointer.
1787 Pred = ICmpInst::getSignedPredicate(Pred);
1788 break;
1789 }
1790
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001791 // Strip off any constant offsets so that we can reason about them.
1792 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1793 // here and compare base addresses like AliasAnalysis does, however there are
1794 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1795 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1796 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001797 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1798 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001799
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001800 // If LHS and RHS are related via constant offsets to the same base
1801 // value, we can replace it with an icmp which just compares the offsets.
1802 if (LHS == RHS)
1803 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001804
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001805 // Various optimizations for (in)equality comparisons.
1806 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1807 // Different non-empty allocations that exist at the same time have
1808 // different addresses (if the program can tell). Global variables always
1809 // exist, so they always exist during the lifetime of each other and all
1810 // allocas. Two different allocas usually have different addresses...
1811 //
1812 // However, if there's an @llvm.stackrestore dynamically in between two
1813 // allocas, they may have the same address. It's tempting to reduce the
1814 // scope of the problem by only looking at *static* allocas here. That would
1815 // cover the majority of allocas while significantly reducing the likelihood
1816 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1817 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1818 // an entry block. Also, if we have a block that's not attached to a
1819 // function, we can't tell if it's "static" under the current definition.
1820 // Theoretically, this problem could be fixed by creating a new kind of
1821 // instruction kind specifically for static allocas. Such a new instruction
1822 // could be required to be at the top of the entry block, thus preventing it
1823 // from being subject to a @llvm.stackrestore. Instcombine could even
1824 // convert regular allocas into these special allocas. It'd be nifty.
1825 // However, until then, this problem remains open.
1826 //
1827 // So, we'll assume that two non-empty allocas have different addresses
1828 // for now.
1829 //
1830 // With all that, if the offsets are within the bounds of their allocations
1831 // (and not one-past-the-end! so we can't use inbounds!), and their
1832 // allocations aren't the same, the pointers are not equal.
1833 //
1834 // Note that it's not necessary to check for LHS being a global variable
1835 // address, due to canonicalization and constant folding.
1836 if (isa<AllocaInst>(LHS) &&
1837 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001838 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1839 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001840 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001841 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001842 getObjectSize(LHS, LHSSize, DL, TLI) &&
1843 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001844 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1845 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001846 if (!LHSOffsetValue.isNegative() &&
1847 !RHSOffsetValue.isNegative() &&
1848 LHSOffsetValue.ult(LHSSize) &&
1849 RHSOffsetValue.ult(RHSSize)) {
1850 return ConstantInt::get(GetCompareTy(LHS),
1851 !CmpInst::isTrueWhenEqual(Pred));
1852 }
1853 }
1854
1855 // Repeat the above check but this time without depending on DataLayout
1856 // or being able to compute a precise size.
1857 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1858 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1859 LHSOffset->isNullValue() &&
1860 RHSOffset->isNullValue())
1861 return ConstantInt::get(GetCompareTy(LHS),
1862 !CmpInst::isTrueWhenEqual(Pred));
1863 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001864
1865 // Even if an non-inbounds GEP occurs along the path we can still optimize
1866 // equality comparisons concerning the result. We avoid walking the whole
1867 // chain again by starting where the last calls to
1868 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001869 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1870 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001871 if (LHS == RHS)
1872 return ConstantExpr::getICmp(Pred,
1873 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1874 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001875 }
1876
1877 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00001878 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001879}
Chris Lattner01990f02012-02-24 19:01:58 +00001880
Chris Lattnerc1f19072009-11-09 23:28:39 +00001881/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1882/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001883static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001884 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00001885 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00001886 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00001887
Chris Lattnera71e9d62009-11-10 00:55:12 +00001888 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001889 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001890 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001891
1892 // If we have a constant, make sure it is on the RHS.
1893 std::swap(LHS, RHS);
1894 Pred = CmpInst::getSwappedPredicate(Pred);
1895 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001896
Chris Lattner229907c2011-07-18 04:54:35 +00001897 Type *ITy = GetCompareTy(LHS); // The return type.
1898 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00001899
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001900 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00001901 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1902 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00001903 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001904 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00001905
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001906 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00001907 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001908 switch (Pred) {
1909 default: break;
1910 case ICmpInst::ICMP_EQ:
1911 // X == 1 -> X
1912 if (match(RHS, m_One()))
1913 return LHS;
1914 break;
1915 case ICmpInst::ICMP_NE:
1916 // X != 0 -> X
1917 if (match(RHS, m_Zero()))
1918 return LHS;
1919 break;
1920 case ICmpInst::ICMP_UGT:
1921 // X >u 0 -> X
1922 if (match(RHS, m_Zero()))
1923 return LHS;
1924 break;
1925 case ICmpInst::ICMP_UGE:
1926 // X >=u 1 -> X
1927 if (match(RHS, m_One()))
1928 return LHS;
1929 break;
1930 case ICmpInst::ICMP_SLT:
1931 // X <s 0 -> X
1932 if (match(RHS, m_Zero()))
1933 return LHS;
1934 break;
1935 case ICmpInst::ICMP_SLE:
1936 // X <=s -1 -> X
1937 if (match(RHS, m_One()))
1938 return LHS;
1939 break;
1940 }
1941 }
1942
Duncan Sandsd3951082011-01-25 09:38:29 +00001943 // If we are comparing with zero then try hard since this is a common case.
1944 if (match(RHS, m_Zero())) {
1945 bool LHSKnownNonNegative, LHSKnownNegative;
1946 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00001947 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00001948 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001949 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001950 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001951 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001952 case ICmpInst::ICMP_EQ:
1953 case ICmpInst::ICMP_ULE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001954 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001955 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001956 break;
1957 case ICmpInst::ICMP_NE:
1958 case ICmpInst::ICMP_UGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001959 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001960 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001961 break;
1962 case ICmpInst::ICMP_SLT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001963 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001964 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001965 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001966 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001967 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001968 break;
1969 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001970 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001971 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001972 return getTrue(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001973 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001974 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001975 break;
1976 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001977 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001978 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001979 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001980 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001981 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001982 break;
1983 case ICmpInst::ICMP_SGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001984 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001985 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001986 return getFalse(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001987 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001988 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001989 break;
1990 }
1991 }
1992
1993 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001994 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001995 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1996 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1997 if (RHS_CR.isEmptySet())
1998 return ConstantInt::getFalse(CI->getContext());
1999 if (RHS_CR.isFullSet())
2000 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002001
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002002 // Many binary operators with constant RHS have easy to compute constant
2003 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002004 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002005 APInt Lower = APInt(Width, 0);
2006 APInt Upper = APInt(Width, 0);
2007 ConstantInt *CI2;
2008 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2009 // 'urem x, CI2' produces [0, CI2).
2010 Upper = CI2->getValue();
2011 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2012 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2013 Upper = CI2->getValue().abs();
2014 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002015 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2016 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002017 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002018 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2019 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2020 APInt NegOne = APInt::getAllOnesValue(Width);
2021 if (!CI2->isZero())
2022 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002023 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2024 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2025 Upper = CI2->getValue().abs() + 1;
2026 Lower = (-Upper) + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002027 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2028 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
2029 APInt IntMin = APInt::getSignedMinValue(Width);
2030 APInt IntMax = APInt::getSignedMaxValue(Width);
2031 APInt Val = CI2->getValue().abs();
2032 if (!Val.isMinValue()) {
2033 Lower = IntMin.sdiv(Val);
2034 Upper = IntMax.sdiv(Val) + 1;
2035 }
2036 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2037 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2038 APInt NegOne = APInt::getAllOnesValue(Width);
2039 if (CI2->getValue().ult(Width))
2040 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002041 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2042 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2043 unsigned ShiftAmount = Width - 1;
2044 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2045 ShiftAmount = CI2->getValue().countTrailingZeros();
2046 Lower = CI2->getValue().lshr(ShiftAmount);
2047 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002048 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2049 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2050 APInt IntMin = APInt::getSignedMinValue(Width);
2051 APInt IntMax = APInt::getSignedMaxValue(Width);
2052 if (CI2->getValue().ult(Width)) {
2053 Lower = IntMin.ashr(CI2->getValue());
2054 Upper = IntMax.ashr(CI2->getValue()) + 1;
2055 }
David Majnemer78910fc2014-05-16 17:14:03 +00002056 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2057 unsigned ShiftAmount = Width - 1;
2058 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2059 ShiftAmount = CI2->getValue().countTrailingZeros();
2060 if (CI2->isNegative()) {
2061 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2062 Lower = CI2->getValue();
2063 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2064 } else {
2065 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2066 Lower = CI2->getValue().ashr(ShiftAmount);
2067 Upper = CI2->getValue() + 1;
2068 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002069 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2070 // 'or x, CI2' produces [CI2, UINT_MAX].
2071 Lower = CI2->getValue();
2072 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2073 // 'and x, CI2' produces [0, CI2].
2074 Upper = CI2->getValue() + 1;
2075 }
2076 if (Lower != Upper) {
2077 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2078 if (RHS_CR.contains(LHS_CR))
2079 return ConstantInt::getTrue(RHS->getContext());
2080 if (RHS_CR.inverse().contains(LHS_CR))
2081 return ConstantInt::getFalse(RHS->getContext());
2082 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002083 }
2084
Duncan Sands8fb2c382011-01-20 13:21:55 +00002085 // Compare of cast, for example (zext X) != 0 -> X != 0
2086 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2087 Instruction *LI = cast<CastInst>(LHS);
2088 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002089 Type *SrcTy = SrcOp->getType();
2090 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002091
2092 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2093 // if the integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002094 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2095 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002096 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2097 // Transfer the cast to the constant.
2098 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2099 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002100 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002101 return V;
2102 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2103 if (RI->getOperand(0)->getType() == SrcTy)
2104 // Compare without the cast.
2105 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002106 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002107 return V;
2108 }
2109 }
2110
2111 if (isa<ZExtInst>(LHS)) {
2112 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2113 // same type.
2114 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2115 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2116 // Compare X and Y. Note that signed predicates become unsigned.
2117 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002118 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002119 MaxRecurse-1))
2120 return V;
2121 }
2122 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2123 // too. If not, then try to deduce the result of the comparison.
2124 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2125 // Compute the constant that would happen if we truncated to SrcTy then
2126 // reextended to DstTy.
2127 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2128 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2129
2130 // If the re-extended constant didn't change then this is effectively
2131 // also a case of comparing two zero-extended values.
2132 if (RExt == CI && MaxRecurse)
2133 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002134 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002135 return V;
2136
2137 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2138 // there. Use this to work out the result of the comparison.
2139 if (RExt != CI) {
2140 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002141 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002142 // LHS <u RHS.
2143 case ICmpInst::ICMP_EQ:
2144 case ICmpInst::ICMP_UGT:
2145 case ICmpInst::ICMP_UGE:
2146 return ConstantInt::getFalse(CI->getContext());
2147
2148 case ICmpInst::ICMP_NE:
2149 case ICmpInst::ICMP_ULT:
2150 case ICmpInst::ICMP_ULE:
2151 return ConstantInt::getTrue(CI->getContext());
2152
2153 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2154 // is non-negative then LHS <s RHS.
2155 case ICmpInst::ICMP_SGT:
2156 case ICmpInst::ICMP_SGE:
2157 return CI->getValue().isNegative() ?
2158 ConstantInt::getTrue(CI->getContext()) :
2159 ConstantInt::getFalse(CI->getContext());
2160
2161 case ICmpInst::ICMP_SLT:
2162 case ICmpInst::ICMP_SLE:
2163 return CI->getValue().isNegative() ?
2164 ConstantInt::getFalse(CI->getContext()) :
2165 ConstantInt::getTrue(CI->getContext());
2166 }
2167 }
2168 }
2169 }
2170
2171 if (isa<SExtInst>(LHS)) {
2172 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2173 // same type.
2174 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2175 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2176 // Compare X and Y. Note that the predicate does not change.
2177 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002178 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002179 return V;
2180 }
2181 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2182 // too. If not, then try to deduce the result of the comparison.
2183 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2184 // Compute the constant that would happen if we truncated to SrcTy then
2185 // reextended to DstTy.
2186 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2187 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2188
2189 // If the re-extended constant didn't change then this is effectively
2190 // also a case of comparing two sign-extended values.
2191 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002192 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002193 return V;
2194
2195 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2196 // bits there. Use this to work out the result of the comparison.
2197 if (RExt != CI) {
2198 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002199 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002200 case ICmpInst::ICMP_EQ:
2201 return ConstantInt::getFalse(CI->getContext());
2202 case ICmpInst::ICMP_NE:
2203 return ConstantInt::getTrue(CI->getContext());
2204
2205 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2206 // LHS >s RHS.
2207 case ICmpInst::ICMP_SGT:
2208 case ICmpInst::ICMP_SGE:
2209 return CI->getValue().isNegative() ?
2210 ConstantInt::getTrue(CI->getContext()) :
2211 ConstantInt::getFalse(CI->getContext());
2212 case ICmpInst::ICMP_SLT:
2213 case ICmpInst::ICMP_SLE:
2214 return CI->getValue().isNegative() ?
2215 ConstantInt::getFalse(CI->getContext()) :
2216 ConstantInt::getTrue(CI->getContext());
2217
2218 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2219 // LHS >u RHS.
2220 case ICmpInst::ICMP_UGT:
2221 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002222 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002223 if (MaxRecurse)
2224 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2225 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002226 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002227 return V;
2228 break;
2229 case ICmpInst::ICMP_ULT:
2230 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002231 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002232 if (MaxRecurse)
2233 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2234 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002235 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002236 return V;
2237 break;
2238 }
2239 }
2240 }
2241 }
2242 }
2243
Duncan Sandsd114ab32011-02-13 17:15:40 +00002244 // Special logic for binary operators.
2245 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2246 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2247 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002248 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002249 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002250 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2251 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2252 if (LBO && LBO->getOpcode() == Instruction::Add) {
2253 A = LBO->getOperand(0); B = LBO->getOperand(1);
2254 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2255 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2256 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2257 }
2258 if (RBO && RBO->getOpcode() == Instruction::Add) {
2259 C = RBO->getOperand(0); D = RBO->getOperand(1);
2260 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2261 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2262 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2263 }
2264
2265 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2266 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2267 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2268 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002269 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002270 return V;
2271
2272 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2273 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2274 if (Value *V = SimplifyICmpInst(Pred,
2275 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002276 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002277 return V;
2278
2279 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2280 if (A && C && (A == C || A == D || B == C || B == D) &&
2281 NoLHSWrapProblem && NoRHSWrapProblem) {
2282 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002283 Value *Y, *Z;
2284 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002285 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002286 Y = B;
2287 Z = D;
2288 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002289 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002290 Y = B;
2291 Z = C;
2292 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002293 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002294 Y = A;
2295 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002296 } else {
2297 assert(B == D);
2298 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002299 Y = A;
2300 Z = C;
2301 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002302 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002303 return V;
2304 }
2305 }
2306
David Majnemer2d6c0232014-05-14 20:16:28 +00002307 // 0 - (zext X) pred C
2308 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2309 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310 if (RHSC->getValue().isStrictlyPositive()) {
2311 if (Pred == ICmpInst::ICMP_SLT)
2312 return ConstantInt::getTrue(RHSC->getContext());
2313 if (Pred == ICmpInst::ICMP_SGE)
2314 return ConstantInt::getFalse(RHSC->getContext());
2315 if (Pred == ICmpInst::ICMP_EQ)
2316 return ConstantInt::getFalse(RHSC->getContext());
2317 if (Pred == ICmpInst::ICMP_NE)
2318 return ConstantInt::getTrue(RHSC->getContext());
2319 }
2320 if (RHSC->getValue().isNonNegative()) {
2321 if (Pred == ICmpInst::ICMP_SLE)
2322 return ConstantInt::getTrue(RHSC->getContext());
2323 if (Pred == ICmpInst::ICMP_SGT)
2324 return ConstantInt::getFalse(RHSC->getContext());
2325 }
2326 }
2327 }
2328
Nick Lewycky35aeea92013-07-12 23:42:57 +00002329 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002330 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002331 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002332 switch (Pred) {
2333 default:
2334 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002335 case ICmpInst::ICMP_SGT:
2336 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002337 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002338 if (!KnownNonNegative)
2339 break;
2340 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002341 case ICmpInst::ICMP_EQ:
2342 case ICmpInst::ICMP_UGT:
2343 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002344 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002345 case ICmpInst::ICMP_SLT:
2346 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002347 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002348 if (!KnownNonNegative)
2349 break;
2350 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002351 case ICmpInst::ICMP_NE:
2352 case ICmpInst::ICMP_ULT:
2353 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002354 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002355 }
2356 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002357
2358 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002359 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2360 bool KnownNonNegative, KnownNegative;
2361 switch (Pred) {
2362 default:
2363 break;
2364 case ICmpInst::ICMP_SGT:
2365 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002366 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002367 if (!KnownNonNegative)
2368 break;
2369 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002370 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002371 case ICmpInst::ICMP_UGT:
2372 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002373 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002374 case ICmpInst::ICMP_SLT:
2375 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002376 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002377 if (!KnownNonNegative)
2378 break;
2379 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002380 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002381 case ICmpInst::ICMP_ULT:
2382 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002383 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002384 }
2385 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002386
Duncan Sands92af0a82011-10-28 18:17:44 +00002387 // x udiv y <=u x.
2388 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2389 // icmp pred (X /u Y), X
2390 if (Pred == ICmpInst::ICMP_UGT)
2391 return getFalse(ITy);
2392 if (Pred == ICmpInst::ICMP_ULE)
2393 return getTrue(ITy);
2394 }
2395
Nick Lewycky9719a712011-03-05 05:19:11 +00002396 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2397 LBO->getOperand(1) == RBO->getOperand(1)) {
2398 switch (LBO->getOpcode()) {
2399 default: break;
2400 case Instruction::UDiv:
2401 case Instruction::LShr:
2402 if (ICmpInst::isSigned(Pred))
2403 break;
2404 // fall-through
2405 case Instruction::SDiv:
2406 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002407 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002408 break;
2409 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002410 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002411 return V;
2412 break;
2413 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002414 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002415 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2416 if (!NUW && !NSW)
2417 break;
2418 if (!NSW && ICmpInst::isSigned(Pred))
2419 break;
2420 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002421 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002422 return V;
2423 break;
2424 }
2425 }
2426 }
2427
Duncan Sands0a9c1242011-05-03 19:53:10 +00002428 // Simplify comparisons involving max/min.
2429 Value *A, *B;
2430 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002431 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002432
Duncan Sandsa2287852011-05-04 16:05:05 +00002433 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002434 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2435 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002436 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002437 // We analyze this as smax(A, B) pred A.
2438 P = Pred;
2439 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2440 (A == LHS || B == LHS)) {
2441 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002442 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002443 // We analyze this as smax(A, B) swapped-pred A.
2444 P = CmpInst::getSwappedPredicate(Pred);
2445 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2446 (A == RHS || B == RHS)) {
2447 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002448 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002449 // We analyze this as smax(-A, -B) swapped-pred -A.
2450 // Note that we do not need to actually form -A or -B thanks to EqP.
2451 P = CmpInst::getSwappedPredicate(Pred);
2452 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2453 (A == LHS || B == LHS)) {
2454 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002455 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002456 // We analyze this as smax(-A, -B) pred -A.
2457 // Note that we do not need to actually form -A or -B thanks to EqP.
2458 P = Pred;
2459 }
2460 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2461 // Cases correspond to "max(A, B) p A".
2462 switch (P) {
2463 default:
2464 break;
2465 case CmpInst::ICMP_EQ:
2466 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002467 // Equivalent to "A EqP B". This may be the same as the condition tested
2468 // in the max/min; if so, we can just return that.
2469 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2470 return V;
2471 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2472 return V;
2473 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002474 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002475 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002476 return V;
2477 break;
2478 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002479 case CmpInst::ICMP_SGT: {
2480 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2481 // Equivalent to "A InvEqP B". This may be the same as the condition
2482 // tested in the max/min; if so, we can just return that.
2483 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2484 return V;
2485 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2486 return V;
2487 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002488 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002489 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002490 return V;
2491 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002492 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002493 case CmpInst::ICMP_SGE:
2494 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002495 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002496 case CmpInst::ICMP_SLT:
2497 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002498 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002499 }
2500 }
2501
Duncan Sandsa2287852011-05-04 16:05:05 +00002502 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002503 P = CmpInst::BAD_ICMP_PREDICATE;
2504 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2505 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002506 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002507 // We analyze this as umax(A, B) pred A.
2508 P = Pred;
2509 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2510 (A == LHS || B == LHS)) {
2511 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002512 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002513 // We analyze this as umax(A, B) swapped-pred A.
2514 P = CmpInst::getSwappedPredicate(Pred);
2515 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2516 (A == RHS || B == RHS)) {
2517 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002518 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002519 // We analyze this as umax(-A, -B) swapped-pred -A.
2520 // Note that we do not need to actually form -A or -B thanks to EqP.
2521 P = CmpInst::getSwappedPredicate(Pred);
2522 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2523 (A == LHS || B == LHS)) {
2524 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002525 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002526 // We analyze this as umax(-A, -B) pred -A.
2527 // Note that we do not need to actually form -A or -B thanks to EqP.
2528 P = Pred;
2529 }
2530 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2531 // Cases correspond to "max(A, B) p A".
2532 switch (P) {
2533 default:
2534 break;
2535 case CmpInst::ICMP_EQ:
2536 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002537 // Equivalent to "A EqP B". This may be the same as the condition tested
2538 // in the max/min; if so, we can just return that.
2539 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2540 return V;
2541 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2542 return V;
2543 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002544 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002545 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002546 return V;
2547 break;
2548 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002549 case CmpInst::ICMP_UGT: {
2550 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2551 // Equivalent to "A InvEqP B". This may be the same as the condition
2552 // tested in the max/min; if so, we can just return that.
2553 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2554 return V;
2555 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2556 return V;
2557 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002558 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002559 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002560 return V;
2561 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002562 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002563 case CmpInst::ICMP_UGE:
2564 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002565 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002566 case CmpInst::ICMP_ULT:
2567 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002568 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002569 }
2570 }
2571
Duncan Sandsa2287852011-05-04 16:05:05 +00002572 // Variants on "max(x,y) >= min(x,z)".
2573 Value *C, *D;
2574 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2575 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2576 (A == C || A == D || B == C || B == D)) {
2577 // max(x, ?) pred min(x, ?).
2578 if (Pred == CmpInst::ICMP_SGE)
2579 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002580 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002581 if (Pred == CmpInst::ICMP_SLT)
2582 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002583 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002584 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2585 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2586 (A == C || A == D || B == C || B == D)) {
2587 // min(x, ?) pred max(x, ?).
2588 if (Pred == CmpInst::ICMP_SLE)
2589 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002590 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002591 if (Pred == CmpInst::ICMP_SGT)
2592 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002593 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002594 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2595 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2596 (A == C || A == D || B == C || B == D)) {
2597 // max(x, ?) pred min(x, ?).
2598 if (Pred == CmpInst::ICMP_UGE)
2599 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002600 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002601 if (Pred == CmpInst::ICMP_ULT)
2602 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002603 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002604 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2605 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2606 (A == C || A == D || B == C || B == D)) {
2607 // min(x, ?) pred max(x, ?).
2608 if (Pred == CmpInst::ICMP_ULE)
2609 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002610 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002611 if (Pred == CmpInst::ICMP_UGT)
2612 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002613 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002614 }
2615
Chandler Carruth8059c842012-03-25 21:28:14 +00002616 // Simplify comparisons of related pointers using a powerful, recursive
2617 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00002618 if (LHS->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002619 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00002620 return C;
2621
Nick Lewycky3db143e2012-02-26 02:09:49 +00002622 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2623 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2624 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2625 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2626 (ICmpInst::isEquality(Pred) ||
2627 (GLHS->isInBounds() && GRHS->isInBounds() &&
2628 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2629 // The bases are equal and the indices are constant. Build a constant
2630 // expression GEP with the same indices and a null base pointer to see
2631 // what constant folding can make out of it.
2632 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2633 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2634 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2635
2636 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2637 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2638 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2639 }
2640 }
2641 }
2642
Duncan Sandsf532d312010-11-07 16:12:23 +00002643 // If the comparison is with the result of a select instruction, check whether
2644 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002645 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002646 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002647 return V;
2648
2649 // If the comparison is with the result of a phi instruction, check whether
2650 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002651 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002652 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002653 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00002654
Craig Topper9f008862014-04-15 04:59:12 +00002655 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00002656}
2657
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002658Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002659 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002660 const TargetLibraryInfo *TLI,
2661 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002662 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002663 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002664}
2665
Chris Lattnerc1f19072009-11-09 23:28:39 +00002666/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2667/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002668static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002669 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002670 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2671 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2672
Chris Lattnera71e9d62009-11-10 00:55:12 +00002673 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002674 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002675 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00002676
Chris Lattnera71e9d62009-11-10 00:55:12 +00002677 // If we have a constant, make sure it is on the RHS.
2678 std::swap(LHS, RHS);
2679 Pred = CmpInst::getSwappedPredicate(Pred);
2680 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002681
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002682 // Fold trivial predicates.
2683 if (Pred == FCmpInst::FCMP_FALSE)
2684 return ConstantInt::get(GetCompareTy(LHS), 0);
2685 if (Pred == FCmpInst::FCMP_TRUE)
2686 return ConstantInt::get(GetCompareTy(LHS), 1);
2687
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002688 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2689 return UndefValue::get(GetCompareTy(LHS));
2690
2691 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00002692 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002693 if (CmpInst::isTrueWhenEqual(Pred))
2694 return ConstantInt::get(GetCompareTy(LHS), 1);
2695 if (CmpInst::isFalseWhenEqual(Pred))
2696 return ConstantInt::get(GetCompareTy(LHS), 0);
2697 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002698
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002699 // Handle fcmp with constant RHS
2700 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2701 // If the constant is a nan, see if we can fold the comparison based on it.
2702 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2703 if (CFP->getValueAPF().isNaN()) {
2704 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2705 return ConstantInt::getFalse(CFP->getContext());
2706 assert(FCmpInst::isUnordered(Pred) &&
2707 "Comparison must be either ordered or unordered!");
2708 // True if unordered.
2709 return ConstantInt::getTrue(CFP->getContext());
2710 }
Dan Gohman754e4a92010-02-22 04:06:03 +00002711 // Check whether the constant is an infinity.
2712 if (CFP->getValueAPF().isInfinity()) {
2713 if (CFP->getValueAPF().isNegative()) {
2714 switch (Pred) {
2715 case FCmpInst::FCMP_OLT:
2716 // No value is ordered and less than negative infinity.
2717 return ConstantInt::getFalse(CFP->getContext());
2718 case FCmpInst::FCMP_UGE:
2719 // All values are unordered with or at least negative infinity.
2720 return ConstantInt::getTrue(CFP->getContext());
2721 default:
2722 break;
2723 }
2724 } else {
2725 switch (Pred) {
2726 case FCmpInst::FCMP_OGT:
2727 // No value is ordered and greater than infinity.
2728 return ConstantInt::getFalse(CFP->getContext());
2729 case FCmpInst::FCMP_ULE:
2730 // All values are unordered with and at most infinity.
2731 return ConstantInt::getTrue(CFP->getContext());
2732 default:
2733 break;
2734 }
2735 }
2736 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002737 }
2738 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002739
Duncan Sandsa620bd12010-11-07 16:46:25 +00002740 // If the comparison is with the result of a select instruction, check whether
2741 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002742 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002743 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002744 return V;
2745
2746 // If the comparison is with the result of a phi instruction, check whether
2747 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002748 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002749 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002750 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00002751
Craig Topper9f008862014-04-15 04:59:12 +00002752 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002753}
2754
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002755Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002756 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002757 const TargetLibraryInfo *TLI,
2758 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002759 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002760 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002761}
2762
Chris Lattnerc707fa92010-04-20 05:32:14 +00002763/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2764/// the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002765static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2766 Value *FalseVal, const Query &Q,
2767 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00002768 // select true, X, Y -> X
2769 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002770 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2771 if (CB->isAllOnesValue())
2772 return TrueVal;
2773 if (CB->isNullValue())
2774 return FalseVal;
2775 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002776
Chris Lattnerc707fa92010-04-20 05:32:14 +00002777 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00002778 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00002779 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002780
Chris Lattnerc707fa92010-04-20 05:32:14 +00002781 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2782 if (isa<Constant>(TrueVal))
2783 return TrueVal;
2784 return FalseVal;
2785 }
Dan Gohman54664ed2011-07-01 01:03:43 +00002786 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2787 return FalseVal;
2788 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2789 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002790
Craig Topper9f008862014-04-15 04:59:12 +00002791 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00002792}
2793
Duncan Sandsb8cee002012-03-13 11:42:19 +00002794Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002795 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002796 const TargetLibraryInfo *TLI,
2797 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002798 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002799 RecursionLimit);
2800}
2801
Chris Lattner8574aba2009-11-27 00:29:05 +00002802/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2803/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002804static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00002805 // The type of the GEP pointer operand.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002806 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002807
Chris Lattner8574aba2009-11-27 00:29:05 +00002808 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00002809 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00002810 return Ops[0];
2811
Duncan Sands8a0f4862010-11-22 13:42:49 +00002812 if (isa<UndefValue>(Ops[0])) {
2813 // Compute the (pointer) type returned by the GEP instruction.
Jay Foadd1b78492011-07-25 09:48:08 +00002814 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattner229907c2011-07-18 04:54:35 +00002815 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002816 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2817 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002818 return UndefValue::get(GEPTy);
2819 }
Chris Lattner8574aba2009-11-27 00:29:05 +00002820
Jay Foadb992a632011-07-19 15:07:52 +00002821 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002822 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002823 if (match(Ops[1], m_Zero()))
2824 return Ops[0];
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002825 // getelementptr P, N -> P if P points to a type of zero size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002826 if (Q.DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002827 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002828 if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002829 return Ops[0];
2830 }
2831 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002832
Chris Lattner8574aba2009-11-27 00:29:05 +00002833 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00002834 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00002835 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00002836 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00002837
Jay Foaded8db7d2011-07-21 14:31:17 +00002838 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00002839}
2840
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002841Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002842 const TargetLibraryInfo *TLI,
2843 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002844 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002845}
2846
Duncan Sandsfd26a952011-09-05 06:52:48 +00002847/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2848/// can fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002849static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2850 ArrayRef<unsigned> Idxs, const Query &Q,
2851 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002852 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2853 if (Constant *CVal = dyn_cast<Constant>(Val))
2854 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2855
2856 // insertvalue x, undef, n -> x
2857 if (match(Val, m_Undef()))
2858 return Agg;
2859
2860 // insertvalue x, (extractvalue y, n), n
2861 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00002862 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2863 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002864 // insertvalue undef, (extractvalue y, n), n -> y
2865 if (match(Agg, m_Undef()))
2866 return EV->getAggregateOperand();
2867
2868 // insertvalue y, (extractvalue y, n), n -> y
2869 if (Agg == EV->getAggregateOperand())
2870 return Agg;
2871 }
2872
Craig Topper9f008862014-04-15 04:59:12 +00002873 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00002874}
2875
Duncan Sandsb8cee002012-03-13 11:42:19 +00002876Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2877 ArrayRef<unsigned> Idxs,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002878 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002879 const TargetLibraryInfo *TLI,
2880 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002881 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002882 RecursionLimit);
2883}
2884
Duncan Sands7412f6e2010-11-17 04:30:22 +00002885/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002886static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00002887 // If all of the PHI's incoming values are the same then replace the PHI node
2888 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00002889 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00002890 bool HasUndefInput = false;
2891 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2892 Value *Incoming = PN->getIncomingValue(i);
2893 // If the incoming value is the phi node itself, it can safely be skipped.
2894 if (Incoming == PN) continue;
2895 if (isa<UndefValue>(Incoming)) {
2896 // Remember that we saw an undef value, but otherwise ignore them.
2897 HasUndefInput = true;
2898 continue;
2899 }
2900 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00002901 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00002902 CommonValue = Incoming;
2903 }
2904
2905 // If CommonValue is null then all of the incoming values were either undef or
2906 // equal to the phi node itself.
2907 if (!CommonValue)
2908 return UndefValue::get(PN->getType());
2909
2910 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2911 // instruction, we cannot return X as the result of the PHI node unless it
2912 // dominates the PHI block.
2913 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00002914 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00002915
2916 return CommonValue;
2917}
2918
Duncan Sands395ac42d2012-03-13 14:07:05 +00002919static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2920 if (Constant *C = dyn_cast<Constant>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002921 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002922
Craig Topper9f008862014-04-15 04:59:12 +00002923 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00002924}
2925
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002926Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00002927 const TargetLibraryInfo *TLI,
2928 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002929 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002930}
2931
Chris Lattnera71e9d62009-11-10 00:55:12 +00002932//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00002933
Chris Lattnera71e9d62009-11-10 00:55:12 +00002934/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2935/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002936static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002937 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00002938 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00002939 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002940 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002941 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002942 case Instruction::FAdd:
2943 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2944
Chris Lattner9e4aa022011-02-09 17:15:04 +00002945 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002946 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002947 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002948 case Instruction::FSub:
2949 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2950
Duncan Sandsb8cee002012-03-13 11:42:19 +00002951 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002952 case Instruction::FMul:
2953 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002954 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2955 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2956 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2957 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2958 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2959 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002960 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002961 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002962 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002963 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002964 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002965 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002966 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2967 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2968 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2969 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002970 default:
2971 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2972 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2973 Constant *COps[] = {CLHS, CRHS};
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002974 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002975 Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002976 }
Duncan Sandsb0579e92010-11-10 13:00:08 +00002977
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002978 // If the operation is associative, try some generic simplifications.
2979 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002980 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002981 return V;
2982
Duncan Sandsb8cee002012-03-13 11:42:19 +00002983 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00002984 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002985 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002986 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002987 return V;
2988
2989 // If the operation is with the result of a phi instruction, check whether
2990 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002991 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002992 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00002993 return V;
2994
Craig Topper9f008862014-04-15 04:59:12 +00002995 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00002996 }
2997}
Chris Lattnerc1f19072009-11-09 23:28:39 +00002998
Duncan Sands7e800d62010-11-14 11:23:23 +00002999Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003000 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003001 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003002 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003003}
3004
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003005/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3006/// fold the result.
3007static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003008 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003009 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003010 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3011 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003012}
3013
3014Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003015 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003016 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003017 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003018 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003019}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003020
Michael Ilseman54857292013-02-07 19:26:05 +00003021static bool IsIdempotent(Intrinsic::ID ID) {
3022 switch (ID) {
3023 default: return false;
3024
3025 // Unary idempotent: f(f(x)) = f(x)
3026 case Intrinsic::fabs:
3027 case Intrinsic::floor:
3028 case Intrinsic::ceil:
3029 case Intrinsic::trunc:
3030 case Intrinsic::rint:
3031 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003032 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003033 return true;
3034 }
3035}
3036
3037template <typename IterTy>
3038static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3039 const Query &Q, unsigned MaxRecurse) {
3040 // Perform idempotent optimizations
3041 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003042 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003043
3044 // Unary Ops
3045 if (std::distance(ArgBegin, ArgEnd) == 1)
3046 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3047 if (II->getIntrinsicID() == IID)
3048 return II;
3049
Craig Topper9f008862014-04-15 04:59:12 +00003050 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003051}
3052
Chandler Carruth9dc35582012-12-28 11:30:55 +00003053template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003054static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003055 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003056 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003057 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3058 Ty = PTy->getElementType();
3059 FunctionType *FTy = cast<FunctionType>(Ty);
3060
Dan Gohman85977e62011-11-04 18:32:42 +00003061 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003062 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003063 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003064
Chandler Carruthf6182152012-12-28 14:23:29 +00003065 Function *F = dyn_cast<Function>(V);
3066 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00003067 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003068
Michael Ilseman54857292013-02-07 19:26:05 +00003069 if (unsigned IID = F->getIntrinsicID())
3070 if (Value *Ret =
3071 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3072 return Ret;
3073
Chandler Carruthf6182152012-12-28 14:23:29 +00003074 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00003075 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003076
3077 SmallVector<Constant *, 4> ConstantArgs;
3078 ConstantArgs.reserve(ArgEnd - ArgBegin);
3079 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3080 Constant *C = dyn_cast<Constant>(*I);
3081 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00003082 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003083 ConstantArgs.push_back(C);
3084 }
3085
3086 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00003087}
3088
Chandler Carruthf6182152012-12-28 14:23:29 +00003089Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003090 User::op_iterator ArgEnd, const DataLayout *DL,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003091 const TargetLibraryInfo *TLI,
3092 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003093 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003094 RecursionLimit);
3095}
3096
Chandler Carruthf6182152012-12-28 14:23:29 +00003097Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003098 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003099 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003100 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003101 RecursionLimit);
3102}
3103
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003104/// SimplifyInstruction - See if we can compute a simplified version of this
3105/// instruction. If not, this returns null.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003106Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003107 const TargetLibraryInfo *TLI,
Duncan Sandsb99f39b2010-11-14 18:36:10 +00003108 const DominatorTree *DT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00003109 Value *Result;
3110
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003111 switch (I->getOpcode()) {
3112 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003113 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003114 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003115 case Instruction::FAdd:
3116 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003117 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003118 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00003119 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003120 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3121 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3122 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003123 DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003124 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003125 case Instruction::FSub:
3126 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003127 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003128 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00003129 case Instruction::Sub:
3130 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3131 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3132 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003133 DL, TLI, DT);
Duncan Sands0a2c41682010-12-15 14:07:39 +00003134 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003135 case Instruction::FMul:
3136 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003137 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003138 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003139 case Instruction::Mul:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003140 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003141 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00003142 case Instruction::SDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003143 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003144 break;
3145 case Instruction::UDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003146 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003147 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00003148 case Instruction::FDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003149 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Frits van Bommelc2549662011-01-29 15:26:31 +00003150 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00003151 case Instruction::SRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003152 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003153 break;
3154 case Instruction::URem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003155 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003156 break;
3157 case Instruction::FRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003158 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003159 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00003160 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003161 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3162 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3163 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003164 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003165 break;
3166 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003167 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3168 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003169 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003170 break;
3171 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003172 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3173 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003174 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003175 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003176 case Instruction::And:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003177 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003178 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003179 case Instruction::Or:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003180 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003181 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00003182 case Instruction::Xor:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003183 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsc89ac072010-11-17 18:52:15 +00003184 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003185 case Instruction::ICmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003186 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003187 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003188 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003189 case Instruction::FCmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003190 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003191 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003192 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003193 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003194 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003195 I->getOperand(2), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003196 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003197 case Instruction::GetElementPtr: {
3198 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003199 Result = SimplifyGEPInst(Ops, DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003200 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003201 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00003202 case Instruction::InsertValue: {
3203 InsertValueInst *IV = cast<InsertValueInst>(I);
3204 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3205 IV->getInsertedValueOperand(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003206 IV->getIndices(), DL, TLI, DT);
Duncan Sandsfd26a952011-09-05 06:52:48 +00003207 break;
3208 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00003209 case Instruction::PHI:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003210 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT));
Duncan Sands64e41cf2010-11-17 08:35:29 +00003211 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003212 case Instruction::Call: {
3213 CallSite CS(cast<CallInst>(I));
3214 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003215 DL, TLI, DT);
Dan Gohman85977e62011-11-04 18:32:42 +00003216 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003217 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00003218 case Instruction::Trunc:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003219 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003220 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003221 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00003222
3223 /// If called on unreachable code, the above logic may report that the
3224 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00003225 /// detecting that case here, returning a safe value instead.
3226 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003227}
3228
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003229/// \brief Implementation of recursive simplification through an instructions
3230/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00003231///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003232/// This is the common implementation of the recursive simplification routines.
3233/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3234/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3235/// instructions to process and attempt to simplify it using
3236/// InstructionSimplify.
3237///
3238/// This routine returns 'true' only when *it* simplifies something. The passed
3239/// in simplified value does not count toward this.
3240static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003241 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003242 const TargetLibraryInfo *TLI,
3243 const DominatorTree *DT) {
3244 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003245 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands7e800d62010-11-14 11:23:23 +00003246
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003247 // If we have an explicit value to collapse to, do that round of the
3248 // simplification loop by hand initially.
3249 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003250 for (User *U : I->users())
3251 if (U != I)
3252 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00003253
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003254 // Replace the instruction with its simplified value.
3255 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00003256
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003257 // Gracefully handle edge cases where the instruction is not wired into any
3258 // parent block.
3259 if (I->getParent())
3260 I->eraseFromParent();
3261 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003262 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00003263 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003264
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003265 // Note that we must test the size on each iteration, the worklist can grow.
3266 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3267 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00003268
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003269 // See if this instruction simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003270 SimpleV = SimplifyInstruction(I, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003271 if (!SimpleV)
3272 continue;
3273
3274 Simplified = true;
3275
3276 // Stash away all the uses of the old instruction so we can check them for
3277 // recursive simplifications after a RAUW. This is cheaper than checking all
3278 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003279 for (User *U : I->users())
3280 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003281
3282 // Replace the instruction with its simplified value.
3283 I->replaceAllUsesWith(SimpleV);
3284
3285 // Gracefully handle edge cases where the instruction is not wired into any
3286 // parent block.
3287 if (I->getParent())
3288 I->eraseFromParent();
3289 }
3290 return Simplified;
3291}
3292
3293bool llvm::recursivelySimplifyInstruction(Instruction *I,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003294 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003295 const TargetLibraryInfo *TLI,
3296 const DominatorTree *DT) {
Craig Topper9f008862014-04-15 04:59:12 +00003297 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003298}
3299
3300bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003301 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003302 const TargetLibraryInfo *TLI,
3303 const DominatorTree *DT) {
3304 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3305 assert(SimpleV && "Must provide a simplified value.");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003306 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT);
Chris Lattner852d6d62009-11-10 22:26:15 +00003307}