blob: 6987faf6bca13dbd523cba087403796c54c35877 [file] [log] [blame]
Chris Lattner084a1b52009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sandsa0219882010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsed6d6c32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner084a1b52009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/Statistic.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000023#include "llvm/Analysis/AliasAnalysis.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000024#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Sanjay Patel54656ca2017-02-06 18:26:06 +000027#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000029#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000030#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/GlobalAlias.h"
35#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000038#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000039using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000040using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "instsimplify"
43
Chris Lattner9e4aa022011-02-09 17:15:04 +000044enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000045
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000047STATISTIC(NumReassoc, "Number of reassociations");
48
Benjamin Kramercfd8d902014-09-12 08:56:53 +000049namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000050struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000051 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000052 const TargetLibraryInfo *TLI;
53 const DominatorTree *DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000054 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000055 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000056
Mehdi Aminia28d91d2015-03-10 02:37:25 +000057 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 const DominatorTree *dt, AssumptionCache *ac = nullptr,
59 const Instruction *cxti = nullptr)
60 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000061};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000062} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000063
64static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
65static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000066 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000067static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
68 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000069static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000070 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000071static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
72 const Query &Q, unsigned MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +000073static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
74static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000075static Value *SimplifyCastInst(unsigned, Value *, Type *,
76 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000077
Sanjay Patel472cc782016-01-11 22:14:42 +000078/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000079/// a vector with every element false, as appropriate for the type.
80static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000081 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000082 "Expected i1 type or a vector of i1!");
83 return Constant::getNullValue(Ty);
84}
85
Sanjay Patel472cc782016-01-11 22:14:42 +000086/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000087/// a vector with every element true, as appropriate for the type.
88static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000089 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000090 "Expected i1 type or a vector of i1!");
91 return Constant::getAllOnesValue(Ty);
92}
93
Duncan Sands3d5692a2011-10-30 19:56:36 +000094/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
95static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
96 Value *RHS) {
97 CmpInst *Cmp = dyn_cast<CmpInst>(V);
98 if (!Cmp)
99 return false;
100 CmpInst::Predicate CPred = Cmp->getPredicate();
101 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
102 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
103 return true;
104 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
105 CRHS == LHS;
106}
107
Sanjay Patel472cc782016-01-11 22:14:42 +0000108/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000109static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
110 Instruction *I = dyn_cast<Instruction>(V);
111 if (!I)
112 // Arguments and constants dominate all instructions.
113 return true;
114
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000115 // If we are processing instructions (and/or basic blocks) that have not been
116 // fully added to a function, the parent nodes may still be null. Simply
117 // return the conservative answer in these cases.
118 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
119 return false;
120
Duncan Sands5ffc2982010-11-16 12:16:38 +0000121 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000122 if (DT) {
123 if (!DT->isReachableFromEntry(P->getParent()))
124 return true;
125 if (!DT->isReachableFromEntry(I->getParent()))
126 return false;
127 return DT->dominates(I, P);
128 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000129
David Majnemer8a1c45d2015-12-12 05:38:55 +0000130 // Otherwise, if the instruction is in the entry block and is not an invoke,
131 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000132 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000133 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000134 return true;
135
136 return false;
137}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000138
Sanjay Patel472cc782016-01-11 22:14:42 +0000139/// Simplify "A op (B op' C)" by distributing op over op', turning it into
140/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000141/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
142/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
143/// Returns the simplified value, or null if no simplification was performed.
144static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000145 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000146 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000147 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148 // Recursion is always used, so bail out at once if we already hit the limit.
149 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000150 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000151
152 // Check whether the expression has the form "(A op' B) op C".
153 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
154 if (Op0->getOpcode() == OpcodeToExpand) {
155 // It does! Try turning it into "(A op C) op' (B op C)".
156 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
157 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000158 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
159 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000160 // They do! Return "L op' R" if it simplifies or is already available.
161 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000162 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
163 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000164 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000165 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000166 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000168 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000169 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000170 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000171 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000172 }
173 }
174
175 // Check whether the expression has the form "A op (B op' C)".
176 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
177 if (Op1->getOpcode() == OpcodeToExpand) {
178 // It does! Try turning it into "(A op B) op' (A op C)".
179 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
180 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000181 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
182 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 // They do! Return "L op' R" if it simplifies or is already available.
184 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000185 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
186 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000187 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000188 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000191 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000192 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000193 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000194 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000195 }
196 }
197
Craig Topper9f008862014-04-15 04:59:12 +0000198 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000199}
200
Sanjay Patel472cc782016-01-11 22:14:42 +0000201/// Generic simplifications for associative binary operations.
202/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000203static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000204 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000205 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000206 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
207
208 // Recursion is always used, so bail out at once if we already hit the limit.
209 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000210 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000211
212 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
213 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
214
215 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
216 if (Op0 && Op0->getOpcode() == Opcode) {
217 Value *A = Op0->getOperand(0);
218 Value *B = Op0->getOperand(1);
219 Value *C = RHS;
220
221 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000222 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // It does! Return "A op V" if it simplifies or is already available.
224 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000225 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000227 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000228 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000229 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000230 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000231 }
232 }
233
234 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
235 if (Op1 && Op1->getOpcode() == Opcode) {
236 Value *A = LHS;
237 Value *B = Op1->getOperand(0);
238 Value *C = Op1->getOperand(1);
239
240 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000241 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000242 // It does! Return "V op C" if it simplifies or is already available.
243 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000244 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000245 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000246 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000247 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000248 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000249 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000250 }
251 }
252
253 // The remaining transforms require commutativity as well as associativity.
254 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000256
257 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
258 if (Op0 && Op0->getOpcode() == Opcode) {
259 Value *A = Op0->getOperand(0);
260 Value *B = Op0->getOperand(1);
261 Value *C = RHS;
262
263 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000264 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000265 // It does! Return "V op B" if it simplifies or is already available.
266 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000267 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000269 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000270 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000271 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000272 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000273 }
274 }
275
276 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
277 if (Op1 && Op1->getOpcode() == Opcode) {
278 Value *A = LHS;
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
281
282 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000283 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000284 // It does! Return "B op V" if it simplifies or is already available.
285 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000286 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000288 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000289 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000290 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000291 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292 }
293 }
294
Craig Topper9f008862014-04-15 04:59:12 +0000295 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000296}
297
Sanjay Patel472cc782016-01-11 22:14:42 +0000298/// In the case of a binary operation with a select instruction as an operand,
299/// try to simplify the binop by seeing whether evaluating it on both branches
300/// of the select results in the same value. Returns the common value if so,
301/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000302static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000303 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000304 // Recursion is always used, so bail out at once if we already hit the limit.
305 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000306 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000307
Duncan Sandsb0579e92010-11-10 13:00:08 +0000308 SelectInst *SI;
309 if (isa<SelectInst>(LHS)) {
310 SI = cast<SelectInst>(LHS);
311 } else {
312 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
313 SI = cast<SelectInst>(RHS);
314 }
315
316 // Evaluate the BinOp on the true and false branches of the select.
317 Value *TV;
318 Value *FV;
319 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000320 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
321 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000322 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000323 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
324 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000325 }
326
Duncan Sandse3c53952011-01-01 16:12:09 +0000327 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000328 // If they both failed to simplify then return null.
329 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000330 return TV;
331
332 // If one branch simplified to undef, return the other one.
333 if (TV && isa<UndefValue>(TV))
334 return FV;
335 if (FV && isa<UndefValue>(FV))
336 return TV;
337
338 // If applying the operation did not change the true and false select values,
339 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000340 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000341 return SI;
342
343 // If one branch simplified and the other did not, and the simplified
344 // value is equal to the unsimplified one, return the simplified value.
345 // For example, select (cond, X, X & Z) & Z -> X & Z.
346 if ((FV && !TV) || (TV && !FV)) {
347 // Check that the simplified value has the form "X op Y" where "op" is the
348 // same as the original operation.
349 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
350 if (Simplified && Simplified->getOpcode() == Opcode) {
351 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
352 // We already know that "op" is the same as for the simplified value. See
353 // if the operands match too. If so, return the simplified value.
354 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
355 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
356 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000357 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
358 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000359 return Simplified;
360 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000361 Simplified->getOperand(1) == UnsimplifiedLHS &&
362 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000363 return Simplified;
364 }
365 }
366
Craig Topper9f008862014-04-15 04:59:12 +0000367 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000368}
369
Sanjay Patel472cc782016-01-11 22:14:42 +0000370/// In the case of a comparison with a select instruction, try to simplify the
371/// comparison by seeing whether both branches of the select result in the same
372/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000373static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000374 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000375 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000376 // Recursion is always used, so bail out at once if we already hit the limit.
377 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000378 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000379
Duncan Sandsb0579e92010-11-10 13:00:08 +0000380 // Make sure the select is on the LHS.
381 if (!isa<SelectInst>(LHS)) {
382 std::swap(LHS, RHS);
383 Pred = CmpInst::getSwappedPredicate(Pred);
384 }
385 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
386 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000387 Value *Cond = SI->getCondition();
388 Value *TV = SI->getTrueValue();
389 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000390
Duncan Sands06504022011-02-03 09:37:39 +0000391 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000392 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000393 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000394 if (TCmp == Cond) {
395 // It not only simplified, it simplified to the select condition. Replace
396 // it with 'true'.
397 TCmp = getTrue(Cond->getType());
398 } else if (!TCmp) {
399 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
400 // condition then we can replace it with 'true'. Otherwise give up.
401 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000402 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000403 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000404 }
405
Duncan Sands3d5692a2011-10-30 19:56:36 +0000406 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000407 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000408 if (FCmp == Cond) {
409 // It not only simplified, it simplified to the select condition. Replace
410 // it with 'false'.
411 FCmp = getFalse(Cond->getType());
412 } else if (!FCmp) {
413 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
414 // condition then we can replace it with 'false'. Otherwise give up.
415 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000416 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000417 FCmp = getFalse(Cond->getType());
418 }
419
420 // If both sides simplified to the same value, then use it as the result of
421 // the original comparison.
422 if (TCmp == FCmp)
423 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000424
425 // The remaining cases only make sense if the select condition has the same
426 // type as the result of the comparison, so bail out if this is not so.
427 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000428 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000429 // If the false value simplified to false, then the result of the compare
430 // is equal to "Cond && TCmp". This also catches the case when the false
431 // value simplified to false and the true value to true, returning "Cond".
432 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000433 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000434 return V;
435 // If the true value simplified to true, then the result of the compare
436 // is equal to "Cond || FCmp".
437 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000438 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000439 return V;
440 // Finally, if the false value simplified to true and the true value to
441 // false, then the result of the compare is equal to "!Cond".
442 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
443 if (Value *V =
444 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000445 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000446 return V;
447
Craig Topper9f008862014-04-15 04:59:12 +0000448 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000449}
450
Sanjay Patel472cc782016-01-11 22:14:42 +0000451/// In the case of a binary operation with an operand that is a PHI instruction,
452/// try to simplify the binop by seeing whether evaluating it on the incoming
453/// phi values yields the same result for every value. If so returns the common
454/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000455static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000456 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000457 // Recursion is always used, so bail out at once if we already hit the limit.
458 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000459 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000460
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000461 PHINode *PI;
462 if (isa<PHINode>(LHS)) {
463 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000464 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000465 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000466 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000467 } else {
468 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
469 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000470 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000471 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000472 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000473 }
474
475 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000476 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000477 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000478 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000479 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000481 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
482 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000483 // If the operation failed to simplify, or simplified to a different value
484 // to previously, then give up.
485 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000486 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000487 CommonValue = V;
488 }
489
490 return CommonValue;
491}
492
Sanjay Patel472cc782016-01-11 22:14:42 +0000493/// In the case of a comparison with a PHI instruction, try to simplify the
494/// comparison by seeing whether comparing with all of the incoming phi values
495/// yields the same result every time. If so returns the common result,
496/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000497static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000498 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000499 // Recursion is always used, so bail out at once if we already hit the limit.
500 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000501 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000502
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000503 // Make sure the phi is on the LHS.
504 if (!isa<PHINode>(LHS)) {
505 std::swap(LHS, RHS);
506 Pred = CmpInst::getSwappedPredicate(Pred);
507 }
508 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
509 PHINode *PI = cast<PHINode>(LHS);
510
Duncan Sands5ffc2982010-11-16 12:16:38 +0000511 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000512 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000513 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000514
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000515 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000516 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000517 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000518 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000519 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000520 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000521 // If the operation failed to simplify, or simplified to a different value
522 // to previously, then give up.
523 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000524 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000525 CommonValue = V;
526 }
527
528 return CommonValue;
529}
530
Sanjay Patel472cc782016-01-11 22:14:42 +0000531/// Given operands for an Add, see if we can fold the result.
532/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000533static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000534 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000535 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000536 if (Constant *CRHS = dyn_cast<Constant>(Op1))
537 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Chris Lattner3d9823b2009-11-27 17:42:22 +0000539 // Canonicalize the constant to the RHS.
540 std::swap(Op0, Op1);
541 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000544 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000545 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + 0 -> X
548 if (match(Op1, m_Zero()))
549 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000550
Duncan Sands0a2c41682010-12-15 14:07:39 +0000551 // X + (Y - X) -> Y
552 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000553 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000554 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000555 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
556 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000557 return Y;
558
559 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000560 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000561 if (match(Op0, m_Not(m_Specific(Op1))) ||
562 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000563 return Constant::getAllOnesValue(Ty);
564
565 // add nsw/nuw (xor Y, signbit), signbit --> Y
566 // The no-wrapping add guarantees that the top bit will be set by the add.
567 // Therefore, the xor must be clearing the already set sign bit of Y.
Craig Topper3a40a392017-03-30 22:21:16 +0000568 if ((isNSW || isNUW) && match(Op1, m_SignBit()) &&
569 match(Op0, m_Xor(m_Value(Y), m_SignBit())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000570 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000571
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000572 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000573 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000574 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000575 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000576
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000577 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000578 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000579 MaxRecurse))
580 return V;
581
Duncan Sandsb238de02010-11-19 09:20:39 +0000582 // Threading Add over selects and phi nodes is pointless, so don't bother.
583 // Threading over the select in "A + select(cond, B, C)" means evaluating
584 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
585 // only if B and C are equal. If B and C are equal then (since we assume
586 // that operands have already been simplified) "select(cond, B, C)" should
587 // have been simplified to the common value of B and C already. Analysing
588 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
589 // for threading over phi nodes.
590
Craig Topper9f008862014-04-15 04:59:12 +0000591 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000592}
593
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000594Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000596 const DominatorTree *DT, AssumptionCache *AC,
597 const Instruction *CxtI) {
598 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000599 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000600}
601
Chandler Carrutha0796552012-03-12 11:19:31 +0000602/// \brief Compute the base pointer and cumulative constant offsets for V.
603///
604/// This strips all constant offsets off of V, leaving it the base pointer, and
605/// accumulates the total constant offset applied in the returned constant. It
606/// returns 0 if V is not a pointer, and returns the constant '0' if there are
607/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000608///
609/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
610/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
611/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000612static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000613 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000614 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000615
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000616 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000617 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000618
619 // Even though we don't look through PHI nodes, we could be called on an
620 // instruction in an unreachable block, which may be on a cycle.
621 SmallPtrSet<Value *, 4> Visited;
622 Visited.insert(V);
623 do {
624 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000625 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000626 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000627 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000628 V = GEP->getPointerOperand();
629 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000630 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000631 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000632 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000633 break;
634 V = GA->getAliasee();
635 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000636 if (auto CS = CallSite(V))
637 if (Value *RV = CS.getReturnedArgOperand()) {
638 V = RV;
639 continue;
640 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000641 break;
642 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000643 assert(V->getType()->getScalarType()->isPointerTy() &&
644 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000645 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000646
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000647 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
648 if (V->getType()->isVectorTy())
649 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
650 OffsetIntPtr);
651 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000652}
653
654/// \brief Compute the constant difference between two pointer values.
655/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000656static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
657 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000658 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
659 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000660
661 // If LHS and RHS are not related via constant offsets to the same base
662 // value, there is nothing we can do here.
663 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000664 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000665
666 // Otherwise, the difference of LHS - RHS can be computed as:
667 // LHS - RHS
668 // = (LHSOffset + Base) - (RHSOffset + Base)
669 // = LHSOffset - RHSOffset
670 return ConstantExpr::getSub(LHSOffset, RHSOffset);
671}
672
Sanjay Patel472cc782016-01-11 22:14:42 +0000673/// Given operands for a Sub, see if we can fold the result.
674/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000675static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000676 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000677 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000678 if (Constant *CRHS = dyn_cast<Constant>(Op1))
679 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000680
681 // X - undef -> undef
682 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000683 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000684 return UndefValue::get(Op0->getType());
685
686 // X - 0 -> X
687 if (match(Op1, m_Zero()))
688 return Op0;
689
690 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000691 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000692 return Constant::getNullValue(Op0->getType());
693
Sanjay Patelefd88852016-10-19 21:23:45 +0000694 // Is this a negation?
695 if (match(Op0, m_Zero())) {
696 // 0 - X -> 0 if the sub is NUW.
697 if (isNUW)
698 return Op0;
699
700 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
701 APInt KnownZero(BitWidth, 0);
702 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000703 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topper6856d342017-03-30 22:10:54 +0000704 if (KnownZero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000705 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
706 // Op1 must be 0 because negating the minimum signed value is undefined.
707 if (isNSW)
708 return Op0;
709
710 // 0 - X -> X if X is 0 or the minimum signed value.
711 return Op1;
712 }
713 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000714
Duncan Sands99589d02011-01-18 11:50:19 +0000715 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
716 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000717 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000718 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
719 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000720 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000721 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000722 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // It does, we successfully reassociated!
724 ++NumReassoc;
725 return W;
726 }
727 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000728 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000729 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does, we successfully reassociated!
732 ++NumReassoc;
733 return W;
734 }
735 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000736
Duncan Sands99589d02011-01-18 11:50:19 +0000737 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
738 // For example, X - (X + 1) -> -1
739 X = Op0;
740 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
741 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000742 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000743 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000744 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000745 // It does, we successfully reassociated!
746 ++NumReassoc;
747 return W;
748 }
749 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000750 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000751 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000752 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000753 // It does, we successfully reassociated!
754 ++NumReassoc;
755 return W;
756 }
757 }
758
759 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
760 // For example, X - (X - Y) -> Y.
761 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000762 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
763 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000764 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000765 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000766 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000767 // It does, we successfully reassociated!
768 ++NumReassoc;
769 return W;
770 }
771
Duncan Sands395ac42d2012-03-13 14:07:05 +0000772 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
773 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
774 match(Op1, m_Trunc(m_Value(Y))))
775 if (X->getType() == Y->getType())
776 // See if "V === X - Y" simplifies.
777 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
778 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000779 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
780 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000781 // It does, return the simplified "trunc V".
782 return W;
783
784 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000785 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000786 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000787 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000788 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
789
Duncan Sands99589d02011-01-18 11:50:19 +0000790 // i1 sub -> xor.
791 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000792 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000793 return V;
794
Duncan Sands0a2c41682010-12-15 14:07:39 +0000795 // Threading Sub over selects and phi nodes is pointless, so don't bother.
796 // Threading over the select in "A - select(cond, B, C)" means evaluating
797 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
798 // only if B and C are equal. If B and C are equal then (since we assume
799 // that operands have already been simplified) "select(cond, B, C)" should
800 // have been simplified to the common value of B and C already. Analysing
801 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
802 // for threading over phi nodes.
803
Craig Topper9f008862014-04-15 04:59:12 +0000804 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000805}
806
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000807Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000808 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000809 const DominatorTree *DT, AssumptionCache *AC,
810 const Instruction *CxtI) {
811 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000812 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000813}
814
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000815/// Given operands for an FAdd, see if we can fold the result. If not, this
816/// returns null.
817static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
818 const Query &Q, unsigned MaxRecurse) {
819 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000820 if (Constant *CRHS = dyn_cast<Constant>(Op1))
821 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000822
823 // Canonicalize the constant to the RHS.
824 std::swap(Op0, Op1);
825 }
826
827 // fadd X, -0 ==> X
828 if (match(Op1, m_NegZero()))
829 return Op0;
830
831 // fadd X, 0 ==> X, when we know X is not -0
832 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000833 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000834 return Op0;
835
836 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
837 // where nnan and ninf have to occur at least once somewhere in this
838 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000839 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000840 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
841 SubOp = Op1;
842 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
843 SubOp = Op0;
844 if (SubOp) {
845 Instruction *FSub = cast<Instruction>(SubOp);
846 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
847 (FMF.noInfs() || FSub->hasNoInfs()))
848 return Constant::getNullValue(Op0->getType());
849 }
850
Craig Topper9f008862014-04-15 04:59:12 +0000851 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852}
853
854/// Given operands for an FSub, see if we can fold the result. If not, this
855/// returns null.
856static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
857 const Query &Q, unsigned MaxRecurse) {
858 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000859 if (Constant *CRHS = dyn_cast<Constant>(Op1))
860 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000861 }
862
863 // fsub X, 0 ==> X
864 if (match(Op1, m_Zero()))
865 return Op0;
866
867 // fsub X, -0 ==> X, when we know X is not -0
868 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000869 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000870 return Op0;
871
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000872 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000873 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000874 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
875 return X;
876
877 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000878 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000879 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
880 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000881
Benjamin Kramer228680d2015-06-14 21:01:20 +0000882 // fsub nnan x, x ==> 0.0
883 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000884 return Constant::getNullValue(Op0->getType());
885
Craig Topper9f008862014-04-15 04:59:12 +0000886 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000887}
888
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000889/// Given the operands for an FMul, see if we can fold the result
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000890static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
891 const Query &Q, unsigned MaxRecurse) {
892 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000893 if (Constant *CRHS = dyn_cast<Constant>(Op1))
894 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000895
896 // Canonicalize the constant to the RHS.
897 std::swap(Op0, Op1);
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000898 }
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000899
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000900 // fmul X, 1.0 ==> X
901 if (match(Op1, m_FPOne()))
902 return Op0;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000903
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000904 // fmul nnan nsz X, 0 ==> 0
905 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
906 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000907
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000908 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000909}
910
Sanjay Patel472cc782016-01-11 22:14:42 +0000911/// Given operands for a Mul, see if we can fold the result.
912/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000913static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
914 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000915 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000916 if (Constant *CRHS = dyn_cast<Constant>(Op1))
917 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000918
919 // Canonicalize the constant to the RHS.
920 std::swap(Op0, Op1);
921 }
922
923 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000924 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000925 return Constant::getNullValue(Op0->getType());
926
927 // X * 0 -> 0
928 if (match(Op1, m_Zero()))
929 return Op1;
930
931 // X * 1 -> X
932 if (match(Op1, m_One()))
933 return Op0;
934
Duncan Sandsb67edc62011-01-30 18:03:50 +0000935 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000936 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000937 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
938 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
939 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000940
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000941 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000942 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000943 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000944 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000945
946 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000947 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000948 MaxRecurse))
949 return V;
950
951 // Mul distributes over Add. Try some generic simplifications based on this.
952 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000953 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000954 return V;
955
956 // If the operation is with the result of a select instruction, check whether
957 // operating on either branch of the select always yields the same value.
958 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000959 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000960 MaxRecurse))
961 return V;
962
963 // If the operation is with the result of a phi instruction, check whether
964 // operating on all incoming values of the phi always yields the same value.
965 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000966 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000967 MaxRecurse))
968 return V;
969
Craig Topper9f008862014-04-15 04:59:12 +0000970 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000971}
972
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000973Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000974 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000975 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000976 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000977 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000978 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000979 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000980}
981
982Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000983 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000984 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000985 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000986 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000987 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000988 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000989}
990
Chandler Carruth66b31302015-01-04 12:03:27 +0000991Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000992 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000993 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000994 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000995 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000996 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000997 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000998}
999
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001000Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001001 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001002 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001003 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001004 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001005 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001006}
1007
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001008/// Check for common or similar folds of integer division or integer remainder.
1009static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
1010 Type *Ty = Op0->getType();
1011
1012 // X / undef -> undef
1013 // X % undef -> undef
1014 if (match(Op1, m_Undef()))
1015 return Op1;
1016
1017 // X / 0 -> undef
1018 // X % 0 -> undef
1019 // We don't need to preserve faults!
1020 if (match(Op1, m_Zero()))
1021 return UndefValue::get(Ty);
1022
Sanjay Patel2b1f6f42017-03-09 16:20:52 +00001023 // If any element of a constant divisor vector is zero, the whole op is undef.
1024 auto *Op1C = dyn_cast<Constant>(Op1);
1025 if (Op1C && Ty->isVectorTy()) {
1026 unsigned NumElts = Ty->getVectorNumElements();
1027 for (unsigned i = 0; i != NumElts; ++i) {
1028 Constant *Elt = Op1C->getAggregateElement(i);
1029 if (Elt && Elt->isNullValue())
1030 return UndefValue::get(Ty);
1031 }
1032 }
1033
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001034 // undef / X -> 0
1035 // undef % X -> 0
1036 if (match(Op0, m_Undef()))
1037 return Constant::getNullValue(Ty);
1038
1039 // 0 / X -> 0
1040 // 0 % X -> 0
1041 if (match(Op0, m_Zero()))
1042 return Op0;
1043
1044 // X / X -> 1
1045 // X % X -> 0
1046 if (Op0 == Op1)
1047 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1048
1049 // X / 1 -> X
1050 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +00001051 // If this is a boolean op (single-bit element type), we can't have
1052 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
1053 if (match(Op1, m_One()) || Ty->getScalarType()->isIntegerTy(1))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001054 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1055
1056 return nullptr;
1057}
1058
Sanjay Patel472cc782016-01-11 22:14:42 +00001059/// Given operands for an SDiv or UDiv, see if we can fold the result.
1060/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001061static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001062 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001063 if (Constant *C0 = dyn_cast<Constant>(Op0))
1064 if (Constant *C1 = dyn_cast<Constant>(Op1))
1065 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001066
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001067 if (Value *V = simplifyDivRem(Op0, Op1, true))
1068 return V;
1069
Duncan Sands65995fa2011-01-28 18:50:50 +00001070 bool isSigned = Opcode == Instruction::SDiv;
1071
Duncan Sands771e82a2011-01-28 16:51:11 +00001072 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001073 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001074 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1075 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001076 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001077 // If the Mul knows it does not overflow, then we are good to go.
1078 if ((isSigned && Mul->hasNoSignedWrap()) ||
1079 (!isSigned && Mul->hasNoUnsignedWrap()))
1080 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001081 // If X has the form X = A / Y then X * Y cannot overflow.
1082 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1083 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1084 return X;
1085 }
1086
Duncan Sands65995fa2011-01-28 18:50:50 +00001087 // (X rem Y) / Y -> 0
1088 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1089 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1090 return Constant::getNullValue(Op0->getType());
1091
David Majnemercb9d5962014-10-11 10:20:01 +00001092 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1093 ConstantInt *C1, *C2;
1094 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1095 match(Op1, m_ConstantInt(C2))) {
1096 bool Overflow;
1097 C1->getValue().umul_ov(C2->getValue(), Overflow);
1098 if (Overflow)
1099 return Constant::getNullValue(Op0->getType());
1100 }
1101
Duncan Sands65995fa2011-01-28 18:50:50 +00001102 // If the operation is with the result of a select instruction, check whether
1103 // operating on either branch of the select always yields the same value.
1104 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001105 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001106 return V;
1107
1108 // If the operation is with the result of a phi instruction, check whether
1109 // operating on all incoming values of the phi always yields the same value.
1110 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001111 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001112 return V;
1113
Craig Topper9f008862014-04-15 04:59:12 +00001114 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001115}
1116
Sanjay Patel472cc782016-01-11 22:14:42 +00001117/// Given operands for an SDiv, see if we can fold the result.
1118/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001119static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1120 unsigned MaxRecurse) {
1121 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001122 return V;
1123
Craig Topper9f008862014-04-15 04:59:12 +00001124 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001125}
1126
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001127Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001128 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001129 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001130 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001131 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001132 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001133}
1134
Sanjay Patel472cc782016-01-11 22:14:42 +00001135/// Given operands for a UDiv, see if we can fold the result.
1136/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001137static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1138 unsigned MaxRecurse) {
1139 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001140 return V;
1141
David Majnemer63da0c22017-01-06 22:58:02 +00001142 // udiv %V, C -> 0 if %V < C
1143 if (MaxRecurse) {
1144 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1145 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1146 if (C->isAllOnesValue()) {
1147 return Constant::getNullValue(Op0->getType());
1148 }
1149 }
1150 }
1151
Craig Topper9f008862014-04-15 04:59:12 +00001152 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001153}
1154
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001155Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001156 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001157 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001158 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001159 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001160 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001161}
1162
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001163static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1164 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001165 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001166 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001167 return Op0;
1168
1169 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001170 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001171 return Op1;
1172
Zia Ansari394cef82016-12-08 23:27:40 +00001173 // X / 1.0 -> X
1174 if (match(Op1, m_FPOne()))
1175 return Op0;
1176
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001177 // 0 / X -> 0
1178 // Requires that NaNs are off (X could be zero) and signed zeroes are
1179 // ignored (X could be positive or negative, so the output sign is unknown).
1180 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1181 return Op0;
1182
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001183 if (FMF.noNaNs()) {
1184 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001185 if (Op0 == Op1)
1186 return ConstantFP::get(Op0->getType(), 1.0);
1187
1188 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001189 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001190 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1191 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1192 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1193 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1194 BinaryOperator::getFNegArgument(Op1) == Op0))
1195 return ConstantFP::get(Op0->getType(), -1.0);
1196 }
1197
Craig Topper9f008862014-04-15 04:59:12 +00001198 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001199}
1200
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001201Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001202 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001203 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001204 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001205 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001206 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001207 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001208}
1209
Sanjay Patel472cc782016-01-11 22:14:42 +00001210/// Given operands for an SRem or URem, see if we can fold the result.
1211/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001212static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001213 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001214 if (Constant *C0 = dyn_cast<Constant>(Op0))
1215 if (Constant *C1 = dyn_cast<Constant>(Op1))
1216 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001217
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001218 if (Value *V = simplifyDivRem(Op0, Op1, false))
1219 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001220
David Majnemerb435a422014-09-17 04:16:35 +00001221 // (X % Y) % Y -> X % Y
1222 if ((Opcode == Instruction::SRem &&
1223 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1224 (Opcode == Instruction::URem &&
1225 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001226 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001227
Duncan Sandsa3e36992011-05-02 16:27:02 +00001228 // If the operation is with the result of a select instruction, check whether
1229 // operating on either branch of the select always yields the same value.
1230 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001231 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001232 return V;
1233
1234 // If the operation is with the result of a phi instruction, check whether
1235 // operating on all incoming values of the phi always yields the same value.
1236 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001237 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001238 return V;
1239
Craig Topper9f008862014-04-15 04:59:12 +00001240 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001241}
1242
Sanjay Patel472cc782016-01-11 22:14:42 +00001243/// Given operands for an SRem, see if we can fold the result.
1244/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001245static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1246 unsigned MaxRecurse) {
1247 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248 return V;
1249
Craig Topper9f008862014-04-15 04:59:12 +00001250 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001251}
1252
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001253Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001254 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001255 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001256 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001257 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001258 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001259}
1260
Sanjay Patel472cc782016-01-11 22:14:42 +00001261/// Given operands for a URem, see if we can fold the result.
1262/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001263static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001264 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001265 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001266 return V;
1267
David Majnemer8c0e62f2017-01-06 21:23:51 +00001268 // urem %V, C -> %V if %V < C
1269 if (MaxRecurse) {
1270 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1271 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1272 if (C->isAllOnesValue()) {
1273 return Op0;
1274 }
1275 }
1276 }
1277
Craig Topper9f008862014-04-15 04:59:12 +00001278 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001279}
1280
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001281Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001282 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001283 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001284 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001285 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001286 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001287}
1288
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001289static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1290 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001291 // undef % X -> undef (the undef could be a snan).
1292 if (match(Op0, m_Undef()))
1293 return Op0;
1294
1295 // X % undef -> undef
1296 if (match(Op1, m_Undef()))
1297 return Op1;
1298
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001299 // 0 % X -> 0
1300 // Requires that NaNs are off (X could be zero) and signed zeroes are
1301 // ignored (X could be positive or negative, so the output sign is unknown).
1302 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1303 return Op0;
1304
Craig Topper9f008862014-04-15 04:59:12 +00001305 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001306}
1307
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001308Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001309 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001310 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001311 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001312 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001313 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001314 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001315}
1316
Sanjay Patel472cc782016-01-11 22:14:42 +00001317/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001318static bool isUndefShift(Value *Amount) {
1319 Constant *C = dyn_cast<Constant>(Amount);
1320 if (!C)
1321 return false;
1322
1323 // X shift by undef -> undef because it may shift by the bitwidth.
1324 if (isa<UndefValue>(C))
1325 return true;
1326
1327 // Shifting by the bitwidth or more is undefined.
1328 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1329 if (CI->getValue().getLimitedValue() >=
1330 CI->getType()->getScalarSizeInBits())
1331 return true;
1332
1333 // If all lanes of a vector shift are undefined the whole shift is.
1334 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1335 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1336 if (!isUndefShift(C->getAggregateElement(I)))
1337 return false;
1338 return true;
1339 }
1340
1341 return false;
1342}
1343
Sanjay Patel472cc782016-01-11 22:14:42 +00001344/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1345/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001346static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001347 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001348 if (Constant *C0 = dyn_cast<Constant>(Op0))
1349 if (Constant *C1 = dyn_cast<Constant>(Op1))
1350 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001351
Duncan Sands571fd9a2011-01-14 14:44:12 +00001352 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001353 if (match(Op0, m_Zero()))
1354 return Op0;
1355
Duncan Sands571fd9a2011-01-14 14:44:12 +00001356 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001357 if (match(Op1, m_Zero()))
1358 return Op0;
1359
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001360 // Fold undefined shifts.
1361 if (isUndefShift(Op1))
1362 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001363
Duncan Sands571fd9a2011-01-14 14:44:12 +00001364 // If the operation is with the result of a select instruction, check whether
1365 // operating on either branch of the select always yields the same value.
1366 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001367 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001368 return V;
1369
1370 // If the operation is with the result of a phi instruction, check whether
1371 // operating on all incoming values of the phi always yields the same value.
1372 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001373 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001374 return V;
1375
Sanjay Patel6786bc52016-05-10 20:46:54 +00001376 // If any bits in the shift amount make that value greater than or equal to
1377 // the number of bits in the type, the shift is undefined.
1378 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1379 APInt KnownZero(BitWidth, 0);
1380 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001381 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001382 if (KnownOne.getLimitedValue() >= BitWidth)
1383 return UndefValue::get(Op0->getType());
1384
1385 // If all valid bits in the shift amount are known zero, the first operand is
1386 // unchanged.
1387 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1388 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1389 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1390 return Op0;
1391
Craig Topper9f008862014-04-15 04:59:12 +00001392 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001393}
1394
David Majnemerbf7550e2014-11-05 00:59:59 +00001395/// \brief Given operands for an Shl, LShr or AShr, see if we can
1396/// fold the result. If not, this returns null.
1397static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1398 bool isExact, const Query &Q,
1399 unsigned MaxRecurse) {
1400 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1401 return V;
1402
1403 // X >> X -> 0
1404 if (Op0 == Op1)
1405 return Constant::getNullValue(Op0->getType());
1406
David Majnemer65c52ae2014-12-17 01:54:33 +00001407 // undef >> X -> 0
1408 // undef >> X -> undef (if it's exact)
1409 if (match(Op0, m_Undef()))
1410 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1411
David Majnemerbf7550e2014-11-05 00:59:59 +00001412 // The low bit cannot be shifted out of an exact shift if it is set.
1413 if (isExact) {
1414 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1415 APInt Op0KnownZero(BitWidth, 0);
1416 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001417 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1418 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001419 if (Op0KnownOne[0])
1420 return Op0;
1421 }
1422
1423 return nullptr;
1424}
1425
Sanjay Patel472cc782016-01-11 22:14:42 +00001426/// Given operands for an Shl, see if we can fold the result.
1427/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001428static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001429 const Query &Q, unsigned MaxRecurse) {
1430 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001431 return V;
1432
1433 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001434 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001435 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001436 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001437
Chris Lattner9e4aa022011-02-09 17:15:04 +00001438 // (X >> A) << A -> X
1439 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001440 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001441 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001442 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001443}
1444
Chris Lattner9e4aa022011-02-09 17:15:04 +00001445Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001446 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001447 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001448 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001449 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001450 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001451}
1452
Sanjay Patel472cc782016-01-11 22:14:42 +00001453/// Given operands for an LShr, see if we can fold the result.
1454/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001455static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001456 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001457 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1458 MaxRecurse))
1459 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001460
Chris Lattner9e4aa022011-02-09 17:15:04 +00001461 // (X << A) >> A -> X
1462 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001463 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001464 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001465
Craig Topper9f008862014-04-15 04:59:12 +00001466 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001467}
1468
Chris Lattner9e4aa022011-02-09 17:15:04 +00001469Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001470 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001471 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001472 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001473 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001474 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001475 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001476}
1477
Sanjay Patel472cc782016-01-11 22:14:42 +00001478/// Given operands for an AShr, see if we can fold the result.
1479/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001480static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001481 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001482 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1483 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001484 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001485
1486 // all ones >>a X -> all ones
1487 if (match(Op0, m_AllOnes()))
1488 return Op0;
1489
Chris Lattner9e4aa022011-02-09 17:15:04 +00001490 // (X << A) >> A -> X
1491 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001492 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001493 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001494
Suyog Sarda68862412014-07-17 06:28:15 +00001495 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001496 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001497 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1498 return Op0;
1499
Craig Topper9f008862014-04-15 04:59:12 +00001500 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001501}
1502
Chris Lattner9e4aa022011-02-09 17:15:04 +00001503Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001504 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001505 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001506 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001507 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001508 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001509 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001510}
1511
David Majnemer1af36e52014-12-06 10:51:40 +00001512static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1513 ICmpInst *UnsignedICmp, bool IsAnd) {
1514 Value *X, *Y;
1515
1516 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001517 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1518 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001519 return nullptr;
1520
1521 ICmpInst::Predicate UnsignedPred;
1522 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1523 ICmpInst::isUnsigned(UnsignedPred))
1524 ;
1525 else if (match(UnsignedICmp,
1526 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1527 ICmpInst::isUnsigned(UnsignedPred))
1528 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1529 else
1530 return nullptr;
1531
1532 // X < Y && Y != 0 --> X < Y
1533 // X < Y || Y != 0 --> Y != 0
1534 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1535 return IsAnd ? UnsignedICmp : ZeroICmp;
1536
1537 // X >= Y || Y != 0 --> true
1538 // X >= Y || Y == 0 --> X >= Y
1539 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1540 if (EqPred == ICmpInst::ICMP_NE)
1541 return getTrue(UnsignedICmp->getType());
1542 return UnsignedICmp;
1543 }
1544
David Majnemerd5b3aa42014-12-08 18:30:43 +00001545 // X < Y && Y == 0 --> false
1546 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1547 IsAnd)
1548 return getFalse(UnsignedICmp->getType());
1549
David Majnemer1af36e52014-12-06 10:51:40 +00001550 return nullptr;
1551}
1552
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001553/// Commuted variants are assumed to be handled by calling this function again
1554/// with the parameters swapped.
1555static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1556 ICmpInst::Predicate Pred0, Pred1;
1557 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001558 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1559 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001560 return nullptr;
1561
1562 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1563 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1564 // can eliminate Op1 from this 'and'.
1565 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1566 return Op0;
1567
1568 // Check for any combination of predicates that are guaranteed to be disjoint.
1569 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1570 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1571 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1572 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1573 return getFalse(Op0->getType());
1574
1575 return nullptr;
1576}
1577
1578/// Commuted variants are assumed to be handled by calling this function again
1579/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001580static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001581 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1582 return X;
1583
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001584 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1585 return X;
1586
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001587 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001588 Type *ITy = Op0->getType();
1589 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001590 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001591 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001592 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1593 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1594 // Make a constant range that's the intersection of the two icmp ranges.
1595 // If the intersection is empty, we know that the result is false.
1596 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1597 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1598 if (Range0.intersectWith(Range1).isEmptySet())
1599 return getFalse(ITy);
1600 }
1601
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001602 // (icmp (add V, C0), C1) & (icmp V, C0)
1603 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001604 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001605
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001606 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001607 return nullptr;
1608
David Majnemera315bd82014-09-15 08:15:28 +00001609 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001610 if (AddInst->getOperand(1) != Op1->getOperand(1))
1611 return nullptr;
1612
David Majnemera315bd82014-09-15 08:15:28 +00001613 bool isNSW = AddInst->hasNoSignedWrap();
1614 bool isNUW = AddInst->hasNoUnsignedWrap();
1615
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001616 const APInt Delta = *C1 - *C0;
1617 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001618 if (Delta == 2) {
1619 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1620 return getFalse(ITy);
1621 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1622 return getFalse(ITy);
1623 }
1624 if (Delta == 1) {
1625 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1626 return getFalse(ITy);
1627 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1628 return getFalse(ITy);
1629 }
1630 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001631 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001632 if (Delta == 2)
1633 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1634 return getFalse(ITy);
1635 if (Delta == 1)
1636 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1637 return getFalse(ITy);
1638 }
1639
1640 return nullptr;
1641}
1642
Sanjay Patel472cc782016-01-11 22:14:42 +00001643/// Given operands for an And, see if we can fold the result.
1644/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001645static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001646 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001647 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001648 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1649 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001650
Chris Lattnera71e9d62009-11-10 00:55:12 +00001651 // Canonicalize the constant to the RHS.
1652 std::swap(Op0, Op1);
1653 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001654
Chris Lattnera71e9d62009-11-10 00:55:12 +00001655 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001656 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001657 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001658
Chris Lattnera71e9d62009-11-10 00:55:12 +00001659 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001660 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001661 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001662
Duncan Sandsc89ac072010-11-17 18:52:15 +00001663 // X & 0 = 0
1664 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001665 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001666
Duncan Sandsc89ac072010-11-17 18:52:15 +00001667 // X & -1 = X
1668 if (match(Op1, m_AllOnes()))
1669 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001670
Chris Lattnera71e9d62009-11-10 00:55:12 +00001671 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001672 if (match(Op0, m_Not(m_Specific(Op1))) ||
1673 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001674 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001675
Chris Lattnera71e9d62009-11-10 00:55:12 +00001676 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001677 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001678 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001679 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001680 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001681
Chris Lattnera71e9d62009-11-10 00:55:12 +00001682 // A & (A | ?) = A
1683 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001684 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001685 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001686
Duncan Sandsba286d72011-10-26 20:55:21 +00001687 // A & (-A) = A if A is a power of two or zero.
1688 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1689 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001690 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1691 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001692 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001693 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1694 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001695 return Op1;
1696 }
1697
David Majnemera315bd82014-09-15 08:15:28 +00001698 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1699 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1700 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1701 return V;
1702 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1703 return V;
1704 }
1705 }
1706
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001707 // The compares may be hidden behind casts. Look through those and try the
1708 // same folds as above.
1709 auto *Cast0 = dyn_cast<CastInst>(Op0);
1710 auto *Cast1 = dyn_cast<CastInst>(Op1);
1711 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1712 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1713 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1714 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1715 if (Cmp0 && Cmp1) {
1716 Instruction::CastOps CastOpc = Cast0->getOpcode();
1717 Type *ResultType = Cast0->getType();
1718 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1719 return ConstantExpr::getCast(CastOpc, V, ResultType);
1720 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1721 return ConstantExpr::getCast(CastOpc, V, ResultType);
1722 }
1723 }
1724
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001725 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001726 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1727 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001728 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001729
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001730 // And distributes over Or. Try some generic simplifications based on this.
1731 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001732 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001733 return V;
1734
1735 // And distributes over Xor. Try some generic simplifications based on this.
1736 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001737 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001738 return V;
1739
Duncan Sandsb0579e92010-11-10 13:00:08 +00001740 // If the operation is with the result of a select instruction, check whether
1741 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001742 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001743 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1744 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001745 return V;
1746
1747 // If the operation is with the result of a phi instruction, check whether
1748 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001749 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001750 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001751 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001752 return V;
1753
Craig Topper9f008862014-04-15 04:59:12 +00001754 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001755}
1756
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001757Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001758 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001759 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001760 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001761 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001762 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001763}
1764
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001765/// Commuted variants are assumed to be handled by calling this function again
1766/// with the parameters swapped.
1767static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1768 ICmpInst::Predicate Pred0, Pred1;
1769 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001770 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1771 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001772 return nullptr;
1773
1774 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1775 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1776 // can eliminate Op0 from this 'or'.
1777 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1778 return Op1;
1779
1780 // Check for any combination of predicates that cover the entire range of
1781 // possibilities.
1782 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1783 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1784 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1785 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1786 return getTrue(Op0->getType());
1787
1788 return nullptr;
1789}
1790
1791/// Commuted variants are assumed to be handled by calling this function again
1792/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001793static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001794 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1795 return X;
1796
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001797 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1798 return X;
1799
Sanjay Patel220a8732016-09-28 14:27:21 +00001800 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001801 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001802 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001803 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001804 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001805 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001806
Sanjay Patel220a8732016-09-28 14:27:21 +00001807 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1808 return nullptr;
1809
1810 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1811 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001812 return nullptr;
1813
1814 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001815 bool isNSW = AddInst->hasNoSignedWrap();
1816 bool isNUW = AddInst->hasNoUnsignedWrap();
1817
Sanjay Patel220a8732016-09-28 14:27:21 +00001818 const APInt Delta = *C1 - *C0;
1819 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001820 if (Delta == 2) {
1821 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1822 return getTrue(ITy);
1823 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1824 return getTrue(ITy);
1825 }
1826 if (Delta == 1) {
1827 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1828 return getTrue(ITy);
1829 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1830 return getTrue(ITy);
1831 }
1832 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001833 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001834 if (Delta == 2)
1835 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1836 return getTrue(ITy);
1837 if (Delta == 1)
1838 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1839 return getTrue(ITy);
1840 }
1841
1842 return nullptr;
1843}
1844
Sanjay Patel472cc782016-01-11 22:14:42 +00001845/// Given operands for an Or, see if we can fold the result.
1846/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001847static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1848 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001849 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001850 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1851 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001852
Chris Lattnera71e9d62009-11-10 00:55:12 +00001853 // Canonicalize the constant to the RHS.
1854 std::swap(Op0, Op1);
1855 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001856
Chris Lattnera71e9d62009-11-10 00:55:12 +00001857 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001858 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001859 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001860
Chris Lattnera71e9d62009-11-10 00:55:12 +00001861 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001862 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001863 return Op0;
1864
Duncan Sandsc89ac072010-11-17 18:52:15 +00001865 // X | 0 = X
1866 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001867 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001868
Duncan Sandsc89ac072010-11-17 18:52:15 +00001869 // X | -1 = -1
1870 if (match(Op1, m_AllOnes()))
1871 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001872
Chris Lattnera71e9d62009-11-10 00:55:12 +00001873 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001874 if (match(Op0, m_Not(m_Specific(Op1))) ||
1875 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001876 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001877
Chris Lattnera71e9d62009-11-10 00:55:12 +00001878 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001879 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001880 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001881 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001882 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001883
Chris Lattnera71e9d62009-11-10 00:55:12 +00001884 // A | (A & ?) = A
1885 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001886 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001887 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001888
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001889 // ~(A & ?) | A = -1
1890 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1891 (A == Op1 || B == Op1))
1892 return Constant::getAllOnesValue(Op1->getType());
1893
1894 // A | ~(A & ?) = -1
1895 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1896 (A == Op0 || B == Op0))
1897 return Constant::getAllOnesValue(Op0->getType());
1898
David Majnemera315bd82014-09-15 08:15:28 +00001899 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1900 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1901 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1902 return V;
1903 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1904 return V;
1905 }
1906 }
1907
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001908 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001909 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1910 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001911 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001912
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001913 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001914 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1915 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001916 return V;
1917
Duncan Sandsb0579e92010-11-10 13:00:08 +00001918 // If the operation is with the result of a select instruction, check whether
1919 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001920 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001921 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001922 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001923 return V;
1924
Nick Lewycky8561a492014-06-19 03:51:46 +00001925 // (A & C)|(B & D)
1926 Value *C = nullptr, *D = nullptr;
1927 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1928 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1929 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1930 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1931 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1932 // (A & C1)|(B & C2)
1933 // If we have: ((V + N) & C1) | (V & C2)
1934 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1935 // replace with V+N.
1936 Value *V1, *V2;
1937 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1938 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1939 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001940 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001941 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001942 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001943 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001944 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001945 return A;
1946 }
1947 // Or commutes, try both ways.
1948 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1949 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1950 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001951 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001952 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001953 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001954 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001955 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001956 return B;
1957 }
1958 }
1959 }
1960
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001961 // If the operation is with the result of a phi instruction, check whether
1962 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001963 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001964 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001965 return V;
1966
Craig Topper9f008862014-04-15 04:59:12 +00001967 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001968}
1969
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001970Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001971 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001972 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001973 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001974 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001975 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001976}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001977
Sanjay Patel472cc782016-01-11 22:14:42 +00001978/// Given operands for a Xor, see if we can fold the result.
1979/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001980static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1981 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001982 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001983 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1984 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001985
1986 // Canonicalize the constant to the RHS.
1987 std::swap(Op0, Op1);
1988 }
1989
1990 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001991 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001992 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001993
1994 // A ^ 0 = A
1995 if (match(Op1, m_Zero()))
1996 return Op0;
1997
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001998 // A ^ A = 0
1999 if (Op0 == Op1)
2000 return Constant::getNullValue(Op0->getType());
2001
Duncan Sandsc89ac072010-11-17 18:52:15 +00002002 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00002003 if (match(Op0, m_Not(m_Specific(Op1))) ||
2004 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002005 return Constant::getAllOnesValue(Op0->getType());
2006
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002007 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002008 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2009 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002010 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002011
Duncan Sandsb238de02010-11-19 09:20:39 +00002012 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2013 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2014 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2015 // only if B and C are equal. If B and C are equal then (since we assume
2016 // that operands have already been simplified) "select(cond, B, C)" should
2017 // have been simplified to the common value of B and C already. Analysing
2018 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2019 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002020
Craig Topper9f008862014-04-15 04:59:12 +00002021 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002022}
2023
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002024Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002025 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002026 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002027 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002028 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002029 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002030}
2031
Chris Lattner229907c2011-07-18 04:54:35 +00002032static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002033 return CmpInst::makeCmpResultType(Op->getType());
2034}
2035
Sanjay Patel472cc782016-01-11 22:14:42 +00002036/// Rummage around inside V looking for something equivalent to the comparison
2037/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2038/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002039static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2040 Value *LHS, Value *RHS) {
2041 SelectInst *SI = dyn_cast<SelectInst>(V);
2042 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002043 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002044 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2045 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002046 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002047 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2048 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2049 return Cmp;
2050 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2051 LHS == CmpRHS && RHS == CmpLHS)
2052 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002053 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002054}
2055
Dan Gohman9631d902013-02-01 00:49:06 +00002056// A significant optimization not implemented here is assuming that alloca
2057// addresses are not equal to incoming argument values. They don't *alias*,
2058// as we say, but that doesn't mean they aren't equal, so we take a
2059// conservative approach.
2060//
2061// This is inspired in part by C++11 5.10p1:
2062// "Two pointers of the same type compare equal if and only if they are both
2063// null, both point to the same function, or both represent the same
2064// address."
2065//
2066// This is pretty permissive.
2067//
2068// It's also partly due to C11 6.5.9p6:
2069// "Two pointers compare equal if and only if both are null pointers, both are
2070// pointers to the same object (including a pointer to an object and a
2071// subobject at its beginning) or function, both are pointers to one past the
2072// last element of the same array object, or one is a pointer to one past the
2073// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002074// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002075// object in the address space.)
2076//
2077// C11's version is more restrictive, however there's no reason why an argument
2078// couldn't be a one-past-the-end value for a stack object in the caller and be
2079// equal to the beginning of a stack object in the callee.
2080//
2081// If the C and C++ standards are ever made sufficiently restrictive in this
2082// area, it may be possible to update LLVM's semantics accordingly and reinstate
2083// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002084static Constant *
2085computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2086 const DominatorTree *DT, CmpInst::Predicate Pred,
2087 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002088 // First, skip past any trivial no-ops.
2089 LHS = LHS->stripPointerCasts();
2090 RHS = RHS->stripPointerCasts();
2091
2092 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002093 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002094 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2095 return ConstantInt::get(GetCompareTy(LHS),
2096 !CmpInst::isTrueWhenEqual(Pred));
2097
Chandler Carruth8059c842012-03-25 21:28:14 +00002098 // We can only fold certain predicates on pointer comparisons.
2099 switch (Pred) {
2100 default:
Craig Topper9f008862014-04-15 04:59:12 +00002101 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002102
2103 // Equality comaprisons are easy to fold.
2104 case CmpInst::ICMP_EQ:
2105 case CmpInst::ICMP_NE:
2106 break;
2107
2108 // We can only handle unsigned relational comparisons because 'inbounds' on
2109 // a GEP only protects against unsigned wrapping.
2110 case CmpInst::ICMP_UGT:
2111 case CmpInst::ICMP_UGE:
2112 case CmpInst::ICMP_ULT:
2113 case CmpInst::ICMP_ULE:
2114 // However, we have to switch them to their signed variants to handle
2115 // negative indices from the base pointer.
2116 Pred = ICmpInst::getSignedPredicate(Pred);
2117 break;
2118 }
2119
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002120 // Strip off any constant offsets so that we can reason about them.
2121 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2122 // here and compare base addresses like AliasAnalysis does, however there are
2123 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2124 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2125 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002126 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2127 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002128
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002129 // If LHS and RHS are related via constant offsets to the same base
2130 // value, we can replace it with an icmp which just compares the offsets.
2131 if (LHS == RHS)
2132 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002133
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002134 // Various optimizations for (in)equality comparisons.
2135 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2136 // Different non-empty allocations that exist at the same time have
2137 // different addresses (if the program can tell). Global variables always
2138 // exist, so they always exist during the lifetime of each other and all
2139 // allocas. Two different allocas usually have different addresses...
2140 //
2141 // However, if there's an @llvm.stackrestore dynamically in between two
2142 // allocas, they may have the same address. It's tempting to reduce the
2143 // scope of the problem by only looking at *static* allocas here. That would
2144 // cover the majority of allocas while significantly reducing the likelihood
2145 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2146 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2147 // an entry block. Also, if we have a block that's not attached to a
2148 // function, we can't tell if it's "static" under the current definition.
2149 // Theoretically, this problem could be fixed by creating a new kind of
2150 // instruction kind specifically for static allocas. Such a new instruction
2151 // could be required to be at the top of the entry block, thus preventing it
2152 // from being subject to a @llvm.stackrestore. Instcombine could even
2153 // convert regular allocas into these special allocas. It'd be nifty.
2154 // However, until then, this problem remains open.
2155 //
2156 // So, we'll assume that two non-empty allocas have different addresses
2157 // for now.
2158 //
2159 // With all that, if the offsets are within the bounds of their allocations
2160 // (and not one-past-the-end! so we can't use inbounds!), and their
2161 // allocations aren't the same, the pointers are not equal.
2162 //
2163 // Note that it's not necessary to check for LHS being a global variable
2164 // address, due to canonicalization and constant folding.
2165 if (isa<AllocaInst>(LHS) &&
2166 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002167 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2168 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002169 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002170 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002171 getObjectSize(LHS, LHSSize, DL, TLI) &&
2172 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002173 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2174 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002175 if (!LHSOffsetValue.isNegative() &&
2176 !RHSOffsetValue.isNegative() &&
2177 LHSOffsetValue.ult(LHSSize) &&
2178 RHSOffsetValue.ult(RHSSize)) {
2179 return ConstantInt::get(GetCompareTy(LHS),
2180 !CmpInst::isTrueWhenEqual(Pred));
2181 }
2182 }
2183
2184 // Repeat the above check but this time without depending on DataLayout
2185 // or being able to compute a precise size.
2186 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2187 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2188 LHSOffset->isNullValue() &&
2189 RHSOffset->isNullValue())
2190 return ConstantInt::get(GetCompareTy(LHS),
2191 !CmpInst::isTrueWhenEqual(Pred));
2192 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002193
2194 // Even if an non-inbounds GEP occurs along the path we can still optimize
2195 // equality comparisons concerning the result. We avoid walking the whole
2196 // chain again by starting where the last calls to
2197 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002198 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2199 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002200 if (LHS == RHS)
2201 return ConstantExpr::getICmp(Pred,
2202 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2203 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002204
2205 // If one side of the equality comparison must come from a noalias call
2206 // (meaning a system memory allocation function), and the other side must
2207 // come from a pointer that cannot overlap with dynamically-allocated
2208 // memory within the lifetime of the current function (allocas, byval
2209 // arguments, globals), then determine the comparison result here.
2210 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2211 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2212 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2213
2214 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002215 auto IsNAC = [](ArrayRef<Value *> Objects) {
2216 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002217 };
2218
2219 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002220 // noalias calls. For allocas, we consider only static ones (dynamic
2221 // allocas might be transformed into calls to malloc not simultaneously
2222 // live with the compared-to allocation). For globals, we exclude symbols
2223 // that might be resolve lazily to symbols in another dynamically-loaded
2224 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002225 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2226 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002227 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2228 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2229 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2230 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002231 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002232 !GV->isThreadLocal();
2233 if (const Argument *A = dyn_cast<Argument>(V))
2234 return A->hasByValAttr();
2235 return false;
2236 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002237 };
2238
2239 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2240 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2241 return ConstantInt::get(GetCompareTy(LHS),
2242 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002243
2244 // Fold comparisons for non-escaping pointer even if the allocation call
2245 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2246 // dynamic allocation call could be either of the operands.
2247 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002248 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002249 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002250 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002251 MI = RHS;
2252 // FIXME: We should also fold the compare when the pointer escapes, but the
2253 // compare dominates the pointer escape
2254 if (MI && !PointerMayBeCaptured(MI, true, true))
2255 return ConstantInt::get(GetCompareTy(LHS),
2256 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002257 }
2258
2259 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002260 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002261}
Chris Lattner01990f02012-02-24 19:01:58 +00002262
Sanjay Pateldc65a272016-12-03 17:30:22 +00002263/// Fold an icmp when its operands have i1 scalar type.
2264static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2265 Value *RHS, const Query &Q) {
2266 Type *ITy = GetCompareTy(LHS); // The return type.
2267 Type *OpTy = LHS->getType(); // The operand type.
2268 if (!OpTy->getScalarType()->isIntegerTy(1))
2269 return nullptr;
2270
2271 switch (Pred) {
2272 default:
2273 break;
2274 case ICmpInst::ICMP_EQ:
2275 // X == 1 -> X
2276 if (match(RHS, m_One()))
2277 return LHS;
2278 break;
2279 case ICmpInst::ICMP_NE:
2280 // X != 0 -> X
2281 if (match(RHS, m_Zero()))
2282 return LHS;
2283 break;
2284 case ICmpInst::ICMP_UGT:
2285 // X >u 0 -> X
2286 if (match(RHS, m_Zero()))
2287 return LHS;
2288 break;
2289 case ICmpInst::ICMP_UGE:
2290 // X >=u 1 -> X
2291 if (match(RHS, m_One()))
2292 return LHS;
2293 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2294 return getTrue(ITy);
2295 break;
2296 case ICmpInst::ICMP_SGE:
2297 /// For signed comparison, the values for an i1 are 0 and -1
2298 /// respectively. This maps into a truth table of:
2299 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2300 /// 0 | 0 | 1 (0 >= 0) | 1
2301 /// 0 | 1 | 1 (0 >= -1) | 1
2302 /// 1 | 0 | 0 (-1 >= 0) | 0
2303 /// 1 | 1 | 1 (-1 >= -1) | 1
2304 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2305 return getTrue(ITy);
2306 break;
2307 case ICmpInst::ICMP_SLT:
2308 // X <s 0 -> X
2309 if (match(RHS, m_Zero()))
2310 return LHS;
2311 break;
2312 case ICmpInst::ICMP_SLE:
2313 // X <=s -1 -> X
2314 if (match(RHS, m_One()))
2315 return LHS;
2316 break;
2317 case ICmpInst::ICMP_ULE:
2318 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2319 return getTrue(ITy);
2320 break;
2321 }
2322
2323 return nullptr;
2324}
2325
2326/// Try hard to fold icmp with zero RHS because this is a common case.
2327static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2328 Value *RHS, const Query &Q) {
2329 if (!match(RHS, m_Zero()))
2330 return nullptr;
2331
2332 Type *ITy = GetCompareTy(LHS); // The return type.
2333 bool LHSKnownNonNegative, LHSKnownNegative;
2334 switch (Pred) {
2335 default:
2336 llvm_unreachable("Unknown ICmp predicate!");
2337 case ICmpInst::ICMP_ULT:
2338 return getFalse(ITy);
2339 case ICmpInst::ICMP_UGE:
2340 return getTrue(ITy);
2341 case ICmpInst::ICMP_EQ:
2342 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002343 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002344 return getFalse(ITy);
2345 break;
2346 case ICmpInst::ICMP_NE:
2347 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002348 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002349 return getTrue(ITy);
2350 break;
2351 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002352 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2353 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002354 if (LHSKnownNegative)
2355 return getTrue(ITy);
2356 if (LHSKnownNonNegative)
2357 return getFalse(ITy);
2358 break;
2359 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002360 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2361 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002362 if (LHSKnownNegative)
2363 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002364 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002365 return getFalse(ITy);
2366 break;
2367 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002368 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2369 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002370 if (LHSKnownNegative)
2371 return getFalse(ITy);
2372 if (LHSKnownNonNegative)
2373 return getTrue(ITy);
2374 break;
2375 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002376 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2377 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002378 if (LHSKnownNegative)
2379 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002380 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002381 return getTrue(ITy);
2382 break;
2383 }
2384
2385 return nullptr;
2386}
2387
Sanjay Patelbe332132017-01-23 18:22:26 +00002388/// Many binary operators with a constant operand have an easy-to-compute
2389/// range of outputs. This can be used to fold a comparison to always true or
2390/// always false.
2391static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2392 unsigned Width = Lower.getBitWidth();
2393 const APInt *C;
2394 switch (BO.getOpcode()) {
2395 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002396 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2397 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2398 if (BO.hasNoUnsignedWrap()) {
2399 // 'add nuw x, C' produces [C, UINT_MAX].
2400 Lower = *C;
2401 } else if (BO.hasNoSignedWrap()) {
2402 if (C->isNegative()) {
2403 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2404 Lower = APInt::getSignedMinValue(Width);
2405 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2406 } else {
2407 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2408 Lower = APInt::getSignedMinValue(Width) + *C;
2409 Upper = APInt::getSignedMaxValue(Width) + 1;
2410 }
2411 }
2412 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002413 break;
2414
2415 case Instruction::And:
2416 if (match(BO.getOperand(1), m_APInt(C)))
2417 // 'and x, C' produces [0, C].
2418 Upper = *C + 1;
2419 break;
2420
2421 case Instruction::Or:
2422 if (match(BO.getOperand(1), m_APInt(C)))
2423 // 'or x, C' produces [C, UINT_MAX].
2424 Lower = *C;
2425 break;
2426
2427 case Instruction::AShr:
2428 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2429 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2430 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2431 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2432 } else if (match(BO.getOperand(0), m_APInt(C))) {
2433 unsigned ShiftAmount = Width - 1;
2434 if (*C != 0 && BO.isExact())
2435 ShiftAmount = C->countTrailingZeros();
2436 if (C->isNegative()) {
2437 // 'ashr C, x' produces [C, C >> (Width-1)]
2438 Lower = *C;
2439 Upper = C->ashr(ShiftAmount) + 1;
2440 } else {
2441 // 'ashr C, x' produces [C >> (Width-1), C]
2442 Lower = C->ashr(ShiftAmount);
2443 Upper = *C + 1;
2444 }
2445 }
2446 break;
2447
2448 case Instruction::LShr:
2449 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2450 // 'lshr x, C' produces [0, UINT_MAX >> C].
2451 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2452 } else if (match(BO.getOperand(0), m_APInt(C))) {
2453 // 'lshr C, x' produces [C >> (Width-1), C].
2454 unsigned ShiftAmount = Width - 1;
2455 if (*C != 0 && BO.isExact())
2456 ShiftAmount = C->countTrailingZeros();
2457 Lower = C->lshr(ShiftAmount);
2458 Upper = *C + 1;
2459 }
2460 break;
2461
2462 case Instruction::Shl:
2463 if (match(BO.getOperand(0), m_APInt(C))) {
2464 if (BO.hasNoUnsignedWrap()) {
2465 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2466 Lower = *C;
2467 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2468 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2469 if (C->isNegative()) {
2470 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2471 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2472 Lower = C->shl(ShiftAmount);
2473 Upper = *C + 1;
2474 } else {
2475 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2476 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2477 Lower = *C;
2478 Upper = C->shl(ShiftAmount) + 1;
2479 }
2480 }
2481 }
2482 break;
2483
2484 case Instruction::SDiv:
2485 if (match(BO.getOperand(1), m_APInt(C))) {
2486 APInt IntMin = APInt::getSignedMinValue(Width);
2487 APInt IntMax = APInt::getSignedMaxValue(Width);
2488 if (C->isAllOnesValue()) {
2489 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2490 // where C != -1 and C != 0 and C != 1
2491 Lower = IntMin + 1;
2492 Upper = IntMax + 1;
2493 } else if (C->countLeadingZeros() < Width - 1) {
2494 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2495 // where C != -1 and C != 0 and C != 1
2496 Lower = IntMin.sdiv(*C);
2497 Upper = IntMax.sdiv(*C);
2498 if (Lower.sgt(Upper))
2499 std::swap(Lower, Upper);
2500 Upper = Upper + 1;
2501 assert(Upper != Lower && "Upper part of range has wrapped!");
2502 }
2503 } else if (match(BO.getOperand(0), m_APInt(C))) {
2504 if (C->isMinSignedValue()) {
2505 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2506 Lower = *C;
2507 Upper = Lower.lshr(1) + 1;
2508 } else {
2509 // 'sdiv C, x' produces [-|C|, |C|].
2510 Upper = C->abs() + 1;
2511 Lower = (-Upper) + 1;
2512 }
2513 }
2514 break;
2515
2516 case Instruction::UDiv:
2517 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2518 // 'udiv x, C' produces [0, UINT_MAX / C].
2519 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2520 } else if (match(BO.getOperand(0), m_APInt(C))) {
2521 // 'udiv C, x' produces [0, C].
2522 Upper = *C + 1;
2523 }
2524 break;
2525
2526 case Instruction::SRem:
2527 if (match(BO.getOperand(1), m_APInt(C))) {
2528 // 'srem x, C' produces (-|C|, |C|).
2529 Upper = C->abs();
2530 Lower = (-Upper) + 1;
2531 }
2532 break;
2533
2534 case Instruction::URem:
2535 if (match(BO.getOperand(1), m_APInt(C)))
2536 // 'urem x, C' produces [0, C).
2537 Upper = *C;
2538 break;
2539
2540 default:
2541 break;
2542 }
2543}
2544
Sanjay Patel67bde282016-08-22 23:12:02 +00002545static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2546 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002547 const APInt *C;
2548 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002549 return nullptr;
2550
2551 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002552 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002553 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002554 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002555 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002556 return ConstantInt::getTrue(GetCompareTy(RHS));
2557
Sanjay Patelbe332132017-01-23 18:22:26 +00002558 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002559 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002560 APInt Lower = APInt(Width, 0);
2561 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002562 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2563 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002564
2565 ConstantRange LHS_CR =
2566 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2567
2568 if (auto *I = dyn_cast<Instruction>(LHS))
2569 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2570 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2571
2572 if (!LHS_CR.isFullSet()) {
2573 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002574 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002575 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002576 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002577 }
2578
2579 return nullptr;
2580}
2581
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002582static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2583 Value *RHS, const Query &Q,
2584 unsigned MaxRecurse) {
2585 Type *ITy = GetCompareTy(LHS); // The return type.
2586
2587 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2588 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2589 if (MaxRecurse && (LBO || RBO)) {
2590 // Analyze the case when either LHS or RHS is an add instruction.
2591 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2592 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2593 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2594 if (LBO && LBO->getOpcode() == Instruction::Add) {
2595 A = LBO->getOperand(0);
2596 B = LBO->getOperand(1);
2597 NoLHSWrapProblem =
2598 ICmpInst::isEquality(Pred) ||
2599 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2600 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2601 }
2602 if (RBO && RBO->getOpcode() == Instruction::Add) {
2603 C = RBO->getOperand(0);
2604 D = RBO->getOperand(1);
2605 NoRHSWrapProblem =
2606 ICmpInst::isEquality(Pred) ||
2607 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2608 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2609 }
2610
2611 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2612 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2613 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2614 Constant::getNullValue(RHS->getType()), Q,
2615 MaxRecurse - 1))
2616 return V;
2617
2618 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2619 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2620 if (Value *V =
2621 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2622 C == LHS ? D : C, Q, MaxRecurse - 1))
2623 return V;
2624
2625 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2626 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2627 NoRHSWrapProblem) {
2628 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2629 Value *Y, *Z;
2630 if (A == C) {
2631 // C + B == C + D -> B == D
2632 Y = B;
2633 Z = D;
2634 } else if (A == D) {
2635 // D + B == C + D -> B == C
2636 Y = B;
2637 Z = C;
2638 } else if (B == C) {
2639 // A + C == C + D -> A == D
2640 Y = A;
2641 Z = D;
2642 } else {
2643 assert(B == D);
2644 // A + D == C + D -> A == C
2645 Y = A;
2646 Z = C;
2647 }
2648 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2649 return V;
2650 }
2651 }
2652
2653 {
2654 Value *Y = nullptr;
2655 // icmp pred (or X, Y), X
2656 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2657 if (Pred == ICmpInst::ICMP_ULT)
2658 return getFalse(ITy);
2659 if (Pred == ICmpInst::ICMP_UGE)
2660 return getTrue(ITy);
2661
2662 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2663 bool RHSKnownNonNegative, RHSKnownNegative;
2664 bool YKnownNonNegative, YKnownNegative;
2665 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002666 Q.AC, Q.CxtI, Q.DT);
2667 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002668 Q.CxtI, Q.DT);
2669 if (RHSKnownNonNegative && YKnownNegative)
2670 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2671 if (RHSKnownNegative || YKnownNonNegative)
2672 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2673 }
2674 }
2675 // icmp pred X, (or X, Y)
2676 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2677 if (Pred == ICmpInst::ICMP_ULE)
2678 return getTrue(ITy);
2679 if (Pred == ICmpInst::ICMP_UGT)
2680 return getFalse(ITy);
2681
2682 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2683 bool LHSKnownNonNegative, LHSKnownNegative;
2684 bool YKnownNonNegative, YKnownNegative;
2685 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002686 Q.AC, Q.CxtI, Q.DT);
2687 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002688 Q.CxtI, Q.DT);
2689 if (LHSKnownNonNegative && YKnownNegative)
2690 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2691 if (LHSKnownNegative || YKnownNonNegative)
2692 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2693 }
2694 }
2695 }
2696
2697 // icmp pred (and X, Y), X
2698 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2699 m_And(m_Specific(RHS), m_Value())))) {
2700 if (Pred == ICmpInst::ICMP_UGT)
2701 return getFalse(ITy);
2702 if (Pred == ICmpInst::ICMP_ULE)
2703 return getTrue(ITy);
2704 }
2705 // icmp pred X, (and X, Y)
2706 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2707 m_And(m_Specific(LHS), m_Value())))) {
2708 if (Pred == ICmpInst::ICMP_UGE)
2709 return getTrue(ITy);
2710 if (Pred == ICmpInst::ICMP_ULT)
2711 return getFalse(ITy);
2712 }
2713
2714 // 0 - (zext X) pred C
2715 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2716 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2717 if (RHSC->getValue().isStrictlyPositive()) {
2718 if (Pred == ICmpInst::ICMP_SLT)
2719 return ConstantInt::getTrue(RHSC->getContext());
2720 if (Pred == ICmpInst::ICMP_SGE)
2721 return ConstantInt::getFalse(RHSC->getContext());
2722 if (Pred == ICmpInst::ICMP_EQ)
2723 return ConstantInt::getFalse(RHSC->getContext());
2724 if (Pred == ICmpInst::ICMP_NE)
2725 return ConstantInt::getTrue(RHSC->getContext());
2726 }
2727 if (RHSC->getValue().isNonNegative()) {
2728 if (Pred == ICmpInst::ICMP_SLE)
2729 return ConstantInt::getTrue(RHSC->getContext());
2730 if (Pred == ICmpInst::ICMP_SGT)
2731 return ConstantInt::getFalse(RHSC->getContext());
2732 }
2733 }
2734 }
2735
2736 // icmp pred (urem X, Y), Y
2737 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2738 bool KnownNonNegative, KnownNegative;
2739 switch (Pred) {
2740 default:
2741 break;
2742 case ICmpInst::ICMP_SGT:
2743 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002744 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2745 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002746 if (!KnownNonNegative)
2747 break;
2748 LLVM_FALLTHROUGH;
2749 case ICmpInst::ICMP_EQ:
2750 case ICmpInst::ICMP_UGT:
2751 case ICmpInst::ICMP_UGE:
2752 return getFalse(ITy);
2753 case ICmpInst::ICMP_SLT:
2754 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002755 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2756 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002757 if (!KnownNonNegative)
2758 break;
2759 LLVM_FALLTHROUGH;
2760 case ICmpInst::ICMP_NE:
2761 case ICmpInst::ICMP_ULT:
2762 case ICmpInst::ICMP_ULE:
2763 return getTrue(ITy);
2764 }
2765 }
2766
2767 // icmp pred X, (urem Y, X)
2768 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2769 bool KnownNonNegative, KnownNegative;
2770 switch (Pred) {
2771 default:
2772 break;
2773 case ICmpInst::ICMP_SGT:
2774 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002775 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2776 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002777 if (!KnownNonNegative)
2778 break;
2779 LLVM_FALLTHROUGH;
2780 case ICmpInst::ICMP_NE:
2781 case ICmpInst::ICMP_UGT:
2782 case ICmpInst::ICMP_UGE:
2783 return getTrue(ITy);
2784 case ICmpInst::ICMP_SLT:
2785 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002786 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2787 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002788 if (!KnownNonNegative)
2789 break;
2790 LLVM_FALLTHROUGH;
2791 case ICmpInst::ICMP_EQ:
2792 case ICmpInst::ICMP_ULT:
2793 case ICmpInst::ICMP_ULE:
2794 return getFalse(ITy);
2795 }
2796 }
2797
2798 // x >> y <=u x
2799 // x udiv y <=u x.
2800 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2801 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2802 // icmp pred (X op Y), X
2803 if (Pred == ICmpInst::ICMP_UGT)
2804 return getFalse(ITy);
2805 if (Pred == ICmpInst::ICMP_ULE)
2806 return getTrue(ITy);
2807 }
2808
2809 // x >=u x >> y
2810 // x >=u x udiv y.
2811 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2812 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2813 // icmp pred X, (X op Y)
2814 if (Pred == ICmpInst::ICMP_ULT)
2815 return getFalse(ITy);
2816 if (Pred == ICmpInst::ICMP_UGE)
2817 return getTrue(ITy);
2818 }
2819
2820 // handle:
2821 // CI2 << X == CI
2822 // CI2 << X != CI
2823 //
2824 // where CI2 is a power of 2 and CI isn't
2825 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2826 const APInt *CI2Val, *CIVal = &CI->getValue();
2827 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2828 CI2Val->isPowerOf2()) {
2829 if (!CIVal->isPowerOf2()) {
2830 // CI2 << X can equal zero in some circumstances,
2831 // this simplification is unsafe if CI is zero.
2832 //
2833 // We know it is safe if:
2834 // - The shift is nsw, we can't shift out the one bit.
2835 // - The shift is nuw, we can't shift out the one bit.
2836 // - CI2 is one
2837 // - CI isn't zero
2838 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2839 *CI2Val == 1 || !CI->isZero()) {
2840 if (Pred == ICmpInst::ICMP_EQ)
2841 return ConstantInt::getFalse(RHS->getContext());
2842 if (Pred == ICmpInst::ICMP_NE)
2843 return ConstantInt::getTrue(RHS->getContext());
2844 }
2845 }
2846 if (CIVal->isSignBit() && *CI2Val == 1) {
2847 if (Pred == ICmpInst::ICMP_UGT)
2848 return ConstantInt::getFalse(RHS->getContext());
2849 if (Pred == ICmpInst::ICMP_ULE)
2850 return ConstantInt::getTrue(RHS->getContext());
2851 }
2852 }
2853 }
2854
2855 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2856 LBO->getOperand(1) == RBO->getOperand(1)) {
2857 switch (LBO->getOpcode()) {
2858 default:
2859 break;
2860 case Instruction::UDiv:
2861 case Instruction::LShr:
2862 if (ICmpInst::isSigned(Pred))
2863 break;
2864 LLVM_FALLTHROUGH;
2865 case Instruction::SDiv:
2866 case Instruction::AShr:
2867 if (!LBO->isExact() || !RBO->isExact())
2868 break;
2869 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2870 RBO->getOperand(0), Q, MaxRecurse - 1))
2871 return V;
2872 break;
2873 case Instruction::Shl: {
2874 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2875 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2876 if (!NUW && !NSW)
2877 break;
2878 if (!NSW && ICmpInst::isSigned(Pred))
2879 break;
2880 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2881 RBO->getOperand(0), Q, MaxRecurse - 1))
2882 return V;
2883 break;
2884 }
2885 }
2886 }
2887 return nullptr;
2888}
2889
Sanjay Patel35289c62016-12-10 17:40:47 +00002890/// Simplify integer comparisons where at least one operand of the compare
2891/// matches an integer min/max idiom.
2892static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2893 Value *RHS, const Query &Q,
2894 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002895 Type *ITy = GetCompareTy(LHS); // The return type.
2896 Value *A, *B;
2897 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2898 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2899
2900 // Signed variants on "max(a,b)>=a -> true".
2901 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2902 if (A != RHS)
2903 std::swap(A, B); // smax(A, B) pred A.
2904 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2905 // We analyze this as smax(A, B) pred A.
2906 P = Pred;
2907 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2908 (A == LHS || B == LHS)) {
2909 if (A != LHS)
2910 std::swap(A, B); // A pred smax(A, B).
2911 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2912 // We analyze this as smax(A, B) swapped-pred A.
2913 P = CmpInst::getSwappedPredicate(Pred);
2914 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2915 (A == RHS || B == RHS)) {
2916 if (A != RHS)
2917 std::swap(A, B); // smin(A, B) pred A.
2918 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2919 // We analyze this as smax(-A, -B) swapped-pred -A.
2920 // Note that we do not need to actually form -A or -B thanks to EqP.
2921 P = CmpInst::getSwappedPredicate(Pred);
2922 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2923 (A == LHS || B == LHS)) {
2924 if (A != LHS)
2925 std::swap(A, B); // A pred smin(A, B).
2926 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2927 // We analyze this as smax(-A, -B) pred -A.
2928 // Note that we do not need to actually form -A or -B thanks to EqP.
2929 P = Pred;
2930 }
2931 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2932 // Cases correspond to "max(A, B) p A".
2933 switch (P) {
2934 default:
2935 break;
2936 case CmpInst::ICMP_EQ:
2937 case CmpInst::ICMP_SLE:
2938 // Equivalent to "A EqP B". This may be the same as the condition tested
2939 // in the max/min; if so, we can just return that.
2940 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2941 return V;
2942 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2943 return V;
2944 // Otherwise, see if "A EqP B" simplifies.
2945 if (MaxRecurse)
2946 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2947 return V;
2948 break;
2949 case CmpInst::ICMP_NE:
2950 case CmpInst::ICMP_SGT: {
2951 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2952 // Equivalent to "A InvEqP B". This may be the same as the condition
2953 // tested in the max/min; if so, we can just return that.
2954 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2955 return V;
2956 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2957 return V;
2958 // Otherwise, see if "A InvEqP B" simplifies.
2959 if (MaxRecurse)
2960 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2961 return V;
2962 break;
2963 }
2964 case CmpInst::ICMP_SGE:
2965 // Always true.
2966 return getTrue(ITy);
2967 case CmpInst::ICMP_SLT:
2968 // Always false.
2969 return getFalse(ITy);
2970 }
2971 }
2972
2973 // Unsigned variants on "max(a,b)>=a -> true".
2974 P = CmpInst::BAD_ICMP_PREDICATE;
2975 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2976 if (A != RHS)
2977 std::swap(A, B); // umax(A, B) pred A.
2978 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2979 // We analyze this as umax(A, B) pred A.
2980 P = Pred;
2981 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2982 (A == LHS || B == LHS)) {
2983 if (A != LHS)
2984 std::swap(A, B); // A pred umax(A, B).
2985 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2986 // We analyze this as umax(A, B) swapped-pred A.
2987 P = CmpInst::getSwappedPredicate(Pred);
2988 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2989 (A == RHS || B == RHS)) {
2990 if (A != RHS)
2991 std::swap(A, B); // umin(A, B) pred A.
2992 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2993 // We analyze this as umax(-A, -B) swapped-pred -A.
2994 // Note that we do not need to actually form -A or -B thanks to EqP.
2995 P = CmpInst::getSwappedPredicate(Pred);
2996 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2997 (A == LHS || B == LHS)) {
2998 if (A != LHS)
2999 std::swap(A, B); // A pred umin(A, B).
3000 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3001 // We analyze this as umax(-A, -B) pred -A.
3002 // Note that we do not need to actually form -A or -B thanks to EqP.
3003 P = Pred;
3004 }
3005 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3006 // Cases correspond to "max(A, B) p A".
3007 switch (P) {
3008 default:
3009 break;
3010 case CmpInst::ICMP_EQ:
3011 case CmpInst::ICMP_ULE:
3012 // Equivalent to "A EqP B". This may be the same as the condition tested
3013 // in the max/min; if so, we can just return that.
3014 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3015 return V;
3016 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3017 return V;
3018 // Otherwise, see if "A EqP B" simplifies.
3019 if (MaxRecurse)
3020 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3021 return V;
3022 break;
3023 case CmpInst::ICMP_NE:
3024 case CmpInst::ICMP_UGT: {
3025 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3026 // Equivalent to "A InvEqP B". This may be the same as the condition
3027 // tested in the max/min; if so, we can just return that.
3028 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3029 return V;
3030 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3031 return V;
3032 // Otherwise, see if "A InvEqP B" simplifies.
3033 if (MaxRecurse)
3034 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3035 return V;
3036 break;
3037 }
3038 case CmpInst::ICMP_UGE:
3039 // Always true.
3040 return getTrue(ITy);
3041 case CmpInst::ICMP_ULT:
3042 // Always false.
3043 return getFalse(ITy);
3044 }
3045 }
3046
3047 // Variants on "max(x,y) >= min(x,z)".
3048 Value *C, *D;
3049 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3050 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3051 (A == C || A == D || B == C || B == D)) {
3052 // max(x, ?) pred min(x, ?).
3053 if (Pred == CmpInst::ICMP_SGE)
3054 // Always true.
3055 return getTrue(ITy);
3056 if (Pred == CmpInst::ICMP_SLT)
3057 // Always false.
3058 return getFalse(ITy);
3059 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3060 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3061 (A == C || A == D || B == C || B == D)) {
3062 // min(x, ?) pred max(x, ?).
3063 if (Pred == CmpInst::ICMP_SLE)
3064 // Always true.
3065 return getTrue(ITy);
3066 if (Pred == CmpInst::ICMP_SGT)
3067 // Always false.
3068 return getFalse(ITy);
3069 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3070 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3071 (A == C || A == D || B == C || B == D)) {
3072 // max(x, ?) pred min(x, ?).
3073 if (Pred == CmpInst::ICMP_UGE)
3074 // Always true.
3075 return getTrue(ITy);
3076 if (Pred == CmpInst::ICMP_ULT)
3077 // Always false.
3078 return getFalse(ITy);
3079 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3080 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3081 (A == C || A == D || B == C || B == D)) {
3082 // min(x, ?) pred max(x, ?).
3083 if (Pred == CmpInst::ICMP_ULE)
3084 // Always true.
3085 return getTrue(ITy);
3086 if (Pred == CmpInst::ICMP_UGT)
3087 // Always false.
3088 return getFalse(ITy);
3089 }
3090
3091 return nullptr;
3092}
3093
Sanjay Patel472cc782016-01-11 22:14:42 +00003094/// Given operands for an ICmpInst, see if we can fold the result.
3095/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003096static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003097 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003098 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003099 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003100
Chris Lattnera71e9d62009-11-10 00:55:12 +00003101 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003102 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003103 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003104
3105 // If we have a constant, make sure it is on the RHS.
3106 std::swap(LHS, RHS);
3107 Pred = CmpInst::getSwappedPredicate(Pred);
3108 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003109
Chris Lattner229907c2011-07-18 04:54:35 +00003110 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003111
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003112 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003113 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3114 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003115 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003116 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003117
Sanjay Pateldc65a272016-12-03 17:30:22 +00003118 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3119 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003120
Sanjay Pateldc65a272016-12-03 17:30:22 +00003121 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3122 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003123
Sanjay Patel67bde282016-08-22 23:12:02 +00003124 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3125 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003126
Chen Li7452d952015-09-26 03:26:47 +00003127 // If both operands have range metadata, use the metadata
3128 // to simplify the comparison.
3129 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3130 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3131 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3132
3133 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3134 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003135 auto RHS_CR = getConstantRangeFromMetadata(
3136 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3137 auto LHS_CR = getConstantRangeFromMetadata(
3138 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003139
3140 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3141 if (Satisfied_CR.contains(LHS_CR))
3142 return ConstantInt::getTrue(RHS->getContext());
3143
3144 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3145 CmpInst::getInversePredicate(Pred), RHS_CR);
3146 if (InversedSatisfied_CR.contains(LHS_CR))
3147 return ConstantInt::getFalse(RHS->getContext());
3148 }
3149 }
3150
Duncan Sands8fb2c382011-01-20 13:21:55 +00003151 // Compare of cast, for example (zext X) != 0 -> X != 0
3152 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3153 Instruction *LI = cast<CastInst>(LHS);
3154 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003155 Type *SrcTy = SrcOp->getType();
3156 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003157
3158 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3159 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003160 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3161 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003162 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3163 // Transfer the cast to the constant.
3164 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3165 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003166 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003167 return V;
3168 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3169 if (RI->getOperand(0)->getType() == SrcTy)
3170 // Compare without the cast.
3171 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003172 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003173 return V;
3174 }
3175 }
3176
3177 if (isa<ZExtInst>(LHS)) {
3178 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3179 // same type.
3180 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3181 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3182 // Compare X and Y. Note that signed predicates become unsigned.
3183 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003184 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003185 MaxRecurse-1))
3186 return V;
3187 }
3188 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3189 // too. If not, then try to deduce the result of the comparison.
3190 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3191 // Compute the constant that would happen if we truncated to SrcTy then
3192 // reextended to DstTy.
3193 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3194 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3195
3196 // If the re-extended constant didn't change then this is effectively
3197 // also a case of comparing two zero-extended values.
3198 if (RExt == CI && MaxRecurse)
3199 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003200 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003201 return V;
3202
3203 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3204 // there. Use this to work out the result of the comparison.
3205 if (RExt != CI) {
3206 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003207 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003208 // LHS <u RHS.
3209 case ICmpInst::ICMP_EQ:
3210 case ICmpInst::ICMP_UGT:
3211 case ICmpInst::ICMP_UGE:
3212 return ConstantInt::getFalse(CI->getContext());
3213
3214 case ICmpInst::ICMP_NE:
3215 case ICmpInst::ICMP_ULT:
3216 case ICmpInst::ICMP_ULE:
3217 return ConstantInt::getTrue(CI->getContext());
3218
3219 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3220 // is non-negative then LHS <s RHS.
3221 case ICmpInst::ICMP_SGT:
3222 case ICmpInst::ICMP_SGE:
3223 return CI->getValue().isNegative() ?
3224 ConstantInt::getTrue(CI->getContext()) :
3225 ConstantInt::getFalse(CI->getContext());
3226
3227 case ICmpInst::ICMP_SLT:
3228 case ICmpInst::ICMP_SLE:
3229 return CI->getValue().isNegative() ?
3230 ConstantInt::getFalse(CI->getContext()) :
3231 ConstantInt::getTrue(CI->getContext());
3232 }
3233 }
3234 }
3235 }
3236
3237 if (isa<SExtInst>(LHS)) {
3238 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3239 // same type.
3240 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3241 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3242 // Compare X and Y. Note that the predicate does not change.
3243 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003244 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003245 return V;
3246 }
3247 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3248 // too. If not, then try to deduce the result of the comparison.
3249 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3250 // Compute the constant that would happen if we truncated to SrcTy then
3251 // reextended to DstTy.
3252 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3253 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3254
3255 // If the re-extended constant didn't change then this is effectively
3256 // also a case of comparing two sign-extended values.
3257 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003258 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003259 return V;
3260
3261 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3262 // bits there. Use this to work out the result of the comparison.
3263 if (RExt != CI) {
3264 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003265 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003266 case ICmpInst::ICMP_EQ:
3267 return ConstantInt::getFalse(CI->getContext());
3268 case ICmpInst::ICMP_NE:
3269 return ConstantInt::getTrue(CI->getContext());
3270
3271 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3272 // LHS >s RHS.
3273 case ICmpInst::ICMP_SGT:
3274 case ICmpInst::ICMP_SGE:
3275 return CI->getValue().isNegative() ?
3276 ConstantInt::getTrue(CI->getContext()) :
3277 ConstantInt::getFalse(CI->getContext());
3278 case ICmpInst::ICMP_SLT:
3279 case ICmpInst::ICMP_SLE:
3280 return CI->getValue().isNegative() ?
3281 ConstantInt::getFalse(CI->getContext()) :
3282 ConstantInt::getTrue(CI->getContext());
3283
3284 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3285 // LHS >u RHS.
3286 case ICmpInst::ICMP_UGT:
3287 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003288 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003289 if (MaxRecurse)
3290 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3291 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003292 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003293 return V;
3294 break;
3295 case ICmpInst::ICMP_ULT:
3296 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003297 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003298 if (MaxRecurse)
3299 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3300 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003301 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003302 return V;
3303 break;
3304 }
3305 }
3306 }
3307 }
3308 }
3309
James Molloy1d88d6f2015-10-22 13:18:42 +00003310 // icmp eq|ne X, Y -> false|true if X != Y
3311 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003312 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003313 LLVMContext &Ctx = LHS->getType()->getContext();
3314 return Pred == ICmpInst::ICMP_NE ?
3315 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3316 }
Junmo Park53470fc2016-04-05 21:14:31 +00003317
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003318 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3319 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003320
Sanjay Patel35289c62016-12-10 17:40:47 +00003321 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003322 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003323
Chandler Carruth8059c842012-03-25 21:28:14 +00003324 // Simplify comparisons of related pointers using a powerful, recursive
3325 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003326 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003327 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003328 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003329 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3330 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3331 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3332 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3333 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3334 Q.DL.getTypeSizeInBits(CRHS->getType()))
3335 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3336 CLHS->getPointerOperand(),
3337 CRHS->getPointerOperand()))
3338 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003339
Nick Lewycky3db143e2012-02-26 02:09:49 +00003340 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3341 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3342 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3343 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3344 (ICmpInst::isEquality(Pred) ||
3345 (GLHS->isInBounds() && GRHS->isInBounds() &&
3346 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3347 // The bases are equal and the indices are constant. Build a constant
3348 // expression GEP with the same indices and a null base pointer to see
3349 // what constant folding can make out of it.
3350 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3351 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003352 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3353 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003354
3355 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003356 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3357 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003358 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3359 }
3360 }
3361 }
3362
David Majnemer5854e9f2014-11-16 02:20:08 +00003363 // If a bit is known to be zero for A and known to be one for B,
3364 // then A and B cannot be equal.
3365 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003366 const APInt *RHSVal;
3367 if (match(RHS, m_APInt(RHSVal))) {
3368 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003369 APInt LHSKnownZero(BitWidth, 0);
3370 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003371 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003372 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003373 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3374 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3375 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003376 }
3377 }
3378
Duncan Sandsf532d312010-11-07 16:12:23 +00003379 // If the comparison is with the result of a select instruction, check whether
3380 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003381 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003382 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003383 return V;
3384
3385 // If the comparison is with the result of a phi instruction, check whether
3386 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003387 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003388 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003389 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003390
Craig Topper9f008862014-04-15 04:59:12 +00003391 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003392}
3393
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003394Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003395 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003396 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003397 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003398 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003399 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003400 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003401}
3402
Sanjay Patel472cc782016-01-11 22:14:42 +00003403/// Given operands for an FCmpInst, see if we can fold the result.
3404/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003405static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003406 FastMathFlags FMF, const Query &Q,
3407 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003408 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3409 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3410
Chris Lattnera71e9d62009-11-10 00:55:12 +00003411 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003412 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003413 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003414
Chris Lattnera71e9d62009-11-10 00:55:12 +00003415 // If we have a constant, make sure it is on the RHS.
3416 std::swap(LHS, RHS);
3417 Pred = CmpInst::getSwappedPredicate(Pred);
3418 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003419
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003420 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003421 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003422 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003423 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003424 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003425 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003426
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003427 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3428 if (FMF.noNaNs()) {
3429 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003430 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003431 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003432 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003433 }
3434
Mehdi Aminieb242a52015-03-09 03:20:25 +00003435 // fcmp pred x, undef and fcmp pred undef, x
3436 // fold to true if unordered, false if ordered
3437 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3438 // Choosing NaN for the undef will always make unordered comparison succeed
3439 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003440 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003441 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003442
3443 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003444 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003445 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003446 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003447 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003448 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003449 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003450
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003451 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003452 const ConstantFP *CFP = nullptr;
3453 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3454 if (RHS->getType()->isVectorTy())
3455 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3456 else
3457 CFP = dyn_cast<ConstantFP>(RHSC);
3458 }
3459 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003460 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003461 if (CFP->getValueAPF().isNaN()) {
3462 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003463 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003464 assert(FCmpInst::isUnordered(Pred) &&
3465 "Comparison must be either ordered or unordered!");
3466 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003467 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003468 }
3469 // Check whether the constant is an infinity.
3470 if (CFP->getValueAPF().isInfinity()) {
3471 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003472 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003473 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003474 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003475 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003476 case FCmpInst::FCMP_UGE:
3477 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003478 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003479 default:
3480 break;
3481 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003482 } else {
3483 switch (Pred) {
3484 case FCmpInst::FCMP_OGT:
3485 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003486 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003487 case FCmpInst::FCMP_ULE:
3488 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003489 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003490 default:
3491 break;
3492 }
3493 }
3494 }
3495 if (CFP->getValueAPF().isZero()) {
3496 switch (Pred) {
3497 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003498 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003499 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003500 break;
3501 case FCmpInst::FCMP_OLT:
3502 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003503 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003504 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003505 break;
3506 default:
3507 break;
3508 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003509 }
3510 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003511
Duncan Sandsa620bd12010-11-07 16:46:25 +00003512 // If the comparison is with the result of a select instruction, check whether
3513 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003514 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003515 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003516 return V;
3517
3518 // If the comparison is with the result of a phi instruction, check whether
3519 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003520 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003521 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003522 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003523
Craig Topper9f008862014-04-15 04:59:12 +00003524 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003525}
3526
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003527Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003528 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003529 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003530 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003531 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003532 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003533 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003534}
3535
Sanjay Patel472cc782016-01-11 22:14:42 +00003536/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003537static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3538 const Query &Q,
3539 unsigned MaxRecurse) {
3540 // Trivial replacement.
3541 if (V == Op)
3542 return RepOp;
3543
3544 auto *I = dyn_cast<Instruction>(V);
3545 if (!I)
3546 return nullptr;
3547
3548 // If this is a binary operator, try to simplify it with the replaced op.
3549 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3550 // Consider:
3551 // %cmp = icmp eq i32 %x, 2147483647
3552 // %add = add nsw i32 %x, 1
3553 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3554 //
3555 // We can't replace %sel with %add unless we strip away the flags.
3556 if (isa<OverflowingBinaryOperator>(B))
3557 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3558 return nullptr;
3559 if (isa<PossiblyExactOperator>(B))
3560 if (B->isExact())
3561 return nullptr;
3562
3563 if (MaxRecurse) {
3564 if (B->getOperand(0) == Op)
3565 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3566 MaxRecurse - 1);
3567 if (B->getOperand(1) == Op)
3568 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3569 MaxRecurse - 1);
3570 }
3571 }
3572
3573 // Same for CmpInsts.
3574 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3575 if (MaxRecurse) {
3576 if (C->getOperand(0) == Op)
3577 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3578 MaxRecurse - 1);
3579 if (C->getOperand(1) == Op)
3580 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3581 MaxRecurse - 1);
3582 }
3583 }
3584
3585 // TODO: We could hand off more cases to instsimplify here.
3586
3587 // If all operands are constant after substituting Op for RepOp then we can
3588 // constant fold the instruction.
3589 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3590 // Build a list of all constant operands.
3591 SmallVector<Constant *, 8> ConstOps;
3592 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3593 if (I->getOperand(i) == Op)
3594 ConstOps.push_back(CRepOp);
3595 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3596 ConstOps.push_back(COp);
3597 else
3598 break;
3599 }
3600
3601 // All operands were constants, fold it.
3602 if (ConstOps.size() == I->getNumOperands()) {
3603 if (CmpInst *C = dyn_cast<CmpInst>(I))
3604 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3605 ConstOps[1], Q.DL, Q.TLI);
3606
3607 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3608 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003609 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003610
Manuel Jacobe9024592016-01-21 06:33:22 +00003611 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003612 }
3613 }
3614
3615 return nullptr;
3616}
3617
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003618/// Try to simplify a select instruction when its condition operand is an
3619/// integer comparison where one operand of the compare is a constant.
3620static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3621 const APInt *Y, bool TrueWhenUnset) {
3622 const APInt *C;
3623
3624 // (X & Y) == 0 ? X & ~Y : X --> X
3625 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3626 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3627 *Y == ~*C)
3628 return TrueWhenUnset ? FalseVal : TrueVal;
3629
3630 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3631 // (X & Y) != 0 ? X : X & ~Y --> X
3632 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3633 *Y == ~*C)
3634 return TrueWhenUnset ? FalseVal : TrueVal;
3635
3636 if (Y->isPowerOf2()) {
3637 // (X & Y) == 0 ? X | Y : X --> X | Y
3638 // (X & Y) != 0 ? X | Y : X --> X
3639 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3640 *Y == *C)
3641 return TrueWhenUnset ? TrueVal : FalseVal;
3642
3643 // (X & Y) == 0 ? X : X | Y --> X
3644 // (X & Y) != 0 ? X : X | Y --> X | Y
3645 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3646 *Y == *C)
3647 return TrueWhenUnset ? TrueVal : FalseVal;
3648 }
Matt Arsenault82606662017-01-11 00:57:54 +00003649
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003650 return nullptr;
3651}
3652
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003653/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3654/// eq/ne.
3655static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3656 Value *FalseVal,
3657 bool TrueWhenUnset) {
3658 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003659 if (!BitWidth)
3660 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003661
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003662 APInt MinSignedValue;
3663 Value *X;
3664 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3665 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3666 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3667 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3668 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3669 } else {
3670 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3671 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3672 X = CmpLHS;
3673 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3674 }
3675
3676 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3677 TrueWhenUnset))
3678 return V;
3679
3680 return nullptr;
3681}
3682
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003683/// Try to simplify a select instruction when its condition operand is an
3684/// integer comparison.
3685static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3686 Value *FalseVal, const Query &Q,
3687 unsigned MaxRecurse) {
3688 ICmpInst::Predicate Pred;
3689 Value *CmpLHS, *CmpRHS;
3690 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3691 return nullptr;
3692
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003693 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3694 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003695 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3696 Value *X;
3697 const APInt *Y;
3698 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3699 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3700 Pred == ICmpInst::ICMP_EQ))
3701 return V;
3702 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003703 // Comparing signed-less-than 0 checks if the sign bit is set.
3704 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3705 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003706 return V;
3707 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003708 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3709 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3710 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003711 return V;
3712 }
3713
3714 if (CondVal->hasOneUse()) {
3715 const APInt *C;
3716 if (match(CmpRHS, m_APInt(C))) {
3717 // X < MIN ? T : F --> F
3718 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3719 return FalseVal;
3720 // X < MIN ? T : F --> F
3721 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3722 return FalseVal;
3723 // X > MAX ? T : F --> F
3724 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3725 return FalseVal;
3726 // X > MAX ? T : F --> F
3727 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3728 return FalseVal;
3729 }
3730 }
3731
3732 // If we have an equality comparison, then we know the value in one of the
3733 // arms of the select. See if substituting this value into the arm and
3734 // simplifying the result yields the same value as the other arm.
3735 if (Pred == ICmpInst::ICMP_EQ) {
3736 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3737 TrueVal ||
3738 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3739 TrueVal)
3740 return FalseVal;
3741 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3742 FalseVal ||
3743 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3744 FalseVal)
3745 return FalseVal;
3746 } else if (Pred == ICmpInst::ICMP_NE) {
3747 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3748 FalseVal ||
3749 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3750 FalseVal)
3751 return TrueVal;
3752 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3753 TrueVal ||
3754 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3755 TrueVal)
3756 return TrueVal;
3757 }
3758
3759 return nullptr;
3760}
3761
Sanjay Patel472cc782016-01-11 22:14:42 +00003762/// Given operands for a SelectInst, see if we can fold the result.
3763/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003764static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3765 Value *FalseVal, const Query &Q,
3766 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003767 // select true, X, Y -> X
3768 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003769 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3770 if (CB->isAllOnesValue())
3771 return TrueVal;
3772 if (CB->isNullValue())
3773 return FalseVal;
3774 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003775
Chris Lattnerc707fa92010-04-20 05:32:14 +00003776 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003777 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003778 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003779
Chris Lattnerc707fa92010-04-20 05:32:14 +00003780 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3781 if (isa<Constant>(TrueVal))
3782 return TrueVal;
3783 return FalseVal;
3784 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003785 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3786 return FalseVal;
3787 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3788 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003789
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003790 if (Value *V =
3791 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3792 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003793
Craig Topper9f008862014-04-15 04:59:12 +00003794 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003795}
3796
Duncan Sandsb8cee002012-03-13 11:42:19 +00003797Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003798 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003799 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003800 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003801 const Instruction *CxtI) {
3802 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003803 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003804}
3805
Sanjay Patel472cc782016-01-11 22:14:42 +00003806/// Given operands for an GetElementPtrInst, see if we can fold the result.
3807/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003808static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3809 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003810 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003811 unsigned AS =
3812 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003813
Chris Lattner8574aba2009-11-27 00:29:05 +00003814 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003815 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003816 return Ops[0];
3817
Nico Weber48c82402014-08-27 20:06:19 +00003818 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003819 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003820 Type *GEPTy = PointerType::get(LastType, AS);
3821 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3822 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3823
3824 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003825 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003826
Jay Foadb992a632011-07-19 15:07:52 +00003827 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003828 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003829 if (match(Ops[1], m_Zero()))
3830 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003831
David Blaikie4a2e73b2015-04-02 18:55:32 +00003832 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003833 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003834 Value *P;
3835 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003837 // getelementptr P, N -> P if P points to a type of zero size.
3838 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003839 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003840
3841 // The following transforms are only safe if the ptrtoint cast
3842 // doesn't truncate the pointers.
3843 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003844 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003845 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3846 if (match(P, m_Zero()))
3847 return Constant::getNullValue(GEPTy);
3848 Value *Temp;
3849 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003850 if (Temp->getType() == GEPTy)
3851 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003852 return nullptr;
3853 };
3854
3855 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3856 if (TyAllocSize == 1 &&
3857 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3858 if (Value *R = PtrToIntOrZero(P))
3859 return R;
3860
3861 // getelementptr V, (ashr (sub P, V), C) -> Q
3862 // if P points to a type of size 1 << C.
3863 if (match(Ops[1],
3864 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3865 m_ConstantInt(C))) &&
3866 TyAllocSize == 1ULL << C)
3867 if (Value *R = PtrToIntOrZero(P))
3868 return R;
3869
3870 // getelementptr V, (sdiv (sub P, V), C) -> Q
3871 // if P points to a type of size C.
3872 if (match(Ops[1],
3873 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3874 m_SpecificInt(TyAllocSize))))
3875 if (Value *R = PtrToIntOrZero(P))
3876 return R;
3877 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003878 }
3879 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003880
David Majnemerd1501372016-08-07 07:58:12 +00003881 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3882 all_of(Ops.slice(1).drop_back(1),
3883 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3884 unsigned PtrWidth =
3885 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3886 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3887 APInt BasePtrOffset(PtrWidth, 0);
3888 Value *StrippedBasePtr =
3889 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3890 BasePtrOffset);
3891
David Majnemer5c5df622016-08-16 06:13:46 +00003892 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003893 if (match(Ops.back(),
3894 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3895 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3896 return ConstantExpr::getIntToPtr(CI, GEPTy);
3897 }
David Majnemer5c5df622016-08-16 06:13:46 +00003898 // gep (gep V, C), (xor V, -1) -> C-1
3899 if (match(Ops.back(),
3900 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3901 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3902 return ConstantExpr::getIntToPtr(CI, GEPTy);
3903 }
David Majnemerd1501372016-08-07 07:58:12 +00003904 }
3905 }
3906
Chris Lattner8574aba2009-11-27 00:29:05 +00003907 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003908 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003909 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003910 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003911
David Blaikie4a2e73b2015-04-02 18:55:32 +00003912 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3913 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003914}
3915
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003916Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3917 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003918 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003919 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003920 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003921 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003922 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003923}
3924
Sanjay Patel472cc782016-01-11 22:14:42 +00003925/// Given operands for an InsertValueInst, see if we can fold the result.
3926/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003927static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3928 ArrayRef<unsigned> Idxs, const Query &Q,
3929 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003930 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3931 if (Constant *CVal = dyn_cast<Constant>(Val))
3932 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3933
3934 // insertvalue x, undef, n -> x
3935 if (match(Val, m_Undef()))
3936 return Agg;
3937
3938 // insertvalue x, (extractvalue y, n), n
3939 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003940 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3941 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003942 // insertvalue undef, (extractvalue y, n), n -> y
3943 if (match(Agg, m_Undef()))
3944 return EV->getAggregateOperand();
3945
3946 // insertvalue y, (extractvalue y, n), n -> y
3947 if (Agg == EV->getAggregateOperand())
3948 return Agg;
3949 }
3950
Craig Topper9f008862014-04-15 04:59:12 +00003951 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003952}
3953
Chandler Carruth66b31302015-01-04 12:03:27 +00003954Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003955 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003956 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003957 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003958 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003959 RecursionLimit);
3960}
3961
Sanjay Patel472cc782016-01-11 22:14:42 +00003962/// Given operands for an ExtractValueInst, see if we can fold the result.
3963/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003964static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3965 const Query &, unsigned) {
3966 if (auto *CAgg = dyn_cast<Constant>(Agg))
3967 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3968
3969 // extractvalue x, (insertvalue y, elt, n), n -> elt
3970 unsigned NumIdxs = Idxs.size();
3971 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3972 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3973 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3974 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3975 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3976 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3977 Idxs.slice(0, NumCommonIdxs)) {
3978 if (NumIdxs == NumInsertValueIdxs)
3979 return IVI->getInsertedValueOperand();
3980 break;
3981 }
3982 }
3983
3984 return nullptr;
3985}
3986
3987Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3988 const DataLayout &DL,
3989 const TargetLibraryInfo *TLI,
3990 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003991 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003992 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003993 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003994 RecursionLimit);
3995}
3996
Sanjay Patel472cc782016-01-11 22:14:42 +00003997/// Given operands for an ExtractElementInst, see if we can fold the result.
3998/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003999static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
4000 unsigned) {
4001 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4002 if (auto *CIdx = dyn_cast<Constant>(Idx))
4003 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4004
4005 // The index is not relevant if our vector is a splat.
4006 if (auto *Splat = CVec->getSplatValue())
4007 return Splat;
4008
4009 if (isa<UndefValue>(Vec))
4010 return UndefValue::get(Vec->getType()->getVectorElementType());
4011 }
4012
4013 // If extracting a specified index from the vector, see if we can recursively
4014 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00004015 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
4016 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00004017 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00004018
4019 return nullptr;
4020}
4021
4022Value *llvm::SimplifyExtractElementInst(
4023 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004024 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4025 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004026 RecursionLimit);
4027}
4028
Sanjay Patel472cc782016-01-11 22:14:42 +00004029/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004030static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004031 // If all of the PHI's incoming values are the same then replace the PHI node
4032 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004033 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004034 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004035 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004036 // If the incoming value is the phi node itself, it can safely be skipped.
4037 if (Incoming == PN) continue;
4038 if (isa<UndefValue>(Incoming)) {
4039 // Remember that we saw an undef value, but otherwise ignore them.
4040 HasUndefInput = true;
4041 continue;
4042 }
4043 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004044 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004045 CommonValue = Incoming;
4046 }
4047
4048 // If CommonValue is null then all of the incoming values were either undef or
4049 // equal to the phi node itself.
4050 if (!CommonValue)
4051 return UndefValue::get(PN->getType());
4052
4053 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4054 // instruction, we cannot return X as the result of the PHI node unless it
4055 // dominates the PHI block.
4056 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004057 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004058
4059 return CommonValue;
4060}
4061
David Majnemer6774d612016-07-26 17:58:05 +00004062static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4063 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004064 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004065 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004066
David Majnemer6774d612016-07-26 17:58:05 +00004067 if (auto *CI = dyn_cast<CastInst>(Op)) {
4068 auto *Src = CI->getOperand(0);
4069 Type *SrcTy = Src->getType();
4070 Type *MidTy = CI->getType();
4071 Type *DstTy = Ty;
4072 if (Src->getType() == Ty) {
4073 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4074 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4075 Type *SrcIntPtrTy =
4076 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4077 Type *MidIntPtrTy =
4078 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4079 Type *DstIntPtrTy =
4080 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4081 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4082 SrcIntPtrTy, MidIntPtrTy,
4083 DstIntPtrTy) == Instruction::BitCast)
4084 return Src;
4085 }
4086 }
David Majnemera90a6212016-07-26 05:52:29 +00004087
4088 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004089 if (CastOpc == Instruction::BitCast)
4090 if (Op->getType() == Ty)
4091 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004092
4093 return nullptr;
4094}
4095
David Majnemer6774d612016-07-26 17:58:05 +00004096Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4097 const DataLayout &DL,
4098 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004099 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004100 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004101 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004102 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004103}
4104
Chris Lattnera71e9d62009-11-10 00:55:12 +00004105//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004106
Sanjay Patel472cc782016-01-11 22:14:42 +00004107/// Given operands for a BinaryOperator, see if we can fold the result.
4108/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004109static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004110 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004111 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004112 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004113 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004114 case Instruction::FAdd:
4115 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004116 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004117 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004118 case Instruction::FSub:
4119 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004120 case Instruction::Mul:
4121 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004122 case Instruction::FMul:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004123 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4124 case Instruction::SDiv:
4125 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4126 case Instruction::UDiv:
4127 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004128 case Instruction::FDiv:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004129 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4130 case Instruction::SRem:
4131 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4132 case Instruction::URem:
4133 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004134 case Instruction::FRem:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004135 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004136 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004137 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004138 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004139 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004140 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004141 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4142 case Instruction::And:
4143 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4144 case Instruction::Or:
4145 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4146 case Instruction::Xor:
4147 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004148 default:
4149 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004150 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4151 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004152
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004153 // If the operation is associative, try some generic simplifications.
4154 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004155 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004156 return V;
4157
Duncan Sandsb8cee002012-03-13 11:42:19 +00004158 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004159 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004160 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004161 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004162 return V;
4163
4164 // If the operation is with the result of a phi instruction, check whether
4165 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004166 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004167 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004168 return V;
4169
Craig Topper9f008862014-04-15 04:59:12 +00004170 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004171 }
4172}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004173
Sanjay Patel472cc782016-01-11 22:14:42 +00004174/// Given operands for a BinaryOperator, see if we can fold the result.
4175/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004176/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4177/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4178static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4179 const FastMathFlags &FMF, const Query &Q,
4180 unsigned MaxRecurse) {
4181 switch (Opcode) {
4182 case Instruction::FAdd:
4183 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4184 case Instruction::FSub:
4185 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4186 case Instruction::FMul:
4187 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004188 case Instruction::FDiv:
4189 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004190 default:
4191 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4192 }
4193}
4194
Duncan Sands7e800d62010-11-14 11:23:23 +00004195Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004196 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004197 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004198 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004199 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004200 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004201}
4202
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004203Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004204 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004205 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004206 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004207 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004208 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004209 RecursionLimit);
4210}
4211
Sanjay Patel472cc782016-01-11 22:14:42 +00004212/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004213static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004214 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004215 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004216 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004217 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004218}
4219
4220Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004221 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004222 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004223 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004224 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004225 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004226}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004227
Michael Ilseman54857292013-02-07 19:26:05 +00004228static bool IsIdempotent(Intrinsic::ID ID) {
4229 switch (ID) {
4230 default: return false;
4231
4232 // Unary idempotent: f(f(x)) = f(x)
4233 case Intrinsic::fabs:
4234 case Intrinsic::floor:
4235 case Intrinsic::ceil:
4236 case Intrinsic::trunc:
4237 case Intrinsic::rint:
4238 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004239 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004240 return true;
4241 }
4242}
4243
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004244static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4245 const DataLayout &DL) {
4246 GlobalValue *PtrSym;
4247 APInt PtrOffset;
4248 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4249 return nullptr;
4250
4251 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4252 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4253 Type *Int32PtrTy = Int32Ty->getPointerTo();
4254 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4255
4256 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4257 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4258 return nullptr;
4259
4260 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4261 if (OffsetInt % 4 != 0)
4262 return nullptr;
4263
4264 Constant *C = ConstantExpr::getGetElementPtr(
4265 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4266 ConstantInt::get(Int64Ty, OffsetInt / 4));
4267 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4268 if (!Loaded)
4269 return nullptr;
4270
4271 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4272 if (!LoadedCE)
4273 return nullptr;
4274
4275 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4276 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4277 if (!LoadedCE)
4278 return nullptr;
4279 }
4280
4281 if (LoadedCE->getOpcode() != Instruction::Sub)
4282 return nullptr;
4283
4284 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4285 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4286 return nullptr;
4287 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4288
4289 Constant *LoadedRHS = LoadedCE->getOperand(1);
4290 GlobalValue *LoadedRHSSym;
4291 APInt LoadedRHSOffset;
4292 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4293 DL) ||
4294 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4295 return nullptr;
4296
4297 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4298}
4299
David Majnemer17a95aa2016-07-14 06:58:37 +00004300static bool maskIsAllZeroOrUndef(Value *Mask) {
4301 auto *ConstMask = dyn_cast<Constant>(Mask);
4302 if (!ConstMask)
4303 return false;
4304 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4305 return true;
4306 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4307 ++I) {
4308 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4309 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4310 continue;
4311 return false;
4312 }
4313 return true;
4314}
4315
Michael Ilseman54857292013-02-07 19:26:05 +00004316template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004317static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004318 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004319 Intrinsic::ID IID = F->getIntrinsicID();
4320 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004321
4322 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004323 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004324 // Perform idempotent optimizations
4325 if (IsIdempotent(IID)) {
4326 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4327 if (II->getIntrinsicID() == IID)
4328 return II;
4329 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004330 }
4331
4332 switch (IID) {
4333 case Intrinsic::fabs: {
4334 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4335 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004336 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004337 }
4338 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004339 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004340 }
4341 }
Michael Ilseman54857292013-02-07 19:26:05 +00004342
Matt Arsenault82606662017-01-11 00:57:54 +00004343 // Binary Ops
4344 if (NumOperands == 2) {
4345 Value *LHS = *ArgBegin;
4346 Value *RHS = *(ArgBegin + 1);
4347 Type *ReturnType = F->getReturnType();
4348
4349 switch (IID) {
4350 case Intrinsic::usub_with_overflow:
4351 case Intrinsic::ssub_with_overflow: {
4352 // X - X -> { 0, false }
4353 if (LHS == RHS)
4354 return Constant::getNullValue(ReturnType);
4355
4356 // X - undef -> undef
4357 // undef - X -> undef
4358 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4359 return UndefValue::get(ReturnType);
4360
4361 return nullptr;
4362 }
4363 case Intrinsic::uadd_with_overflow:
4364 case Intrinsic::sadd_with_overflow: {
4365 // X + undef -> undef
4366 if (isa<UndefValue>(RHS))
4367 return UndefValue::get(ReturnType);
4368
4369 return nullptr;
4370 }
4371 case Intrinsic::umul_with_overflow:
4372 case Intrinsic::smul_with_overflow: {
4373 // X * 0 -> { 0, false }
4374 if (match(RHS, m_Zero()))
4375 return Constant::getNullValue(ReturnType);
4376
4377 // X * undef -> { 0, false }
4378 if (match(RHS, m_Undef()))
4379 return Constant::getNullValue(ReturnType);
4380
4381 return nullptr;
4382 }
4383 case Intrinsic::load_relative: {
4384 Constant *C0 = dyn_cast<Constant>(LHS);
4385 Constant *C1 = dyn_cast<Constant>(RHS);
4386 if (C0 && C1)
4387 return SimplifyRelativeLoad(C0, C1, Q.DL);
4388 return nullptr;
4389 }
4390 default:
4391 return nullptr;
4392 }
4393 }
4394
4395 // Simplify calls to llvm.masked.load.*
4396 switch (IID) {
4397 case Intrinsic::masked_load: {
4398 Value *MaskArg = ArgBegin[2];
4399 Value *PassthruArg = ArgBegin[3];
4400 // If the mask is all zeros or undef, the "passthru" argument is the result.
4401 if (maskIsAllZeroOrUndef(MaskArg))
4402 return PassthruArg;
4403 return nullptr;
4404 }
4405 default:
4406 return nullptr;
4407 }
Michael Ilseman54857292013-02-07 19:26:05 +00004408}
4409
Chandler Carruth9dc35582012-12-28 11:30:55 +00004410template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004411static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004412 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004413 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004414 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4415 Ty = PTy->getElementType();
4416 FunctionType *FTy = cast<FunctionType>(Ty);
4417
Dan Gohman85977e62011-11-04 18:32:42 +00004418 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004419 // call null -> undef
4420 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004421 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004422
Chandler Carruthf6182152012-12-28 14:23:29 +00004423 Function *F = dyn_cast<Function>(V);
4424 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004425 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004426
David Majnemer15032582015-05-22 03:56:46 +00004427 if (F->isIntrinsic())
4428 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004429 return Ret;
4430
Chandler Carruthf6182152012-12-28 14:23:29 +00004431 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004432 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004433
4434 SmallVector<Constant *, 4> ConstantArgs;
4435 ConstantArgs.reserve(ArgEnd - ArgBegin);
4436 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4437 Constant *C = dyn_cast<Constant>(*I);
4438 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004439 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004440 ConstantArgs.push_back(C);
4441 }
4442
4443 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004444}
4445
Chandler Carruthf6182152012-12-28 14:23:29 +00004446Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004447 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004448 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004449 AssumptionCache *AC, const Instruction *CxtI) {
4450 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004451 RecursionLimit);
4452}
4453
Chandler Carruthf6182152012-12-28 14:23:29 +00004454Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004455 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004456 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004457 const Instruction *CxtI) {
4458 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004459 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004460}
4461
Sanjay Patel472cc782016-01-11 22:14:42 +00004462/// See if we can compute a simplified version of this instruction.
4463/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004464Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004465 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004466 const DominatorTree *DT, AssumptionCache *AC,
4467 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004468 Value *Result;
4469
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004470 switch (I->getOpcode()) {
4471 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004472 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004473 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004474 case Instruction::FAdd:
4475 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004476 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004477 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004478 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004479 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4480 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004481 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004482 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004483 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004484 case Instruction::FSub:
4485 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004486 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004487 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004488 case Instruction::Sub:
4489 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4490 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004491 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004492 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004493 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004494 case Instruction::FMul:
4495 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004496 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004497 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004498 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004499 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004500 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004501 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004502 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004503 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004504 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004505 break;
4506 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004507 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004508 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004509 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004510 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004511 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004512 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004513 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004514 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004515 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004516 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004517 break;
4518 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004519 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004520 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004521 break;
4522 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004523 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004524 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004525 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004526 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004527 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4528 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004529 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004530 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004531 break;
4532 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004533 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004534 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004535 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004536 break;
4537 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004538 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004539 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004540 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004541 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004542 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004543 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004544 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004545 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004546 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004547 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004548 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004549 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004550 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004551 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004552 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004553 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004554 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004555 Result =
4556 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004557 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004558 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004559 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004560 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4561 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004562 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004563 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004564 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004565 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004566 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004567 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004568 case Instruction::GetElementPtr: {
4569 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004570 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004571 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004572 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004573 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004574 case Instruction::InsertValue: {
4575 InsertValueInst *IV = cast<InsertValueInst>(I);
4576 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4577 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004578 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004579 break;
4580 }
David Majnemer25a796e2015-07-13 01:15:46 +00004581 case Instruction::ExtractValue: {
4582 auto *EVI = cast<ExtractValueInst>(I);
4583 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004584 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004585 break;
4586 }
David Majnemer599ca442015-07-13 01:15:53 +00004587 case Instruction::ExtractElement: {
4588 auto *EEI = cast<ExtractElementInst>(I);
4589 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004590 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004591 break;
4592 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004593 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004594 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004595 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004596 case Instruction::Call: {
4597 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004598 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004599 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004600 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004601 }
David Majnemer6774d612016-07-26 17:58:05 +00004602#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4603#include "llvm/IR/Instruction.def"
4604#undef HANDLE_CAST_INST
4605 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004606 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004607 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004608 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004609
Hal Finkelf2199b22015-10-23 20:37:08 +00004610 // In general, it is possible for computeKnownBits to determine all bits in a
4611 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004612 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004613 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4614 APInt KnownZero(BitWidth, 0);
4615 APInt KnownOne(BitWidth, 0);
Sanjay Patel54656ca2017-02-06 18:26:06 +00004616 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT, ORE);
Hal Finkelf2199b22015-10-23 20:37:08 +00004617 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004618 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004619 }
4620
Duncan Sands64e41cf2010-11-17 08:35:29 +00004621 /// If called on unreachable code, the above logic may report that the
4622 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004623 /// detecting that case here, returning a safe value instead.
4624 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004625}
4626
Sanjay Patelf44bd382016-01-20 18:59:48 +00004627/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004628/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004629///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004630/// This is the common implementation of the recursive simplification routines.
4631/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4632/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4633/// instructions to process and attempt to simplify it using
4634/// InstructionSimplify.
4635///
4636/// This routine returns 'true' only when *it* simplifies something. The passed
4637/// in simplified value does not count toward this.
4638static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004639 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004640 const DominatorTree *DT,
4641 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004642 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004643 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004644 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004645
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004646 // If we have an explicit value to collapse to, do that round of the
4647 // simplification loop by hand initially.
4648 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004649 for (User *U : I->users())
4650 if (U != I)
4651 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004652
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004653 // Replace the instruction with its simplified value.
4654 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004655
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004656 // Gracefully handle edge cases where the instruction is not wired into any
4657 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004658 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4659 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004660 I->eraseFromParent();
4661 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004662 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004663 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004664
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004665 // Note that we must test the size on each iteration, the worklist can grow.
4666 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4667 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004668
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004669 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004670 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004671 if (!SimpleV)
4672 continue;
4673
4674 Simplified = true;
4675
4676 // Stash away all the uses of the old instruction so we can check them for
4677 // recursive simplifications after a RAUW. This is cheaper than checking all
4678 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004679 for (User *U : I->users())
4680 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004681
4682 // Replace the instruction with its simplified value.
4683 I->replaceAllUsesWith(SimpleV);
4684
4685 // Gracefully handle edge cases where the instruction is not wired into any
4686 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004687 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4688 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004689 I->eraseFromParent();
4690 }
4691 return Simplified;
4692}
4693
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004694bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004695 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004696 const DominatorTree *DT,
4697 AssumptionCache *AC) {
4698 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004699}
4700
4701bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004702 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004703 const DominatorTree *DT,
4704 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004705 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4706 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004707 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004708}