blob: fee6b4fc3771f8a5576eb7bd7b0c68594097aa07 [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
Duncan Sands3547d2e2010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Chris Lattner084a1b52009-11-09 22:57:59 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000024#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "llvm/Analysis/ValueTracking.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 Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/GlobalAlias.h"
30#include "llvm/IR/Operator.h"
Nick Lewycky3cec6f52011-03-04 07:00:57 +000031#include "llvm/Support/ConstantRange.h"
Chandler Carrutha0796552012-03-12 11:19:31 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnera71e9d62009-11-10 00:55:12 +000033#include "llvm/Support/PatternMatch.h"
Duncan Sands5ffc2982010-11-16 12:16:38 +000034#include "llvm/Support/ValueHandle.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000035using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000036using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000037
Chris Lattner9e4aa022011-02-09 17:15:04 +000038enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000039
Duncan Sands3547d2e2010-12-22 09:40:51 +000040STATISTIC(NumExpand, "Number of expansions");
41STATISTIC(NumFactor , "Number of factorizations");
42STATISTIC(NumReassoc, "Number of reassociations");
43
Duncan Sandsb8cee002012-03-13 11:42:19 +000044struct Query {
Rafael Espindola37dc9e12014-02-21 00:06:31 +000045 const DataLayout *DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000046 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
48
Rafael Espindola37dc9e12014-02-21 00:06:31 +000049 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
50 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000051};
52
53static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000055 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000056static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000057 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000058static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000060static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000061
Duncan Sandsc1c92712011-07-26 15:03:53 +000062/// getFalse - For a boolean type, or a vector of boolean type, return false, or
63/// a vector with every element false, as appropriate for the type.
64static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000065 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000066 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
68}
69
70/// getTrue - For a boolean type, or a vector of boolean type, return true, or
71/// a vector with every element true, as appropriate for the type.
72static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000073 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000074 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
76}
77
Duncan Sands3d5692a2011-10-30 19:56:36 +000078/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80 Value *RHS) {
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
82 if (!Cmp)
83 return false;
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87 return true;
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 CRHS == LHS;
90}
91
Duncan Sands5ffc2982010-11-16 12:16:38 +000092/// ValueDominatesPHI - Does the given value dominate the specified phi node?
93static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
95 if (!I)
96 // Arguments and constants dominate all instructions.
97 return true;
98
Chandler Carruth3ffccb32012-03-21 10:58:47 +000099 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103 return false;
104
Duncan Sands5ffc2982010-11-16 12:16:38 +0000105 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000106 if (DT) {
107 if (!DT->isReachableFromEntry(P->getParent()))
108 return true;
109 if (!DT->isReachableFromEntry(I->getParent()))
110 return false;
111 return DT->dominates(I, P);
112 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000113
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117 !isa<InvokeInst>(I))
118 return true;
119
120 return false;
121}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000122
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000123/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127/// Returns the simplified value, or null if no simplification was performed.
128static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000129 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000130 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000132 // Recursion is always used, so bail out at once if we already hit the limit.
133 if (!MaxRecurse--)
134 return 0;
135
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000148 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000149 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000150 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000151 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000153 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000154 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000155 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000156 }
157 }
158
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000171 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000172 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000173 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000174 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000176 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000177 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000178 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000179 }
180 }
181
182 return 0;
183}
184
185/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186/// using the operation OpCodeToExtract. For example, when Opcode is Add and
187/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188/// Returns the simplified value, or null if no simplification was performed.
189static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000190 unsigned OpcToExtract, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000191 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000193 // Recursion is always used, so bail out at once if we already hit the limit.
194 if (!MaxRecurse--)
195 return 0;
196
197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
199
200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201 !Op1 || Op1->getOpcode() != OpcodeToExtract)
202 return 0;
203
204 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000207
208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands772749a2011-01-01 20:08:02 +0000211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212 Value *DD = A == C ? D : C;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000213 // Form "A op' (B op DD)" if it simplifies completely.
214 // Does "B op DD" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000216 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sandsa45cfbd2010-12-22 17:15:25 +0000217 // If V equals B then "A op' V" is just the LHS. If V equals DD then
218 // "A op' V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000219 if (V == B || V == DD) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000220 ++NumFactor;
Duncan Sands772749a2011-01-01 20:08:02 +0000221 return V == B ? LHS : RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000222 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000223 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000225 ++NumFactor;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000226 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000227 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000228 }
229 }
230
231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands772749a2011-01-01 20:08:02 +0000234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235 Value *CC = B == D ? C : D;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000236 // Form "(A op CC) op' B" if it simplifies completely..
237 // Does "A op CC" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000239 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sandsa45cfbd2010-12-22 17:15:25 +0000240 // If V equals A then "V op' B" is just the LHS. If V equals CC then
241 // "V op' B" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000242 if (V == A || V == CC) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000243 ++NumFactor;
Duncan Sands772749a2011-01-01 20:08:02 +0000244 return V == A ? LHS : RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000245 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000246 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000248 ++NumFactor;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000249 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000250 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000251 }
252 }
253
254 return 0;
255}
256
257/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000259static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000260 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
263
264 // Recursion is always used, so bail out at once if we already hit the limit.
265 if (!MaxRecurse--)
266 return 0;
267
268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
270
271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272 if (Op0 && Op0->getOpcode() == Opcode) {
273 Value *A = Op0->getOperand(0);
274 Value *B = Op0->getOperand(1);
275 Value *C = RHS;
276
277 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000279 // It does! Return "A op V" if it simplifies or is already available.
280 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000281 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000282 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000284 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000285 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000286 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 }
288 }
289
290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291 if (Op1 && Op1->getOpcode() == Opcode) {
292 Value *A = LHS;
293 Value *B = Op1->getOperand(0);
294 Value *C = Op1->getOperand(1);
295
296 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000298 // It does! Return "V op C" if it simplifies or is already available.
299 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000300 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000301 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000303 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000304 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000305 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000306 }
307 }
308
309 // The remaining transforms require commutativity as well as associativity.
310 if (!Instruction::isCommutative(Opcode))
311 return 0;
312
313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314 if (Op0 && Op0->getOpcode() == Opcode) {
315 Value *A = Op0->getOperand(0);
316 Value *B = Op0->getOperand(1);
317 Value *C = RHS;
318
319 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000321 // It does! Return "V op B" if it simplifies or is already available.
322 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000323 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000324 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000326 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000327 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000328 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000329 }
330 }
331
332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333 if (Op1 && Op1->getOpcode() == Opcode) {
334 Value *A = LHS;
335 Value *B = Op1->getOperand(0);
336 Value *C = Op1->getOperand(1);
337
338 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000340 // It does! Return "B op V" if it simplifies or is already available.
341 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000342 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000343 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000345 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000346 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000347 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000348 }
349 }
350
351 return 0;
352}
353
Duncan Sandsb0579e92010-11-10 13:00:08 +0000354/// ThreadBinOpOverSelect - In the case of a binary operation with a select
355/// instruction as an operand, try to simplify the binop by seeing whether
356/// evaluating it on both branches of the select results in the same value.
357/// Returns the common value if so, otherwise returns null.
358static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000359 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000360 // Recursion is always used, so bail out at once if we already hit the limit.
361 if (!MaxRecurse--)
362 return 0;
363
Duncan Sandsb0579e92010-11-10 13:00:08 +0000364 SelectInst *SI;
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
367 } else {
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
370 }
371
372 // Evaluate the BinOp on the true and false branches of the select.
373 Value *TV;
374 Value *FV;
375 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000378 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000381 }
382
Duncan Sandse3c53952011-01-01 16:12:09 +0000383 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000384 // If they both failed to simplify then return null.
385 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000386 return TV;
387
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
390 return FV;
391 if (FV && isa<UndefValue>(FV))
392 return TV;
393
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000397 return SI;
398
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000415 return Simplified;
416 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000419 return Simplified;
420 }
421 }
422
423 return 0;
424}
425
426/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427/// try to simplify the comparison by seeing whether both branches of the select
428/// result in the same value. Returns the common value if so, otherwise returns
429/// null.
430static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000431 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000432 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000433 // Recursion is always used, so bail out at once if we already hit the limit.
434 if (!MaxRecurse--)
435 return 0;
436
Duncan Sandsb0579e92010-11-10 13:00:08 +0000437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
439 std::swap(LHS, RHS);
440 Pred = CmpInst::getSwappedPredicate(Pred);
441 }
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000447
Duncan Sands06504022011-02-03 09:37:39 +0000448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000449 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000451 if (TCmp == Cond) {
452 // It not only simplified, it simplified to the select condition. Replace
453 // it with 'true'.
454 TCmp = getTrue(Cond->getType());
455 } else if (!TCmp) {
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
459 return 0;
460 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000461 }
462
Duncan Sands3d5692a2011-10-30 19:56:36 +0000463 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000465 if (FCmp == Cond) {
466 // It not only simplified, it simplified to the select condition. Replace
467 // it with 'false'.
468 FCmp = getFalse(Cond->getType());
469 } else if (!FCmp) {
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
473 return 0;
474 FCmp = getFalse(Cond->getType());
475 }
476
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
479 if (TCmp == FCmp)
480 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000481
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485 return 0;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000491 return V;
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000496 return V;
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500 if (Value *V =
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000502 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000503 return V;
504
Duncan Sandsb0579e92010-11-10 13:00:08 +0000505 return 0;
506}
507
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000508/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510/// it on the incoming phi values yields the same result for every value. If so
511/// returns the common value, otherwise returns null.
512static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000513 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000514 // Recursion is always used, so bail out at once if we already hit the limit.
515 if (!MaxRecurse--)
516 return 0;
517
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000518 PHINode *PI;
519 if (isa<PHINode>(LHS)) {
520 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000521 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000522 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000523 return 0;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000524 } else {
525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000527 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000528 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000529 return 0;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000530 }
531
532 // Evaluate the BinOp on the incoming phi values.
533 Value *CommonValue = 0;
534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000535 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000536 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000537 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000538 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000541 // If the operation failed to simplify, or simplified to a different value
542 // to previously, then give up.
543 if (!V || (CommonValue && V != CommonValue))
544 return 0;
545 CommonValue = V;
546 }
547
548 return CommonValue;
549}
550
551/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552/// try to simplify the comparison by seeing whether comparing with all of the
553/// incoming phi values yields the same result every time. If so returns the
554/// common result, otherwise returns null.
555static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000556 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000557 // Recursion is always used, so bail out at once if we already hit the limit.
558 if (!MaxRecurse--)
559 return 0;
560
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000561 // Make sure the phi is on the LHS.
562 if (!isa<PHINode>(LHS)) {
563 std::swap(LHS, RHS);
564 Pred = CmpInst::getSwappedPredicate(Pred);
565 }
566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567 PHINode *PI = cast<PHINode>(LHS);
568
Duncan Sands5ffc2982010-11-16 12:16:38 +0000569 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000570 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000571 return 0;
572
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000573 // Evaluate the BinOp on the incoming phi values.
574 Value *CommonValue = 0;
575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000576 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000577 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000578 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000580 // If the operation failed to simplify, or simplified to a different value
581 // to previously, then give up.
582 if (!V || (CommonValue && V != CommonValue))
583 return 0;
584 CommonValue = V;
585 }
586
587 return CommonValue;
588}
589
Chris Lattner3d9823b2009-11-27 17:42:22 +0000590/// SimplifyAddInst - Given operands for an Add, see if we can
591/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000592static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000593 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
Duncan Sandsb8cee002012-03-13 11:42:19 +0000597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000598 Q.DL, Q.TLI);
Chris Lattner3d9823b2009-11-27 17:42:22 +0000599 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000600
Chris Lattner3d9823b2009-11-27 17:42:22 +0000601 // Canonicalize the constant to the RHS.
602 std::swap(Op0, Op1);
603 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000604
Duncan Sands0a2c41682010-12-15 14:07:39 +0000605 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000606 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000607 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000608
Duncan Sands0a2c41682010-12-15 14:07:39 +0000609 // X + 0 -> X
610 if (match(Op1, m_Zero()))
611 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000612
Duncan Sands0a2c41682010-12-15 14:07:39 +0000613 // X + (Y - X) -> Y
614 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000615 // Eg: X + -X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000616 Value *Y = 0;
617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000619 return Y;
620
621 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000622 if (match(Op0, m_Not(m_Specific(Op1))) ||
623 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000624 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000625
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000626 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000627 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000629 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000630
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000631 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000633 MaxRecurse))
634 return V;
635
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000636 // Mul distributes over Add. Try some generic simplifications based on this.
637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000638 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000639 return V;
640
Duncan Sandsb238de02010-11-19 09:20:39 +0000641 // Threading Add over selects and phi nodes is pointless, so don't bother.
642 // Threading over the select in "A + select(cond, B, C)" means evaluating
643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644 // only if B and C are equal. If B and C are equal then (since we assume
645 // that operands have already been simplified) "select(cond, B, C)" should
646 // have been simplified to the common value of B and C already. Analysing
647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
648 // for threading over phi nodes.
649
Chris Lattner3d9823b2009-11-27 17:42:22 +0000650 return 0;
651}
652
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000653Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000654 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000655 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000657 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000658}
659
Chandler Carrutha0796552012-03-12 11:19:31 +0000660/// \brief Compute the base pointer and cumulative constant offsets for V.
661///
662/// This strips all constant offsets off of V, leaving it the base pointer, and
663/// accumulates the total constant offset applied in the returned constant. It
664/// returns 0 if V is not a pointer, and returns the constant '0' if there are
665/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000666///
667/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
668/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
669/// folding.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000670static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000671 Value *&V,
672 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000673 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000674
Dan Gohman18c77a12013-01-31 02:50:36 +0000675 // Without DataLayout, just be conservative for now. Theoretically, more could
676 // be done in this case.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000677 if (!DL)
Dan Gohman18c77a12013-01-31 02:50:36 +0000678 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
679
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000680 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000681 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000682
683 // Even though we don't look through PHI nodes, we could be called on an
684 // instruction in an unreachable block, which may be on a cycle.
685 SmallPtrSet<Value *, 4> Visited;
686 Visited.insert(V);
687 do {
688 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000689 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000690 !GEP->accumulateConstantOffset(*DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000691 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000692 V = GEP->getPointerOperand();
693 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000694 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000695 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
696 if (GA->mayBeOverridden())
697 break;
698 V = GA->getAliasee();
699 } else {
700 break;
701 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000702 assert(V->getType()->getScalarType()->isPointerTy() &&
703 "Unexpected operand type!");
Chandler Carrutha0796552012-03-12 11:19:31 +0000704 } while (Visited.insert(V));
705
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000706 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
707 if (V->getType()->isVectorTy())
708 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
709 OffsetIntPtr);
710 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000711}
712
713/// \brief Compute the constant difference between two pointer values.
714/// If the difference is not a constant, returns zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000715static Constant *computePointerDifference(const DataLayout *DL,
Chandler Carrutha0796552012-03-12 11:19:31 +0000716 Value *LHS, Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000717 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
718 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000719
720 // If LHS and RHS are not related via constant offsets to the same base
721 // value, there is nothing we can do here.
722 if (LHS != RHS)
723 return 0;
724
725 // Otherwise, the difference of LHS - RHS can be computed as:
726 // LHS - RHS
727 // = (LHSOffset + Base) - (RHSOffset + Base)
728 // = LHSOffset - RHSOffset
729 return ConstantExpr::getSub(LHSOffset, RHSOffset);
730}
731
Duncan Sands0a2c41682010-12-15 14:07:39 +0000732/// SimplifySubInst - Given operands for a Sub, see if we can
733/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000734static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000735 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000736 if (Constant *CLHS = dyn_cast<Constant>(Op0))
737 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
738 Constant *Ops[] = { CLHS, CRHS };
739 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000740 Ops, Q.DL, Q.TLI);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000741 }
742
743 // X - undef -> undef
744 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000745 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000746 return UndefValue::get(Op0->getType());
747
748 // X - 0 -> X
749 if (match(Op1, m_Zero()))
750 return Op0;
751
752 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000753 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000754 return Constant::getNullValue(Op0->getType());
755
Duncan Sands9b8e2bd2011-01-18 09:24:58 +0000756 // (X*2) - X -> X
757 // (X<<1) - X -> X
Duncan Sands99589d02011-01-18 11:50:19 +0000758 Value *X = 0;
Duncan Sands9b8e2bd2011-01-18 09:24:58 +0000759 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
760 match(Op0, m_Shl(m_Specific(Op1), m_One())))
761 return Op1;
762
Duncan Sands99589d02011-01-18 11:50:19 +0000763 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
764 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
765 Value *Y = 0, *Z = Op1;
766 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
767 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000768 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000769 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000770 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000771 // It does, we successfully reassociated!
772 ++NumReassoc;
773 return W;
774 }
775 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000776 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000777 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000778 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000779 // It does, we successfully reassociated!
780 ++NumReassoc;
781 return W;
782 }
783 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000784
Duncan Sands99589d02011-01-18 11:50:19 +0000785 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
786 // For example, X - (X + 1) -> -1
787 X = Op0;
788 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
789 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000790 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000791 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000792 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000793 // It does, we successfully reassociated!
794 ++NumReassoc;
795 return W;
796 }
797 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000798 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000799 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000800 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000801 // It does, we successfully reassociated!
802 ++NumReassoc;
803 return W;
804 }
805 }
806
807 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
808 // For example, X - (X - Y) -> Y.
809 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000810 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
811 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000812 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000813 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000814 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000815 // It does, we successfully reassociated!
816 ++NumReassoc;
817 return W;
818 }
819
Duncan Sands395ac42d2012-03-13 14:07:05 +0000820 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
821 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
822 match(Op1, m_Trunc(m_Value(Y))))
823 if (X->getType() == Y->getType())
824 // See if "V === X - Y" simplifies.
825 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
826 // It does! Now see if "trunc V" simplifies.
827 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
828 // It does, return the simplified "trunc V".
829 return W;
830
831 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000832 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000833 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000834 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000835 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
836
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000837 // Mul distributes over Sub. Try some generic simplifications based on this.
838 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000839 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000840 return V;
841
Duncan Sands99589d02011-01-18 11:50:19 +0000842 // i1 sub -> xor.
843 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000844 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000845 return V;
846
Duncan Sands0a2c41682010-12-15 14:07:39 +0000847 // Threading Sub over selects and phi nodes is pointless, so don't bother.
848 // Threading over the select in "A - select(cond, B, C)" means evaluating
849 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
850 // only if B and C are equal. If B and C are equal then (since we assume
851 // that operands have already been simplified) "select(cond, B, C)" should
852 // have been simplified to the common value of B and C already. Analysing
853 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
854 // for threading over phi nodes.
855
856 return 0;
857}
858
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000859Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000860 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000861 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000862 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000863 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000864}
865
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000866/// Given operands for an FAdd, see if we can fold the result. If not, this
867/// returns null.
868static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
869 const Query &Q, unsigned MaxRecurse) {
870 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
871 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
872 Constant *Ops[] = { CLHS, CRHS };
873 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000874 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000875 }
876
877 // Canonicalize the constant to the RHS.
878 std::swap(Op0, Op1);
879 }
880
881 // fadd X, -0 ==> X
882 if (match(Op1, m_NegZero()))
883 return Op0;
884
885 // fadd X, 0 ==> X, when we know X is not -0
886 if (match(Op1, m_Zero()) &&
887 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
888 return Op0;
889
890 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
891 // where nnan and ninf have to occur at least once somewhere in this
892 // expression
893 Value *SubOp = 0;
894 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
895 SubOp = Op1;
896 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
897 SubOp = Op0;
898 if (SubOp) {
899 Instruction *FSub = cast<Instruction>(SubOp);
900 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
901 (FMF.noInfs() || FSub->hasNoInfs()))
902 return Constant::getNullValue(Op0->getType());
903 }
904
905 return 0;
906}
907
908/// Given operands for an FSub, see if we can fold the result. If not, this
909/// returns null.
910static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
911 const Query &Q, unsigned MaxRecurse) {
912 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
913 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
914 Constant *Ops[] = { CLHS, CRHS };
915 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000916 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000917 }
918 }
919
920 // fsub X, 0 ==> X
921 if (match(Op1, m_Zero()))
922 return Op0;
923
924 // fsub X, -0 ==> X, when we know X is not -0
925 if (match(Op1, m_NegZero()) &&
926 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
927 return Op0;
928
929 // fsub 0, (fsub -0.0, X) ==> X
930 Value *X;
931 if (match(Op0, m_AnyZero())) {
932 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
933 return X;
934 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
935 return X;
936 }
937
938 // fsub nnan ninf x, x ==> 0.0
939 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
940 return Constant::getNullValue(Op0->getType());
941
942 return 0;
943}
944
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000945/// Given the operands for an FMul, see if we can fold the result
946static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
947 FastMathFlags FMF,
948 const Query &Q,
949 unsigned MaxRecurse) {
950 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
951 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
952 Constant *Ops[] = { CLHS, CRHS };
953 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000954 Ops, Q.DL, Q.TLI);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000955 }
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000956
957 // Canonicalize the constant to the RHS.
958 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000959 }
960
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000961 // fmul X, 1.0 ==> X
962 if (match(Op1, m_FPOne()))
963 return Op0;
964
965 // fmul nnan nsz X, 0 ==> 0
966 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
967 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000968
969 return 0;
970}
971
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000972/// SimplifyMulInst - Given operands for a Mul, see if we can
973/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000974static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
975 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000976 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
977 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
978 Constant *Ops[] = { CLHS, CRHS };
979 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000980 Ops, Q.DL, Q.TLI);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000981 }
982
983 // Canonicalize the constant to the RHS.
984 std::swap(Op0, Op1);
985 }
986
987 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000988 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000989 return Constant::getNullValue(Op0->getType());
990
991 // X * 0 -> 0
992 if (match(Op1, m_Zero()))
993 return Op1;
994
995 // X * 1 -> X
996 if (match(Op1, m_One()))
997 return Op0;
998
Duncan Sandsb67edc62011-01-30 18:03:50 +0000999 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001000 Value *X = 0;
1001 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1002 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
1003 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +00001004
Nick Lewyckyb89d9a42011-01-29 19:55:23 +00001005 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +00001006 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001007 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +00001008 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001009
1010 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001011 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001012 MaxRecurse))
1013 return V;
1014
1015 // Mul distributes over Add. Try some generic simplifications based on this.
1016 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001017 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001018 return V;
1019
1020 // If the operation is with the result of a select instruction, check whether
1021 // operating on either branch of the select always yields the same value.
1022 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001023 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001024 MaxRecurse))
1025 return V;
1026
1027 // If the operation is with the result of a phi instruction, check whether
1028 // operating on all incoming values of the phi always yields the same value.
1029 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001030 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001031 MaxRecurse))
1032 return V;
1033
1034 return 0;
1035}
1036
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001037Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001038 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001039 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001040 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001041}
1042
1043Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001044 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001045 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001046 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00001047}
1048
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001049Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1050 FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001051 const DataLayout *DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001052 const TargetLibraryInfo *TLI,
1053 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001054 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001055}
1056
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001057Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001058 const TargetLibraryInfo *TLI,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001059 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001060 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001061}
1062
Duncan Sands771e82a2011-01-28 16:51:11 +00001063/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1064/// fold the result. If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001065static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001066 const Query &Q, unsigned MaxRecurse) {
Duncan Sands771e82a2011-01-28 16:51:11 +00001067 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1068 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1069 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001070 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands771e82a2011-01-28 16:51:11 +00001071 }
1072 }
1073
Duncan Sands65995fa2011-01-28 18:50:50 +00001074 bool isSigned = Opcode == Instruction::SDiv;
1075
Duncan Sands771e82a2011-01-28 16:51:11 +00001076 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001077 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001078 return Op1;
1079
1080 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001081 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001082 return Constant::getNullValue(Op0->getType());
1083
1084 // 0 / X -> 0, we don't need to preserve faults!
1085 if (match(Op0, m_Zero()))
1086 return Op0;
1087
1088 // X / 1 -> X
1089 if (match(Op1, m_One()))
1090 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001091
1092 if (Op0->getType()->isIntegerTy(1))
1093 // It can't be division by zero, hence it must be division by one.
1094 return Op0;
1095
1096 // X / X -> 1
1097 if (Op0 == Op1)
1098 return ConstantInt::get(Op0->getType(), 1);
1099
1100 // (X * Y) / Y -> X if the multiplication does not overflow.
1101 Value *X = 0, *Y = 0;
1102 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1103 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001104 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001105 // If the Mul knows it does not overflow, then we are good to go.
1106 if ((isSigned && Mul->hasNoSignedWrap()) ||
1107 (!isSigned && Mul->hasNoUnsignedWrap()))
1108 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001109 // If X has the form X = A / Y then X * Y cannot overflow.
1110 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1111 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1112 return X;
1113 }
1114
Duncan Sands65995fa2011-01-28 18:50:50 +00001115 // (X rem Y) / Y -> 0
1116 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1117 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1118 return Constant::getNullValue(Op0->getType());
1119
1120 // If the operation is with the result of a select instruction, check whether
1121 // operating on either branch of the select always yields the same value.
1122 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001123 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001124 return V;
1125
1126 // If the operation is with the result of a phi instruction, check whether
1127 // operating on all incoming values of the phi always yields the same value.
1128 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001129 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001130 return V;
1131
Duncan Sands771e82a2011-01-28 16:51:11 +00001132 return 0;
1133}
1134
1135/// SimplifySDivInst - Given operands for an SDiv, see if we can
1136/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001137static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1138 unsigned MaxRecurse) {
1139 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001140 return V;
1141
Duncan Sands771e82a2011-01-28 16:51:11 +00001142 return 0;
1143}
1144
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001145Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001146 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001147 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001148 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001149}
1150
1151/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1152/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001153static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1154 unsigned MaxRecurse) {
1155 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001156 return V;
1157
Duncan Sands771e82a2011-01-28 16:51:11 +00001158 return 0;
1159}
1160
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001161Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001162 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001163 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001164 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001165}
1166
Duncan Sandsb8cee002012-03-13 11:42:19 +00001167static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1168 unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001169 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001170 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001171 return Op0;
1172
1173 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001174 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001175 return Op1;
1176
1177 return 0;
1178}
1179
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001180Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001181 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001182 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001183 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001184}
1185
Duncan Sandsa3e36992011-05-02 16:27:02 +00001186/// SimplifyRem - Given operands for an SRem or URem, see if we can
1187/// fold the result. If not, this returns null.
1188static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001189 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001190 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1191 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1192 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001193 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001194 }
1195 }
1196
Duncan Sandsa3e36992011-05-02 16:27:02 +00001197 // X % undef -> undef
1198 if (match(Op1, m_Undef()))
1199 return Op1;
1200
1201 // undef % X -> 0
1202 if (match(Op0, m_Undef()))
1203 return Constant::getNullValue(Op0->getType());
1204
1205 // 0 % X -> 0, we don't need to preserve faults!
1206 if (match(Op0, m_Zero()))
1207 return Op0;
1208
1209 // X % 0 -> undef, we don't need to preserve faults!
1210 if (match(Op1, m_Zero()))
1211 return UndefValue::get(Op0->getType());
1212
1213 // X % 1 -> 0
1214 if (match(Op1, m_One()))
1215 return Constant::getNullValue(Op0->getType());
1216
1217 if (Op0->getType()->isIntegerTy(1))
1218 // It can't be remainder by zero, hence it must be remainder by one.
1219 return Constant::getNullValue(Op0->getType());
1220
1221 // X % X -> 0
1222 if (Op0 == Op1)
1223 return Constant::getNullValue(Op0->getType());
1224
1225 // If the operation is with the result of a select instruction, check whether
1226 // operating on either branch of the select always yields the same value.
1227 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001228 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001229 return V;
1230
1231 // If the operation is with the result of a phi instruction, check whether
1232 // operating on all incoming values of the phi always yields the same value.
1233 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001234 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001235 return V;
1236
1237 return 0;
1238}
1239
1240/// SimplifySRemInst - Given operands for an SRem, see if we can
1241/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001242static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1243 unsigned MaxRecurse) {
1244 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001245 return V;
1246
1247 return 0;
1248}
1249
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001250Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001251 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001252 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001253 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001254}
1255
1256/// SimplifyURemInst - Given operands for a URem, see if we can
1257/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001258static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001259 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001260 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001261 return V;
1262
1263 return 0;
1264}
1265
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001266Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001267 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001268 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001269 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001270}
1271
Duncan Sandsb8cee002012-03-13 11:42:19 +00001272static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001273 unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001274 // undef % X -> undef (the undef could be a snan).
1275 if (match(Op0, m_Undef()))
1276 return Op0;
1277
1278 // X % undef -> undef
1279 if (match(Op1, m_Undef()))
1280 return Op1;
1281
1282 return 0;
1283}
1284
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001285Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001286 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001287 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001288 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001289}
1290
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001291/// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1292static bool isUndefShift(Value *Amount) {
1293 Constant *C = dyn_cast<Constant>(Amount);
1294 if (!C)
1295 return false;
1296
1297 // X shift by undef -> undef because it may shift by the bitwidth.
1298 if (isa<UndefValue>(C))
1299 return true;
1300
1301 // Shifting by the bitwidth or more is undefined.
1302 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1303 if (CI->getValue().getLimitedValue() >=
1304 CI->getType()->getScalarSizeInBits())
1305 return true;
1306
1307 // If all lanes of a vector shift are undefined the whole shift is.
1308 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1309 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1310 if (!isUndefShift(C->getAggregateElement(I)))
1311 return false;
1312 return true;
1313 }
1314
1315 return false;
1316}
1317
Duncan Sands571fd9a2011-01-14 14:44:12 +00001318/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sands7f60dc12011-01-14 00:37:45 +00001319/// fold the result. If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001320static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001321 const Query &Q, unsigned MaxRecurse) {
Duncan Sands7f60dc12011-01-14 00:37:45 +00001322 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1323 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1324 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001325 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001326 }
1327 }
1328
Duncan Sands571fd9a2011-01-14 14:44:12 +00001329 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001330 if (match(Op0, m_Zero()))
1331 return Op0;
1332
Duncan Sands571fd9a2011-01-14 14:44:12 +00001333 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001334 if (match(Op1, m_Zero()))
1335 return Op0;
1336
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001337 // Fold undefined shifts.
1338 if (isUndefShift(Op1))
1339 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001340
Duncan Sands571fd9a2011-01-14 14:44:12 +00001341 // If the operation is with the result of a select instruction, check whether
1342 // operating on either branch of the select always yields the same value.
1343 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001344 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001345 return V;
1346
1347 // If the operation is with the result of a phi instruction, check whether
1348 // operating on all incoming values of the phi always yields the same value.
1349 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001350 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001351 return V;
1352
1353 return 0;
1354}
1355
1356/// SimplifyShlInst - Given operands for an Shl, see if we can
1357/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001358static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001359 const Query &Q, unsigned MaxRecurse) {
1360 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001361 return V;
1362
1363 // undef << X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001364 if (match(Op0, m_Undef()))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001365 return Constant::getNullValue(Op0->getType());
1366
Chris Lattner9e4aa022011-02-09 17:15:04 +00001367 // (X >> A) << A -> X
1368 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001369 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001370 return X;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001371 return 0;
1372}
1373
Chris Lattner9e4aa022011-02-09 17:15:04 +00001374Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001375 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001376 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001377 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001378 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001379}
1380
1381/// SimplifyLShrInst - Given operands for an LShr, see if we can
1382/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001383static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001384 const Query &Q, unsigned MaxRecurse) {
1385 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001386 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001387
David Majnemera80fed72013-07-09 22:01:22 +00001388 // X >> X -> 0
1389 if (Op0 == Op1)
1390 return Constant::getNullValue(Op0->getType());
1391
Duncan Sands7f60dc12011-01-14 00:37:45 +00001392 // undef >>l X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001393 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001394 return Constant::getNullValue(Op0->getType());
1395
Chris Lattner9e4aa022011-02-09 17:15:04 +00001396 // (X << A) >> A -> X
1397 Value *X;
1398 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1399 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1400 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001401
Duncan Sands7f60dc12011-01-14 00:37:45 +00001402 return 0;
1403}
1404
Chris Lattner9e4aa022011-02-09 17:15:04 +00001405Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001406 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001407 const TargetLibraryInfo *TLI,
1408 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001409 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001410 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001411}
1412
1413/// SimplifyAShrInst - Given operands for an AShr, see if we can
1414/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001415static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001416 const Query &Q, unsigned MaxRecurse) {
1417 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001418 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001419
David Majnemera80fed72013-07-09 22:01:22 +00001420 // X >> X -> 0
1421 if (Op0 == Op1)
1422 return Constant::getNullValue(Op0->getType());
1423
Duncan Sands7f60dc12011-01-14 00:37:45 +00001424 // all ones >>a X -> all ones
1425 if (match(Op0, m_AllOnes()))
1426 return Op0;
1427
1428 // undef >>a X -> all ones
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001429 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001430 return Constant::getAllOnesValue(Op0->getType());
1431
Chris Lattner9e4aa022011-02-09 17:15:04 +00001432 // (X << A) >> A -> X
1433 Value *X;
1434 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1435 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1436 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001437
Duncan Sands7f60dc12011-01-14 00:37:45 +00001438 return 0;
1439}
1440
Chris Lattner9e4aa022011-02-09 17:15:04 +00001441Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001442 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001443 const TargetLibraryInfo *TLI,
1444 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001445 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001446 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001447}
1448
Chris Lattnera71e9d62009-11-10 00:55:12 +00001449/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner084a1b52009-11-09 22:57:59 +00001450/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001451static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001452 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001453 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1454 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1455 Constant *Ops[] = { CLHS, CRHS };
1456 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001457 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001458 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001459
Chris Lattnera71e9d62009-11-10 00:55:12 +00001460 // Canonicalize the constant to the RHS.
1461 std::swap(Op0, Op1);
1462 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001463
Chris Lattnera71e9d62009-11-10 00:55:12 +00001464 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001465 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001466 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001467
Chris Lattnera71e9d62009-11-10 00:55:12 +00001468 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001469 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001470 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001471
Duncan Sandsc89ac072010-11-17 18:52:15 +00001472 // X & 0 = 0
1473 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001474 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001475
Duncan Sandsc89ac072010-11-17 18:52:15 +00001476 // X & -1 = X
1477 if (match(Op1, m_AllOnes()))
1478 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001479
Chris Lattnera71e9d62009-11-10 00:55:12 +00001480 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001481 if (match(Op0, m_Not(m_Specific(Op1))) ||
1482 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001483 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001484
Chris Lattnera71e9d62009-11-10 00:55:12 +00001485 // (A | ?) & A = A
Chris Lattner9e4aa022011-02-09 17:15:04 +00001486 Value *A = 0, *B = 0;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001487 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001488 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001489 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001490
Chris Lattnera71e9d62009-11-10 00:55:12 +00001491 // A & (A | ?) = A
1492 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001493 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001494 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001495
Duncan Sandsba286d72011-10-26 20:55:21 +00001496 // A & (-A) = A if A is a power of two or zero.
1497 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1498 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindola319f74c2012-12-13 03:37:24 +00001499 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001500 return Op0;
Rafael Espindola319f74c2012-12-13 03:37:24 +00001501 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001502 return Op1;
1503 }
1504
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001505 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001506 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1507 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001508 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001509
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001510 // And distributes over Or. Try some generic simplifications based on this.
1511 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001512 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001513 return V;
1514
1515 // And distributes over Xor. Try some generic simplifications based on this.
1516 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001517 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001518 return V;
1519
1520 // Or distributes over And. Try some generic simplifications based on this.
1521 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001522 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001523 return V;
1524
Duncan Sandsb0579e92010-11-10 13:00:08 +00001525 // If the operation is with the result of a select instruction, check whether
1526 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001527 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001528 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1529 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001530 return V;
1531
1532 // If the operation is with the result of a phi instruction, check whether
1533 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001534 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001535 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001536 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001537 return V;
1538
Chris Lattner084a1b52009-11-09 22:57:59 +00001539 return 0;
1540}
1541
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001542Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001543 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001544 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001545 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001546}
1547
Chris Lattnera71e9d62009-11-10 00:55:12 +00001548/// SimplifyOrInst - Given operands for an Or, see if we can
1549/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001550static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1551 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001552 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1553 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1554 Constant *Ops[] = { CLHS, CRHS };
1555 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001556 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001557 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001558
Chris Lattnera71e9d62009-11-10 00:55:12 +00001559 // Canonicalize the constant to the RHS.
1560 std::swap(Op0, Op1);
1561 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001562
Chris Lattnera71e9d62009-11-10 00:55:12 +00001563 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001564 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001565 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001566
Chris Lattnera71e9d62009-11-10 00:55:12 +00001567 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001568 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001569 return Op0;
1570
Duncan Sandsc89ac072010-11-17 18:52:15 +00001571 // X | 0 = X
1572 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001573 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001574
Duncan Sandsc89ac072010-11-17 18:52:15 +00001575 // X | -1 = -1
1576 if (match(Op1, m_AllOnes()))
1577 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001578
Chris Lattnera71e9d62009-11-10 00:55:12 +00001579 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001580 if (match(Op0, m_Not(m_Specific(Op1))) ||
1581 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001582 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001583
Chris Lattnera71e9d62009-11-10 00:55:12 +00001584 // (A & ?) | A = A
Chris Lattner9e4aa022011-02-09 17:15:04 +00001585 Value *A = 0, *B = 0;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001586 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001587 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001588 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001589
Chris Lattnera71e9d62009-11-10 00:55:12 +00001590 // A | (A & ?) = A
1591 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001592 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001593 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001594
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001595 // ~(A & ?) | A = -1
1596 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1597 (A == Op1 || B == Op1))
1598 return Constant::getAllOnesValue(Op1->getType());
1599
1600 // A | ~(A & ?) = -1
1601 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1602 (A == Op0 || B == Op0))
1603 return Constant::getAllOnesValue(Op0->getType());
1604
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001605 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001606 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1607 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001608 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001609
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001610 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001611 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1612 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001613 return V;
1614
1615 // And distributes over Or. Try some generic simplifications based on this.
1616 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001617 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001618 return V;
1619
Duncan Sandsb0579e92010-11-10 13:00:08 +00001620 // If the operation is with the result of a select instruction, check whether
1621 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001622 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001623 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001624 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001625 return V;
1626
1627 // If the operation is with the result of a phi instruction, check whether
1628 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001629 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001630 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001631 return V;
1632
Chris Lattnera71e9d62009-11-10 00:55:12 +00001633 return 0;
1634}
1635
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001636Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001637 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001638 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001639 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001640}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001641
Duncan Sandsc89ac072010-11-17 18:52:15 +00001642/// SimplifyXorInst - Given operands for a Xor, see if we can
1643/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001644static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1645 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001646 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1647 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1648 Constant *Ops[] = { CLHS, CRHS };
1649 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001650 Ops, Q.DL, Q.TLI);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001651 }
1652
1653 // Canonicalize the constant to the RHS.
1654 std::swap(Op0, Op1);
1655 }
1656
1657 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001658 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001659 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001660
1661 // A ^ 0 = A
1662 if (match(Op1, m_Zero()))
1663 return Op0;
1664
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001665 // A ^ A = 0
1666 if (Op0 == Op1)
1667 return Constant::getNullValue(Op0->getType());
1668
Duncan Sandsc89ac072010-11-17 18:52:15 +00001669 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001670 if (match(Op0, m_Not(m_Specific(Op1))) ||
1671 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001672 return Constant::getAllOnesValue(Op0->getType());
1673
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001674 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001675 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1676 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001677 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001678
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001679 // And distributes over Xor. Try some generic simplifications based on this.
1680 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001681 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001682 return V;
1683
Duncan Sandsb238de02010-11-19 09:20:39 +00001684 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1685 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1686 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1687 // only if B and C are equal. If B and C are equal then (since we assume
1688 // that operands have already been simplified) "select(cond, B, C)" should
1689 // have been simplified to the common value of B and C already. Analysing
1690 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1691 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001692
1693 return 0;
1694}
1695
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001696Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001697 const TargetLibraryInfo *TLI,
Duncan Sandsc89ac072010-11-17 18:52:15 +00001698 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001699 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001700}
1701
Chris Lattner229907c2011-07-18 04:54:35 +00001702static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001703 return CmpInst::makeCmpResultType(Op->getType());
1704}
1705
Duncan Sandsaf327282011-05-07 16:56:49 +00001706/// ExtractEquivalentCondition - Rummage around inside V looking for something
1707/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1708/// otherwise return null. Helper function for analyzing max/min idioms.
1709static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1710 Value *LHS, Value *RHS) {
1711 SelectInst *SI = dyn_cast<SelectInst>(V);
1712 if (!SI)
1713 return 0;
1714 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1715 if (!Cmp)
1716 return 0;
1717 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1718 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1719 return Cmp;
1720 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1721 LHS == CmpRHS && RHS == CmpLHS)
1722 return Cmp;
1723 return 0;
1724}
1725
Dan Gohman9631d902013-02-01 00:49:06 +00001726// A significant optimization not implemented here is assuming that alloca
1727// addresses are not equal to incoming argument values. They don't *alias*,
1728// as we say, but that doesn't mean they aren't equal, so we take a
1729// conservative approach.
1730//
1731// This is inspired in part by C++11 5.10p1:
1732// "Two pointers of the same type compare equal if and only if they are both
1733// null, both point to the same function, or both represent the same
1734// address."
1735//
1736// This is pretty permissive.
1737//
1738// It's also partly due to C11 6.5.9p6:
1739// "Two pointers compare equal if and only if both are null pointers, both are
1740// pointers to the same object (including a pointer to an object and a
1741// subobject at its beginning) or function, both are pointers to one past the
1742// last element of the same array object, or one is a pointer to one past the
1743// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001744// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001745// object in the address space.)
1746//
1747// C11's version is more restrictive, however there's no reason why an argument
1748// couldn't be a one-past-the-end value for a stack object in the caller and be
1749// equal to the beginning of a stack object in the callee.
1750//
1751// If the C and C++ standards are ever made sufficiently restrictive in this
1752// area, it may be possible to update LLVM's semantics accordingly and reinstate
1753// this optimization.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001754static Constant *computePointerICmp(const DataLayout *DL,
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001755 const TargetLibraryInfo *TLI,
Chandler Carruth8059c842012-03-25 21:28:14 +00001756 CmpInst::Predicate Pred,
1757 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001758 // First, skip past any trivial no-ops.
1759 LHS = LHS->stripPointerCasts();
1760 RHS = RHS->stripPointerCasts();
1761
1762 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001763 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001764 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1765 return ConstantInt::get(GetCompareTy(LHS),
1766 !CmpInst::isTrueWhenEqual(Pred));
1767
Chandler Carruth8059c842012-03-25 21:28:14 +00001768 // We can only fold certain predicates on pointer comparisons.
1769 switch (Pred) {
1770 default:
1771 return 0;
1772
1773 // Equality comaprisons are easy to fold.
1774 case CmpInst::ICMP_EQ:
1775 case CmpInst::ICMP_NE:
1776 break;
1777
1778 // We can only handle unsigned relational comparisons because 'inbounds' on
1779 // a GEP only protects against unsigned wrapping.
1780 case CmpInst::ICMP_UGT:
1781 case CmpInst::ICMP_UGE:
1782 case CmpInst::ICMP_ULT:
1783 case CmpInst::ICMP_ULE:
1784 // However, we have to switch them to their signed variants to handle
1785 // negative indices from the base pointer.
1786 Pred = ICmpInst::getSignedPredicate(Pred);
1787 break;
1788 }
1789
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001790 // Strip off any constant offsets so that we can reason about them.
1791 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1792 // here and compare base addresses like AliasAnalysis does, however there are
1793 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1794 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1795 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001796 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1797 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001798
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001799 // If LHS and RHS are related via constant offsets to the same base
1800 // value, we can replace it with an icmp which just compares the offsets.
1801 if (LHS == RHS)
1802 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001803
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001804 // Various optimizations for (in)equality comparisons.
1805 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1806 // Different non-empty allocations that exist at the same time have
1807 // different addresses (if the program can tell). Global variables always
1808 // exist, so they always exist during the lifetime of each other and all
1809 // allocas. Two different allocas usually have different addresses...
1810 //
1811 // However, if there's an @llvm.stackrestore dynamically in between two
1812 // allocas, they may have the same address. It's tempting to reduce the
1813 // scope of the problem by only looking at *static* allocas here. That would
1814 // cover the majority of allocas while significantly reducing the likelihood
1815 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1816 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1817 // an entry block. Also, if we have a block that's not attached to a
1818 // function, we can't tell if it's "static" under the current definition.
1819 // Theoretically, this problem could be fixed by creating a new kind of
1820 // instruction kind specifically for static allocas. Such a new instruction
1821 // could be required to be at the top of the entry block, thus preventing it
1822 // from being subject to a @llvm.stackrestore. Instcombine could even
1823 // convert regular allocas into these special allocas. It'd be nifty.
1824 // However, until then, this problem remains open.
1825 //
1826 // So, we'll assume that two non-empty allocas have different addresses
1827 // for now.
1828 //
1829 // With all that, if the offsets are within the bounds of their allocations
1830 // (and not one-past-the-end! so we can't use inbounds!), and their
1831 // allocations aren't the same, the pointers are not equal.
1832 //
1833 // Note that it's not necessary to check for LHS being a global variable
1834 // address, due to canonicalization and constant folding.
1835 if (isa<AllocaInst>(LHS) &&
1836 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001837 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1838 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001839 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001840 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001841 getObjectSize(LHS, LHSSize, DL, TLI) &&
1842 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001843 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1844 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001845 if (!LHSOffsetValue.isNegative() &&
1846 !RHSOffsetValue.isNegative() &&
1847 LHSOffsetValue.ult(LHSSize) &&
1848 RHSOffsetValue.ult(RHSSize)) {
1849 return ConstantInt::get(GetCompareTy(LHS),
1850 !CmpInst::isTrueWhenEqual(Pred));
1851 }
1852 }
1853
1854 // Repeat the above check but this time without depending on DataLayout
1855 // or being able to compute a precise size.
1856 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1857 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1858 LHSOffset->isNullValue() &&
1859 RHSOffset->isNullValue())
1860 return ConstantInt::get(GetCompareTy(LHS),
1861 !CmpInst::isTrueWhenEqual(Pred));
1862 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001863
1864 // Even if an non-inbounds GEP occurs along the path we can still optimize
1865 // equality comparisons concerning the result. We avoid walking the whole
1866 // chain again by starting where the last calls to
1867 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001868 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1869 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001870 if (LHS == RHS)
1871 return ConstantExpr::getICmp(Pred,
1872 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1873 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001874 }
1875
1876 // Otherwise, fail.
1877 return 0;
Chandler Carruth8059c842012-03-25 21:28:14 +00001878}
Chris Lattner01990f02012-02-24 19:01:58 +00001879
Chris Lattnerc1f19072009-11-09 23:28:39 +00001880/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1881/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001882static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001883 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00001884 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00001885 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00001886
Chris Lattnera71e9d62009-11-10 00:55:12 +00001887 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001888 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001889 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001890
1891 // If we have a constant, make sure it is on the RHS.
1892 std::swap(LHS, RHS);
1893 Pred = CmpInst::getSwappedPredicate(Pred);
1894 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001895
Chris Lattner229907c2011-07-18 04:54:35 +00001896 Type *ITy = GetCompareTy(LHS); // The return type.
1897 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00001898
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001899 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00001900 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1901 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00001902 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001903 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00001904
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001905 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00001906 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001907 switch (Pred) {
1908 default: break;
1909 case ICmpInst::ICMP_EQ:
1910 // X == 1 -> X
1911 if (match(RHS, m_One()))
1912 return LHS;
1913 break;
1914 case ICmpInst::ICMP_NE:
1915 // X != 0 -> X
1916 if (match(RHS, m_Zero()))
1917 return LHS;
1918 break;
1919 case ICmpInst::ICMP_UGT:
1920 // X >u 0 -> X
1921 if (match(RHS, m_Zero()))
1922 return LHS;
1923 break;
1924 case ICmpInst::ICMP_UGE:
1925 // X >=u 1 -> X
1926 if (match(RHS, m_One()))
1927 return LHS;
1928 break;
1929 case ICmpInst::ICMP_SLT:
1930 // X <s 0 -> X
1931 if (match(RHS, m_Zero()))
1932 return LHS;
1933 break;
1934 case ICmpInst::ICMP_SLE:
1935 // X <=s -1 -> X
1936 if (match(RHS, m_One()))
1937 return LHS;
1938 break;
1939 }
1940 }
1941
Duncan Sandsd3951082011-01-25 09:38:29 +00001942 // If we are comparing with zero then try hard since this is a common case.
1943 if (match(RHS, m_Zero())) {
1944 bool LHSKnownNonNegative, LHSKnownNegative;
1945 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00001946 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00001947 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001948 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001949 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001950 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001951 case ICmpInst::ICMP_EQ:
1952 case ICmpInst::ICMP_ULE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001953 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001954 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001955 break;
1956 case ICmpInst::ICMP_NE:
1957 case ICmpInst::ICMP_UGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001958 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001959 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001960 break;
1961 case ICmpInst::ICMP_SLT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001962 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001963 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001964 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001965 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001966 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001967 break;
1968 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001969 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001970 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001971 return getTrue(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001972 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001973 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001974 break;
1975 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001976 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001977 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001978 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001979 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001980 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001981 break;
1982 case ICmpInst::ICMP_SGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001983 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001984 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001985 return getFalse(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001986 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001987 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001988 break;
1989 }
1990 }
1991
1992 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001993 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001994 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1995 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1996 if (RHS_CR.isEmptySet())
1997 return ConstantInt::getFalse(CI->getContext());
1998 if (RHS_CR.isFullSet())
1999 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002000
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002001 // Many binary operators with constant RHS have easy to compute constant
2002 // range. Use them to check whether the comparison is a tautology.
2003 uint32_t Width = CI->getBitWidth();
2004 APInt Lower = APInt(Width, 0);
2005 APInt Upper = APInt(Width, 0);
2006 ConstantInt *CI2;
2007 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2008 // 'urem x, CI2' produces [0, CI2).
2009 Upper = CI2->getValue();
2010 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2011 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2012 Upper = CI2->getValue().abs();
2013 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002014 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2015 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002016 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002017 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2018 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2019 APInt NegOne = APInt::getAllOnesValue(Width);
2020 if (!CI2->isZero())
2021 Upper = NegOne.udiv(CI2->getValue()) + 1;
2022 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2023 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
2024 APInt IntMin = APInt::getSignedMinValue(Width);
2025 APInt IntMax = APInt::getSignedMaxValue(Width);
2026 APInt Val = CI2->getValue().abs();
2027 if (!Val.isMinValue()) {
2028 Lower = IntMin.sdiv(Val);
2029 Upper = IntMax.sdiv(Val) + 1;
2030 }
2031 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2032 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2033 APInt NegOne = APInt::getAllOnesValue(Width);
2034 if (CI2->getValue().ult(Width))
2035 Upper = NegOne.lshr(CI2->getValue()) + 1;
2036 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2037 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2038 APInt IntMin = APInt::getSignedMinValue(Width);
2039 APInt IntMax = APInt::getSignedMaxValue(Width);
2040 if (CI2->getValue().ult(Width)) {
2041 Lower = IntMin.ashr(CI2->getValue());
2042 Upper = IntMax.ashr(CI2->getValue()) + 1;
2043 }
2044 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2045 // 'or x, CI2' produces [CI2, UINT_MAX].
2046 Lower = CI2->getValue();
2047 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2048 // 'and x, CI2' produces [0, CI2].
2049 Upper = CI2->getValue() + 1;
2050 }
2051 if (Lower != Upper) {
2052 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2053 if (RHS_CR.contains(LHS_CR))
2054 return ConstantInt::getTrue(RHS->getContext());
2055 if (RHS_CR.inverse().contains(LHS_CR))
2056 return ConstantInt::getFalse(RHS->getContext());
2057 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002058 }
2059
Duncan Sands8fb2c382011-01-20 13:21:55 +00002060 // Compare of cast, for example (zext X) != 0 -> X != 0
2061 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2062 Instruction *LI = cast<CastInst>(LHS);
2063 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002064 Type *SrcTy = SrcOp->getType();
2065 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002066
2067 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2068 // if the integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002069 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2070 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002071 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2072 // Transfer the cast to the constant.
2073 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2074 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002075 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002076 return V;
2077 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2078 if (RI->getOperand(0)->getType() == SrcTy)
2079 // Compare without the cast.
2080 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002081 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002082 return V;
2083 }
2084 }
2085
2086 if (isa<ZExtInst>(LHS)) {
2087 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2088 // same type.
2089 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2090 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2091 // Compare X and Y. Note that signed predicates become unsigned.
2092 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002093 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002094 MaxRecurse-1))
2095 return V;
2096 }
2097 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2098 // too. If not, then try to deduce the result of the comparison.
2099 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2100 // Compute the constant that would happen if we truncated to SrcTy then
2101 // reextended to DstTy.
2102 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2103 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2104
2105 // If the re-extended constant didn't change then this is effectively
2106 // also a case of comparing two zero-extended values.
2107 if (RExt == CI && MaxRecurse)
2108 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002109 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002110 return V;
2111
2112 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2113 // there. Use this to work out the result of the comparison.
2114 if (RExt != CI) {
2115 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002116 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002117 // LHS <u RHS.
2118 case ICmpInst::ICMP_EQ:
2119 case ICmpInst::ICMP_UGT:
2120 case ICmpInst::ICMP_UGE:
2121 return ConstantInt::getFalse(CI->getContext());
2122
2123 case ICmpInst::ICMP_NE:
2124 case ICmpInst::ICMP_ULT:
2125 case ICmpInst::ICMP_ULE:
2126 return ConstantInt::getTrue(CI->getContext());
2127
2128 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2129 // is non-negative then LHS <s RHS.
2130 case ICmpInst::ICMP_SGT:
2131 case ICmpInst::ICMP_SGE:
2132 return CI->getValue().isNegative() ?
2133 ConstantInt::getTrue(CI->getContext()) :
2134 ConstantInt::getFalse(CI->getContext());
2135
2136 case ICmpInst::ICMP_SLT:
2137 case ICmpInst::ICMP_SLE:
2138 return CI->getValue().isNegative() ?
2139 ConstantInt::getFalse(CI->getContext()) :
2140 ConstantInt::getTrue(CI->getContext());
2141 }
2142 }
2143 }
2144 }
2145
2146 if (isa<SExtInst>(LHS)) {
2147 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2148 // same type.
2149 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2150 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2151 // Compare X and Y. Note that the predicate does not change.
2152 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002153 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002154 return V;
2155 }
2156 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2157 // too. If not, then try to deduce the result of the comparison.
2158 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2159 // Compute the constant that would happen if we truncated to SrcTy then
2160 // reextended to DstTy.
2161 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2162 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2163
2164 // If the re-extended constant didn't change then this is effectively
2165 // also a case of comparing two sign-extended values.
2166 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002167 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002168 return V;
2169
2170 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2171 // bits there. Use this to work out the result of the comparison.
2172 if (RExt != CI) {
2173 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002174 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002175 case ICmpInst::ICMP_EQ:
2176 return ConstantInt::getFalse(CI->getContext());
2177 case ICmpInst::ICMP_NE:
2178 return ConstantInt::getTrue(CI->getContext());
2179
2180 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2181 // LHS >s RHS.
2182 case ICmpInst::ICMP_SGT:
2183 case ICmpInst::ICMP_SGE:
2184 return CI->getValue().isNegative() ?
2185 ConstantInt::getTrue(CI->getContext()) :
2186 ConstantInt::getFalse(CI->getContext());
2187 case ICmpInst::ICMP_SLT:
2188 case ICmpInst::ICMP_SLE:
2189 return CI->getValue().isNegative() ?
2190 ConstantInt::getFalse(CI->getContext()) :
2191 ConstantInt::getTrue(CI->getContext());
2192
2193 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2194 // LHS >u RHS.
2195 case ICmpInst::ICMP_UGT:
2196 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002197 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002198 if (MaxRecurse)
2199 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2200 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002201 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002202 return V;
2203 break;
2204 case ICmpInst::ICMP_ULT:
2205 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002206 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002207 if (MaxRecurse)
2208 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2209 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002210 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002211 return V;
2212 break;
2213 }
2214 }
2215 }
2216 }
2217 }
2218
Duncan Sandsd114ab32011-02-13 17:15:40 +00002219 // Special logic for binary operators.
2220 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2221 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2222 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002223 // Analyze the case when either LHS or RHS is an add instruction.
2224 Value *A = 0, *B = 0, *C = 0, *D = 0;
2225 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2226 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2227 if (LBO && LBO->getOpcode() == Instruction::Add) {
2228 A = LBO->getOperand(0); B = LBO->getOperand(1);
2229 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2230 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2231 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2232 }
2233 if (RBO && RBO->getOpcode() == Instruction::Add) {
2234 C = RBO->getOperand(0); D = RBO->getOperand(1);
2235 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2236 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2237 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2238 }
2239
2240 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2241 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2242 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2243 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002244 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002245 return V;
2246
2247 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2248 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2249 if (Value *V = SimplifyICmpInst(Pred,
2250 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002251 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002252 return V;
2253
2254 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2255 if (A && C && (A == C || A == D || B == C || B == D) &&
2256 NoLHSWrapProblem && NoRHSWrapProblem) {
2257 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002258 Value *Y, *Z;
2259 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002260 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002261 Y = B;
2262 Z = D;
2263 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002264 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002265 Y = B;
2266 Z = C;
2267 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002268 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002269 Y = A;
2270 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002271 } else {
2272 assert(B == D);
2273 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002274 Y = A;
2275 Z = C;
2276 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002277 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002278 return V;
2279 }
2280 }
2281
Nick Lewycky35aeea92013-07-12 23:42:57 +00002282 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002283 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002284 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002285 switch (Pred) {
2286 default:
2287 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002288 case ICmpInst::ICMP_SGT:
2289 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002290 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002291 if (!KnownNonNegative)
2292 break;
2293 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002294 case ICmpInst::ICMP_EQ:
2295 case ICmpInst::ICMP_UGT:
2296 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002297 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002298 case ICmpInst::ICMP_SLT:
2299 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002300 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002301 if (!KnownNonNegative)
2302 break;
2303 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002304 case ICmpInst::ICMP_NE:
2305 case ICmpInst::ICMP_ULT:
2306 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002307 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002308 }
2309 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002310
2311 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002312 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2313 bool KnownNonNegative, KnownNegative;
2314 switch (Pred) {
2315 default:
2316 break;
2317 case ICmpInst::ICMP_SGT:
2318 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002319 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002320 if (!KnownNonNegative)
2321 break;
2322 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002323 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002324 case ICmpInst::ICMP_UGT:
2325 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002326 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002327 case ICmpInst::ICMP_SLT:
2328 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002329 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002330 if (!KnownNonNegative)
2331 break;
2332 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002333 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002334 case ICmpInst::ICMP_ULT:
2335 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002336 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002337 }
2338 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002339
Duncan Sands92af0a82011-10-28 18:17:44 +00002340 // x udiv y <=u x.
2341 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2342 // icmp pred (X /u Y), X
2343 if (Pred == ICmpInst::ICMP_UGT)
2344 return getFalse(ITy);
2345 if (Pred == ICmpInst::ICMP_ULE)
2346 return getTrue(ITy);
2347 }
2348
Nick Lewycky9719a712011-03-05 05:19:11 +00002349 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2350 LBO->getOperand(1) == RBO->getOperand(1)) {
2351 switch (LBO->getOpcode()) {
2352 default: break;
2353 case Instruction::UDiv:
2354 case Instruction::LShr:
2355 if (ICmpInst::isSigned(Pred))
2356 break;
2357 // fall-through
2358 case Instruction::SDiv:
2359 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002360 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002361 break;
2362 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002363 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002364 return V;
2365 break;
2366 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002367 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002368 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2369 if (!NUW && !NSW)
2370 break;
2371 if (!NSW && ICmpInst::isSigned(Pred))
2372 break;
2373 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002374 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002375 return V;
2376 break;
2377 }
2378 }
2379 }
2380
Duncan Sands0a9c1242011-05-03 19:53:10 +00002381 // Simplify comparisons involving max/min.
2382 Value *A, *B;
2383 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002384 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002385
Duncan Sandsa2287852011-05-04 16:05:05 +00002386 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002387 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2388 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002389 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002390 // We analyze this as smax(A, B) pred A.
2391 P = Pred;
2392 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2393 (A == LHS || B == LHS)) {
2394 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002395 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002396 // We analyze this as smax(A, B) swapped-pred A.
2397 P = CmpInst::getSwappedPredicate(Pred);
2398 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2399 (A == RHS || B == RHS)) {
2400 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002401 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002402 // We analyze this as smax(-A, -B) swapped-pred -A.
2403 // Note that we do not need to actually form -A or -B thanks to EqP.
2404 P = CmpInst::getSwappedPredicate(Pred);
2405 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2406 (A == LHS || B == LHS)) {
2407 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002408 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002409 // We analyze this as smax(-A, -B) pred -A.
2410 // Note that we do not need to actually form -A or -B thanks to EqP.
2411 P = Pred;
2412 }
2413 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2414 // Cases correspond to "max(A, B) p A".
2415 switch (P) {
2416 default:
2417 break;
2418 case CmpInst::ICMP_EQ:
2419 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002420 // Equivalent to "A EqP B". This may be the same as the condition tested
2421 // in the max/min; if so, we can just return that.
2422 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2423 return V;
2424 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2425 return V;
2426 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002427 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002428 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002429 return V;
2430 break;
2431 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002432 case CmpInst::ICMP_SGT: {
2433 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2434 // Equivalent to "A InvEqP B". This may be the same as the condition
2435 // tested in the max/min; if so, we can just return that.
2436 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2437 return V;
2438 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2439 return V;
2440 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002441 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002442 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002443 return V;
2444 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002445 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002446 case CmpInst::ICMP_SGE:
2447 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002448 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002449 case CmpInst::ICMP_SLT:
2450 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002451 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002452 }
2453 }
2454
Duncan Sandsa2287852011-05-04 16:05:05 +00002455 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002456 P = CmpInst::BAD_ICMP_PREDICATE;
2457 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2458 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002459 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002460 // We analyze this as umax(A, B) pred A.
2461 P = Pred;
2462 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2463 (A == LHS || B == LHS)) {
2464 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002465 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002466 // We analyze this as umax(A, B) swapped-pred A.
2467 P = CmpInst::getSwappedPredicate(Pred);
2468 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2469 (A == RHS || B == RHS)) {
2470 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002471 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002472 // We analyze this as umax(-A, -B) swapped-pred -A.
2473 // Note that we do not need to actually form -A or -B thanks to EqP.
2474 P = CmpInst::getSwappedPredicate(Pred);
2475 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2476 (A == LHS || B == LHS)) {
2477 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002478 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002479 // We analyze this as umax(-A, -B) pred -A.
2480 // Note that we do not need to actually form -A or -B thanks to EqP.
2481 P = Pred;
2482 }
2483 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2484 // Cases correspond to "max(A, B) p A".
2485 switch (P) {
2486 default:
2487 break;
2488 case CmpInst::ICMP_EQ:
2489 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002490 // Equivalent to "A EqP B". This may be the same as the condition tested
2491 // in the max/min; if so, we can just return that.
2492 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2493 return V;
2494 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2495 return V;
2496 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002497 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002498 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002499 return V;
2500 break;
2501 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002502 case CmpInst::ICMP_UGT: {
2503 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2504 // Equivalent to "A InvEqP B". This may be the same as the condition
2505 // tested in the max/min; if so, we can just return that.
2506 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2507 return V;
2508 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2509 return V;
2510 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002511 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002512 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002513 return V;
2514 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002515 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002516 case CmpInst::ICMP_UGE:
2517 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002518 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002519 case CmpInst::ICMP_ULT:
2520 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002521 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002522 }
2523 }
2524
Duncan Sandsa2287852011-05-04 16:05:05 +00002525 // Variants on "max(x,y) >= min(x,z)".
2526 Value *C, *D;
2527 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2528 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2529 (A == C || A == D || B == C || B == D)) {
2530 // max(x, ?) pred min(x, ?).
2531 if (Pred == CmpInst::ICMP_SGE)
2532 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002533 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002534 if (Pred == CmpInst::ICMP_SLT)
2535 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002536 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002537 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2538 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2539 (A == C || A == D || B == C || B == D)) {
2540 // min(x, ?) pred max(x, ?).
2541 if (Pred == CmpInst::ICMP_SLE)
2542 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002543 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002544 if (Pred == CmpInst::ICMP_SGT)
2545 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002546 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002547 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2548 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2549 (A == C || A == D || B == C || B == D)) {
2550 // max(x, ?) pred min(x, ?).
2551 if (Pred == CmpInst::ICMP_UGE)
2552 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002553 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002554 if (Pred == CmpInst::ICMP_ULT)
2555 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002556 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002557 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2558 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2559 (A == C || A == D || B == C || B == D)) {
2560 // min(x, ?) pred max(x, ?).
2561 if (Pred == CmpInst::ICMP_ULE)
2562 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002563 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002564 if (Pred == CmpInst::ICMP_UGT)
2565 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002566 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002567 }
2568
Chandler Carruth8059c842012-03-25 21:28:14 +00002569 // Simplify comparisons of related pointers using a powerful, recursive
2570 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00002571 if (LHS->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002572 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00002573 return C;
2574
Nick Lewycky3db143e2012-02-26 02:09:49 +00002575 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2576 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2577 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2578 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2579 (ICmpInst::isEquality(Pred) ||
2580 (GLHS->isInBounds() && GRHS->isInBounds() &&
2581 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2582 // The bases are equal and the indices are constant. Build a constant
2583 // expression GEP with the same indices and a null base pointer to see
2584 // what constant folding can make out of it.
2585 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2586 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2587 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2588
2589 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2590 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2591 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2592 }
2593 }
2594 }
2595
Duncan Sandsf532d312010-11-07 16:12:23 +00002596 // If the comparison is with the result of a select instruction, check whether
2597 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002598 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002599 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002600 return V;
2601
2602 // If the comparison is with the result of a phi instruction, check whether
2603 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002604 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002605 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002606 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00002607
Chris Lattner084a1b52009-11-09 22:57:59 +00002608 return 0;
2609}
2610
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002611Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002612 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002613 const TargetLibraryInfo *TLI,
2614 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002615 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002616 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002617}
2618
Chris Lattnerc1f19072009-11-09 23:28:39 +00002619/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2620/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002621static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002622 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002623 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2624 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2625
Chris Lattnera71e9d62009-11-10 00:55:12 +00002626 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002627 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002628 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00002629
Chris Lattnera71e9d62009-11-10 00:55:12 +00002630 // If we have a constant, make sure it is on the RHS.
2631 std::swap(LHS, RHS);
2632 Pred = CmpInst::getSwappedPredicate(Pred);
2633 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002634
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002635 // Fold trivial predicates.
2636 if (Pred == FCmpInst::FCMP_FALSE)
2637 return ConstantInt::get(GetCompareTy(LHS), 0);
2638 if (Pred == FCmpInst::FCMP_TRUE)
2639 return ConstantInt::get(GetCompareTy(LHS), 1);
2640
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002641 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2642 return UndefValue::get(GetCompareTy(LHS));
2643
2644 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00002645 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002646 if (CmpInst::isTrueWhenEqual(Pred))
2647 return ConstantInt::get(GetCompareTy(LHS), 1);
2648 if (CmpInst::isFalseWhenEqual(Pred))
2649 return ConstantInt::get(GetCompareTy(LHS), 0);
2650 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002651
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002652 // Handle fcmp with constant RHS
2653 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2654 // If the constant is a nan, see if we can fold the comparison based on it.
2655 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2656 if (CFP->getValueAPF().isNaN()) {
2657 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2658 return ConstantInt::getFalse(CFP->getContext());
2659 assert(FCmpInst::isUnordered(Pred) &&
2660 "Comparison must be either ordered or unordered!");
2661 // True if unordered.
2662 return ConstantInt::getTrue(CFP->getContext());
2663 }
Dan Gohman754e4a92010-02-22 04:06:03 +00002664 // Check whether the constant is an infinity.
2665 if (CFP->getValueAPF().isInfinity()) {
2666 if (CFP->getValueAPF().isNegative()) {
2667 switch (Pred) {
2668 case FCmpInst::FCMP_OLT:
2669 // No value is ordered and less than negative infinity.
2670 return ConstantInt::getFalse(CFP->getContext());
2671 case FCmpInst::FCMP_UGE:
2672 // All values are unordered with or at least negative infinity.
2673 return ConstantInt::getTrue(CFP->getContext());
2674 default:
2675 break;
2676 }
2677 } else {
2678 switch (Pred) {
2679 case FCmpInst::FCMP_OGT:
2680 // No value is ordered and greater than infinity.
2681 return ConstantInt::getFalse(CFP->getContext());
2682 case FCmpInst::FCMP_ULE:
2683 // All values are unordered with and at most infinity.
2684 return ConstantInt::getTrue(CFP->getContext());
2685 default:
2686 break;
2687 }
2688 }
2689 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002690 }
2691 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002692
Duncan Sandsa620bd12010-11-07 16:46:25 +00002693 // If the comparison is with the result of a select instruction, check whether
2694 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002695 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002696 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002697 return V;
2698
2699 // If the comparison is with the result of a phi instruction, check whether
2700 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002701 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002702 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002703 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00002704
Chris Lattnerc1f19072009-11-09 23:28:39 +00002705 return 0;
2706}
2707
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002708Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002709 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002710 const TargetLibraryInfo *TLI,
2711 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002712 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002713 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002714}
2715
Chris Lattnerc707fa92010-04-20 05:32:14 +00002716/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2717/// the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002718static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2719 Value *FalseVal, const Query &Q,
2720 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00002721 // select true, X, Y -> X
2722 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002723 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2724 if (CB->isAllOnesValue())
2725 return TrueVal;
2726 if (CB->isNullValue())
2727 return FalseVal;
2728 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002729
Chris Lattnerc707fa92010-04-20 05:32:14 +00002730 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00002731 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00002732 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002733
Chris Lattnerc707fa92010-04-20 05:32:14 +00002734 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2735 if (isa<Constant>(TrueVal))
2736 return TrueVal;
2737 return FalseVal;
2738 }
Dan Gohman54664ed2011-07-01 01:03:43 +00002739 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2740 return FalseVal;
2741 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2742 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002743
Chris Lattnerc707fa92010-04-20 05:32:14 +00002744 return 0;
2745}
2746
Duncan Sandsb8cee002012-03-13 11:42:19 +00002747Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002748 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002749 const TargetLibraryInfo *TLI,
2750 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002751 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002752 RecursionLimit);
2753}
2754
Chris Lattner8574aba2009-11-27 00:29:05 +00002755/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2756/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002757static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00002758 // The type of the GEP pointer operand.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002759 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002760
Chris Lattner8574aba2009-11-27 00:29:05 +00002761 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00002762 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00002763 return Ops[0];
2764
Duncan Sands8a0f4862010-11-22 13:42:49 +00002765 if (isa<UndefValue>(Ops[0])) {
2766 // Compute the (pointer) type returned by the GEP instruction.
Jay Foadd1b78492011-07-25 09:48:08 +00002767 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattner229907c2011-07-18 04:54:35 +00002768 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002769 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2770 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002771 return UndefValue::get(GEPTy);
2772 }
Chris Lattner8574aba2009-11-27 00:29:05 +00002773
Jay Foadb992a632011-07-19 15:07:52 +00002774 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002775 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002776 if (match(Ops[1], m_Zero()))
2777 return Ops[0];
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002778 // getelementptr P, N -> P if P points to a type of zero size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002779 if (Q.DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002780 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002781 if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002782 return Ops[0];
2783 }
2784 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002785
Chris Lattner8574aba2009-11-27 00:29:05 +00002786 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00002787 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00002788 if (!isa<Constant>(Ops[i]))
2789 return 0;
Duncan Sands7e800d62010-11-14 11:23:23 +00002790
Jay Foaded8db7d2011-07-21 14:31:17 +00002791 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00002792}
2793
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002794Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002795 const TargetLibraryInfo *TLI,
2796 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002797 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002798}
2799
Duncan Sandsfd26a952011-09-05 06:52:48 +00002800/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2801/// can fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002802static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2803 ArrayRef<unsigned> Idxs, const Query &Q,
2804 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002805 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2806 if (Constant *CVal = dyn_cast<Constant>(Val))
2807 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2808
2809 // insertvalue x, undef, n -> x
2810 if (match(Val, m_Undef()))
2811 return Agg;
2812
2813 // insertvalue x, (extractvalue y, n), n
2814 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00002815 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2816 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002817 // insertvalue undef, (extractvalue y, n), n -> y
2818 if (match(Agg, m_Undef()))
2819 return EV->getAggregateOperand();
2820
2821 // insertvalue y, (extractvalue y, n), n -> y
2822 if (Agg == EV->getAggregateOperand())
2823 return Agg;
2824 }
2825
2826 return 0;
2827}
2828
Duncan Sandsb8cee002012-03-13 11:42:19 +00002829Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2830 ArrayRef<unsigned> Idxs,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002831 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002832 const TargetLibraryInfo *TLI,
2833 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002834 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002835 RecursionLimit);
2836}
2837
Duncan Sands7412f6e2010-11-17 04:30:22 +00002838/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002839static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00002840 // If all of the PHI's incoming values are the same then replace the PHI node
2841 // with the common value.
2842 Value *CommonValue = 0;
2843 bool HasUndefInput = false;
2844 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2845 Value *Incoming = PN->getIncomingValue(i);
2846 // If the incoming value is the phi node itself, it can safely be skipped.
2847 if (Incoming == PN) continue;
2848 if (isa<UndefValue>(Incoming)) {
2849 // Remember that we saw an undef value, but otherwise ignore them.
2850 HasUndefInput = true;
2851 continue;
2852 }
2853 if (CommonValue && Incoming != CommonValue)
2854 return 0; // Not the same, bail out.
2855 CommonValue = Incoming;
2856 }
2857
2858 // If CommonValue is null then all of the incoming values were either undef or
2859 // equal to the phi node itself.
2860 if (!CommonValue)
2861 return UndefValue::get(PN->getType());
2862
2863 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2864 // instruction, we cannot return X as the result of the PHI node unless it
2865 // dominates the PHI block.
2866 if (HasUndefInput)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002867 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sands7412f6e2010-11-17 04:30:22 +00002868
2869 return CommonValue;
2870}
2871
Duncan Sands395ac42d2012-03-13 14:07:05 +00002872static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2873 if (Constant *C = dyn_cast<Constant>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002874 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002875
2876 return 0;
2877}
2878
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002879Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00002880 const TargetLibraryInfo *TLI,
2881 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002882 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002883}
2884
Chris Lattnera71e9d62009-11-10 00:55:12 +00002885//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00002886
Chris Lattnera71e9d62009-11-10 00:55:12 +00002887/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2888/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002889static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002890 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00002891 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00002892 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002893 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002894 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002895 case Instruction::FAdd:
2896 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2897
Chris Lattner9e4aa022011-02-09 17:15:04 +00002898 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002899 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002900 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002901 case Instruction::FSub:
2902 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2903
Duncan Sandsb8cee002012-03-13 11:42:19 +00002904 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002905 case Instruction::FMul:
2906 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002907 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2908 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2909 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2910 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2911 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2912 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002913 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002914 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002915 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002916 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002917 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002918 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002919 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2920 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2921 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2922 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002923 default:
2924 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2925 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2926 Constant *COps[] = {CLHS, CRHS};
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002927 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002928 Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002929 }
Duncan Sandsb0579e92010-11-10 13:00:08 +00002930
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002931 // If the operation is associative, try some generic simplifications.
2932 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002933 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002934 return V;
2935
Duncan Sandsb8cee002012-03-13 11:42:19 +00002936 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00002937 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002938 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002939 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002940 return V;
2941
2942 // If the operation is with the result of a phi instruction, check whether
2943 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002944 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002945 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00002946 return V;
2947
Chris Lattnera71e9d62009-11-10 00:55:12 +00002948 return 0;
2949 }
2950}
Chris Lattnerc1f19072009-11-09 23:28:39 +00002951
Duncan Sands7e800d62010-11-14 11:23:23 +00002952Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002953 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002954 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002955 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00002956}
2957
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002958/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2959/// fold the result.
2960static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002961 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002962 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002963 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2964 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002965}
2966
2967Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002968 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002969 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002970 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002971 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002972}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00002973
Michael Ilseman54857292013-02-07 19:26:05 +00002974static bool IsIdempotent(Intrinsic::ID ID) {
2975 switch (ID) {
2976 default: return false;
2977
2978 // Unary idempotent: f(f(x)) = f(x)
2979 case Intrinsic::fabs:
2980 case Intrinsic::floor:
2981 case Intrinsic::ceil:
2982 case Intrinsic::trunc:
2983 case Intrinsic::rint:
2984 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00002985 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00002986 return true;
2987 }
2988}
2989
2990template <typename IterTy>
2991static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
2992 const Query &Q, unsigned MaxRecurse) {
2993 // Perform idempotent optimizations
2994 if (!IsIdempotent(IID))
2995 return 0;
2996
2997 // Unary Ops
2998 if (std::distance(ArgBegin, ArgEnd) == 1)
2999 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3000 if (II->getIntrinsicID() == IID)
3001 return II;
3002
3003 return 0;
3004}
3005
Chandler Carruth9dc35582012-12-28 11:30:55 +00003006template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003007static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003008 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003009 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003010 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3011 Ty = PTy->getElementType();
3012 FunctionType *FTy = cast<FunctionType>(Ty);
3013
Dan Gohman85977e62011-11-04 18:32:42 +00003014 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003015 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003016 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003017
Chandler Carruthf6182152012-12-28 14:23:29 +00003018 Function *F = dyn_cast<Function>(V);
3019 if (!F)
3020 return 0;
3021
Michael Ilseman54857292013-02-07 19:26:05 +00003022 if (unsigned IID = F->getIntrinsicID())
3023 if (Value *Ret =
3024 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3025 return Ret;
3026
Chandler Carruthf6182152012-12-28 14:23:29 +00003027 if (!canConstantFoldCallTo(F))
3028 return 0;
3029
3030 SmallVector<Constant *, 4> ConstantArgs;
3031 ConstantArgs.reserve(ArgEnd - ArgBegin);
3032 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3033 Constant *C = dyn_cast<Constant>(*I);
3034 if (!C)
3035 return 0;
3036 ConstantArgs.push_back(C);
3037 }
3038
3039 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00003040}
3041
Chandler Carruthf6182152012-12-28 14:23:29 +00003042Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003043 User::op_iterator ArgEnd, const DataLayout *DL,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003044 const TargetLibraryInfo *TLI,
3045 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003046 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003047 RecursionLimit);
3048}
3049
Chandler Carruthf6182152012-12-28 14:23:29 +00003050Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003051 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003052 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003053 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003054 RecursionLimit);
3055}
3056
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003057/// SimplifyInstruction - See if we can compute a simplified version of this
3058/// instruction. If not, this returns null.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003059Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003060 const TargetLibraryInfo *TLI,
Duncan Sandsb99f39b2010-11-14 18:36:10 +00003061 const DominatorTree *DT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00003062 Value *Result;
3063
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003064 switch (I->getOpcode()) {
3065 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003066 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003067 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003068 case Instruction::FAdd:
3069 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003070 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003071 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00003072 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003073 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3074 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3075 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003076 DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003077 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003078 case Instruction::FSub:
3079 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003080 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003081 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00003082 case Instruction::Sub:
3083 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3084 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3085 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003086 DL, TLI, DT);
Duncan Sands0a2c41682010-12-15 14:07:39 +00003087 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003088 case Instruction::FMul:
3089 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003090 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003091 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003092 case Instruction::Mul:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003093 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003094 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00003095 case Instruction::SDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003096 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003097 break;
3098 case Instruction::UDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003099 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003100 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00003101 case Instruction::FDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003102 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Frits van Bommelc2549662011-01-29 15:26:31 +00003103 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00003104 case Instruction::SRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003105 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003106 break;
3107 case Instruction::URem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003108 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003109 break;
3110 case Instruction::FRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003111 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003112 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00003113 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003114 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3115 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3116 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003117 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003118 break;
3119 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003120 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3121 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003122 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003123 break;
3124 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003125 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3126 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003127 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003128 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003129 case Instruction::And:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003130 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003131 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003132 case Instruction::Or:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003133 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003134 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00003135 case Instruction::Xor:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003136 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsc89ac072010-11-17 18:52:15 +00003137 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003138 case Instruction::ICmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003139 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003140 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003141 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003142 case Instruction::FCmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003143 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003144 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003145 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003146 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003147 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003148 I->getOperand(2), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003149 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003150 case Instruction::GetElementPtr: {
3151 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003152 Result = SimplifyGEPInst(Ops, DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003153 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003154 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00003155 case Instruction::InsertValue: {
3156 InsertValueInst *IV = cast<InsertValueInst>(I);
3157 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3158 IV->getInsertedValueOperand(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003159 IV->getIndices(), DL, TLI, DT);
Duncan Sandsfd26a952011-09-05 06:52:48 +00003160 break;
3161 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00003162 case Instruction::PHI:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003163 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT));
Duncan Sands64e41cf2010-11-17 08:35:29 +00003164 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003165 case Instruction::Call: {
3166 CallSite CS(cast<CallInst>(I));
3167 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003168 DL, TLI, DT);
Dan Gohman85977e62011-11-04 18:32:42 +00003169 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003170 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00003171 case Instruction::Trunc:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003172 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003173 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003174 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00003175
3176 /// If called on unreachable code, the above logic may report that the
3177 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00003178 /// detecting that case here, returning a safe value instead.
3179 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003180}
3181
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003182/// \brief Implementation of recursive simplification through an instructions
3183/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00003184///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003185/// This is the common implementation of the recursive simplification routines.
3186/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3187/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3188/// instructions to process and attempt to simplify it using
3189/// InstructionSimplify.
3190///
3191/// This routine returns 'true' only when *it* simplifies something. The passed
3192/// in simplified value does not count toward this.
3193static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003194 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003195 const TargetLibraryInfo *TLI,
3196 const DominatorTree *DT) {
3197 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003198 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands7e800d62010-11-14 11:23:23 +00003199
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003200 // If we have an explicit value to collapse to, do that round of the
3201 // simplification loop by hand initially.
3202 if (SimpleV) {
3203 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3204 ++UI)
Chandler Carruthe41fc732012-03-24 22:34:23 +00003205 if (*UI != I)
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003206 Worklist.insert(cast<Instruction>(*UI));
Duncan Sands7e800d62010-11-14 11:23:23 +00003207
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003208 // Replace the instruction with its simplified value.
3209 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00003210
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003211 // Gracefully handle edge cases where the instruction is not wired into any
3212 // parent block.
3213 if (I->getParent())
3214 I->eraseFromParent();
3215 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003216 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00003217 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003218
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003219 // Note that we must test the size on each iteration, the worklist can grow.
3220 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3221 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00003222
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003223 // See if this instruction simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003224 SimpleV = SimplifyInstruction(I, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003225 if (!SimpleV)
3226 continue;
3227
3228 Simplified = true;
3229
3230 // Stash away all the uses of the old instruction so we can check them for
3231 // recursive simplifications after a RAUW. This is cheaper than checking all
3232 // uses of To on the recursive step in most cases.
3233 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3234 ++UI)
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003235 Worklist.insert(cast<Instruction>(*UI));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003236
3237 // Replace the instruction with its simplified value.
3238 I->replaceAllUsesWith(SimpleV);
3239
3240 // Gracefully handle edge cases where the instruction is not wired into any
3241 // parent block.
3242 if (I->getParent())
3243 I->eraseFromParent();
3244 }
3245 return Simplified;
3246}
3247
3248bool llvm::recursivelySimplifyInstruction(Instruction *I,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003249 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003250 const TargetLibraryInfo *TLI,
3251 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003252 return replaceAndRecursivelySimplifyImpl(I, 0, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003253}
3254
3255bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003256 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003257 const TargetLibraryInfo *TLI,
3258 const DominatorTree *DT) {
3259 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3260 assert(SimpleV && "Must provide a simplified value.");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003261 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT);
Chris Lattner852d6d62009-11-10 22:26:15 +00003262}