blob: 519d6d67be510b322f6f70e28442f8e29215080b [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"
Daniel Berlin4d0fe642017-04-28 19:55:38 +000024#include "llvm/Analysis/AssumptionCache.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000025#include "llvm/Analysis/CaptureTracking.h"
Craig Topper0aa3a192017-08-14 21:39:51 +000026#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000027#include "llvm/Analysis/ConstantFolding.h"
Daniel Berlin4d0fe642017-04-28 19:55:38 +000028#include "llvm/Analysis/LoopAnalysisManager.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000030#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000031#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000032#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000035#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/GlobalAlias.h"
37#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000038#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000039#include "llvm/IR/ValueHandle.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000040#include "llvm/Support/KnownBits.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000041#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000042using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000043using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000044
Chandler Carruthf1221bd2014-04-22 02:48:03 +000045#define DEBUG_TYPE "instsimplify"
46
Chris Lattner9e4aa022011-02-09 17:15:04 +000047enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000048
Duncan Sands3547d2e2010-12-22 09:40:51 +000049STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000050STATISTIC(NumReassoc, "Number of reassociations");
51
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000052static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
53static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000054 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000055static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000056 const SimplifyQuery &, unsigned);
57static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000058 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000059static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000060 const SimplifyQuery &Q, unsigned MaxRecurse);
61static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
62static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000063static Value *SimplifyCastInst(unsigned, Value *, Type *,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000064 const SimplifyQuery &, unsigned);
George Burgess IV8e807bf2018-04-24 00:25:01 +000065static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &,
66 unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000067
Sanjay Patel35ed2412017-04-16 17:43:11 +000068/// For a boolean type or a vector of boolean type, return false or a vector
69/// with every element false.
Duncan Sandsc1c92712011-07-26 15:03:53 +000070static Constant *getFalse(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000071 return ConstantInt::getFalse(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000072}
73
Sanjay Patel35ed2412017-04-16 17:43:11 +000074/// For a boolean type or a vector of boolean type, return true or a vector
75/// with every element true.
Duncan Sandsc1c92712011-07-26 15:03:53 +000076static Constant *getTrue(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000077 return ConstantInt::getTrue(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000078}
79
Duncan Sands3d5692a2011-10-30 19:56:36 +000080/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
81static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
82 Value *RHS) {
83 CmpInst *Cmp = dyn_cast<CmpInst>(V);
84 if (!Cmp)
85 return false;
86 CmpInst::Predicate CPred = Cmp->getPredicate();
87 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
88 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
89 return true;
90 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
91 CRHS == LHS;
92}
93
Sanjay Patel472cc782016-01-11 22:14:42 +000094/// Does the given value dominate the specified phi node?
Sanjay Patel5da361a2018-04-10 18:38:19 +000095static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
Duncan Sands5ffc2982010-11-16 12:16:38 +000096 Instruction *I = dyn_cast<Instruction>(V);
97 if (!I)
98 // Arguments and constants dominate all instructions.
99 return true;
100
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000101 // If we are processing instructions (and/or basic blocks) that have not been
102 // fully added to a function, the parent nodes may still be null. Simply
103 // return the conservative answer in these cases.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000104 if (!I->getParent() || !P->getParent() || !I->getFunction())
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000105 return false;
106
Duncan Sands5ffc2982010-11-16 12:16:38 +0000107 // If we have a DominatorTree then do a precise test.
Daniel Berlin71ff6632017-05-31 01:47:24 +0000108 if (DT)
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000109 return DT->dominates(I, P);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000110
David Majnemer8a1c45d2015-12-12 05:38:55 +0000111 // Otherwise, if the instruction is in the entry block and is not an invoke,
112 // then it obviously dominates all phi nodes.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000113 if (I->getParent() == &I->getFunction()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000114 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000115 return true;
116
117 return false;
118}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000119
Sanjay Patel472cc782016-01-11 22:14:42 +0000120/// Simplify "A op (B op' C)" by distributing op over op', turning it into
121/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000122/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
123/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
124/// Returns the simplified value, or null if no simplification was performed.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000125static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
Craig Topper9c913bf2017-05-19 16:56:53 +0000126 Instruction::BinaryOps OpcodeToExpand,
127 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000128 // Recursion is always used, so bail out at once if we already hit the limit.
129 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000130 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000131
132 // Check whether the expression has the form "(A op' B) op C".
133 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
134 if (Op0->getOpcode() == OpcodeToExpand) {
135 // It does! Try turning it into "(A op C) op' (B op C)".
136 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
137 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000138 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
139 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000140 // They do! Return "L op' R" if it simplifies or is already available.
141 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000142 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
143 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000144 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000145 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000146 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000147 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000148 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000149 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000150 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000151 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000152 }
153 }
154
155 // Check whether the expression has the form "A op (B op' C)".
156 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
157 if (Op1->getOpcode() == OpcodeToExpand) {
158 // It does! Try turning it into "(A op B) op' (A op C)".
159 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
160 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000161 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
162 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000163 // They do! Return "L op' R" if it simplifies or is already available.
164 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000165 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
166 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000167 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000168 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000169 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000170 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000171 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000172 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000173 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000174 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000175 }
176 }
177
Craig Topper9f008862014-04-15 04:59:12 +0000178 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000179}
180
Sanjay Patel472cc782016-01-11 22:14:42 +0000181/// Generic simplifications for associative binary operations.
182/// Returns the simpler value, or null if none was found.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000183static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
Craig Topper9c913bf2017-05-19 16:56:53 +0000184 Value *LHS, Value *RHS,
185 const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000186 unsigned MaxRecurse) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000187 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
188
189 // Recursion is always used, so bail out at once if we already hit the limit.
190 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000191 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000192
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
195
196 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
197 if (Op0 && Op0->getOpcode() == Opcode) {
198 Value *A = Op0->getOperand(0);
199 Value *B = Op0->getOperand(1);
200 Value *C = RHS;
201
202 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000203 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000204 // It does! Return "A op V" if it simplifies or is already available.
205 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000206 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000207 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000208 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000209 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000210 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000211 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000212 }
213 }
214
215 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
216 if (Op1 && Op1->getOpcode() == Opcode) {
217 Value *A = LHS;
218 Value *B = Op1->getOperand(0);
219 Value *C = Op1->getOperand(1);
220
221 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000222 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // It does! Return "V op C" if it simplifies or is already available.
224 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000225 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000227 if (Value *W = SimplifyBinOp(Opcode, V, C, 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 // The remaining transforms require commutativity as well as associativity.
235 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000236 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000237
238 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
239 if (Op0 && Op0->getOpcode() == Opcode) {
240 Value *A = Op0->getOperand(0);
241 Value *B = Op0->getOperand(1);
242 Value *C = RHS;
243
244 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000245 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000246 // It does! Return "V op B" if it simplifies or is already available.
247 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000248 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000249 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000250 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000251 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000252 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000253 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000254 }
255 }
256
257 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
258 if (Op1 && Op1->getOpcode() == Opcode) {
259 Value *A = LHS;
260 Value *B = Op1->getOperand(0);
261 Value *C = Op1->getOperand(1);
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 "B op V" if it simplifies or is already available.
266 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000267 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000269 if (Value *W = SimplifyBinOp(Opcode, B, V, 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
Craig Topper9f008862014-04-15 04:59:12 +0000276 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000277}
278
Sanjay Patel472cc782016-01-11 22:14:42 +0000279/// In the case of a binary operation with a select instruction as an operand,
280/// try to simplify the binop by seeing whether evaluating it on both branches
281/// of the select results in the same value. Returns the common value if so,
282/// otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000283static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000284 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000285 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000286 // Recursion is always used, so bail out at once if we already hit the limit.
287 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000288 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000289
Duncan Sandsb0579e92010-11-10 13:00:08 +0000290 SelectInst *SI;
291 if (isa<SelectInst>(LHS)) {
292 SI = cast<SelectInst>(LHS);
293 } else {
294 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
295 SI = cast<SelectInst>(RHS);
296 }
297
298 // Evaluate the BinOp on the true and false branches of the select.
299 Value *TV;
300 Value *FV;
301 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000302 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
303 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000304 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000305 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
306 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000307 }
308
Duncan Sandse3c53952011-01-01 16:12:09 +0000309 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000310 // If they both failed to simplify then return null.
311 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000312 return TV;
313
314 // If one branch simplified to undef, return the other one.
315 if (TV && isa<UndefValue>(TV))
316 return FV;
317 if (FV && isa<UndefValue>(FV))
318 return TV;
319
320 // If applying the operation did not change the true and false select values,
321 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000322 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000323 return SI;
324
325 // If one branch simplified and the other did not, and the simplified
326 // value is equal to the unsimplified one, return the simplified value.
327 // For example, select (cond, X, X & Z) & Z -> X & Z.
328 if ((FV && !TV) || (TV && !FV)) {
329 // Check that the simplified value has the form "X op Y" where "op" is the
330 // same as the original operation.
331 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
Zachary Turner260fe3e2017-12-14 22:07:03 +0000332 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
Duncan Sandsb0579e92010-11-10 13:00:08 +0000333 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
334 // We already know that "op" is the same as for the simplified value. See
335 // if the operands match too. If so, return the simplified value.
336 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
337 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
338 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000339 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
340 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000341 return Simplified;
342 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000343 Simplified->getOperand(1) == UnsimplifiedLHS &&
344 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000345 return Simplified;
346 }
347 }
348
Craig Topper9f008862014-04-15 04:59:12 +0000349 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000350}
351
Sanjay Patel472cc782016-01-11 22:14:42 +0000352/// In the case of a comparison with a select instruction, try to simplify the
353/// comparison by seeing whether both branches of the select result in the same
354/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000356 Value *RHS, const SimplifyQuery &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000357 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000358 // Recursion is always used, so bail out at once if we already hit the limit.
359 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000360 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000361
Duncan Sandsb0579e92010-11-10 13:00:08 +0000362 // Make sure the select is on the LHS.
363 if (!isa<SelectInst>(LHS)) {
364 std::swap(LHS, RHS);
365 Pred = CmpInst::getSwappedPredicate(Pred);
366 }
367 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
368 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000369 Value *Cond = SI->getCondition();
370 Value *TV = SI->getTrueValue();
371 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000372
Duncan Sands06504022011-02-03 09:37:39 +0000373 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000374 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000375 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000376 if (TCmp == Cond) {
377 // It not only simplified, it simplified to the select condition. Replace
378 // it with 'true'.
379 TCmp = getTrue(Cond->getType());
380 } else if (!TCmp) {
381 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
382 // condition then we can replace it with 'true'. Otherwise give up.
383 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000384 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000385 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000386 }
387
Duncan Sands3d5692a2011-10-30 19:56:36 +0000388 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000389 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000390 if (FCmp == Cond) {
391 // It not only simplified, it simplified to the select condition. Replace
392 // it with 'false'.
393 FCmp = getFalse(Cond->getType());
394 } else if (!FCmp) {
395 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
396 // condition then we can replace it with 'false'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000398 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 FCmp = getFalse(Cond->getType());
400 }
401
402 // If both sides simplified to the same value, then use it as the result of
403 // the original comparison.
404 if (TCmp == FCmp)
405 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000406
407 // The remaining cases only make sense if the select condition has the same
408 // type as the result of the comparison, so bail out if this is not so.
409 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000410 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000411 // If the false value simplified to false, then the result of the compare
412 // is equal to "Cond && TCmp". This also catches the case when the false
413 // value simplified to false and the true value to true, returning "Cond".
414 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000415 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000416 return V;
417 // If the true value simplified to true, then the result of the compare
418 // is equal to "Cond || FCmp".
419 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000420 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000421 return V;
422 // Finally, if the false value simplified to true and the true value to
423 // false, then the result of the compare is equal to "!Cond".
424 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
425 if (Value *V =
426 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000427 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 return V;
429
Craig Topper9f008862014-04-15 04:59:12 +0000430 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000431}
432
Sanjay Patel472cc782016-01-11 22:14:42 +0000433/// In the case of a binary operation with an operand that is a PHI instruction,
434/// try to simplify the binop by seeing whether evaluating it on the incoming
435/// phi values yields the same result for every value. If so returns the common
436/// value, otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000437static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000438 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000439 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000440 // Recursion is always used, so bail out at once if we already hit the limit.
441 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000442 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000443
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000444 PHINode *PI;
445 if (isa<PHINode>(LHS)) {
446 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000447 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000448 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000449 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000450 } else {
451 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
452 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000453 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000454 if (!valueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000456 }
457
458 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000459 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000460 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000461 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000462 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000463 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000464 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
465 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 // If the operation failed to simplify, or simplified to a different value
467 // to previously, then give up.
468 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000469 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 CommonValue = V;
471 }
472
473 return CommonValue;
474}
475
Sanjay Patel472cc782016-01-11 22:14:42 +0000476/// In the case of a comparison with a PHI instruction, try to simplify the
477/// comparison by seeing whether comparing with all of the incoming phi values
478/// yields the same result every time. If so returns the common result,
479/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000481 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000482 // Recursion is always used, so bail out at once if we already hit the limit.
483 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000484 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000485
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000486 // Make sure the phi is on the LHS.
487 if (!isa<PHINode>(LHS)) {
488 std::swap(LHS, RHS);
489 Pred = CmpInst::getSwappedPredicate(Pred);
490 }
491 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
492 PHINode *PI = cast<PHINode>(LHS);
493
Duncan Sands5ffc2982010-11-16 12:16:38 +0000494 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Sanjay Patel5da361a2018-04-10 18:38:19 +0000495 if (!valueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000496 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000497
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000498 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000499 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000500 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000501 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000502 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000503 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000504 // If the operation failed to simplify, or simplified to a different value
505 // to previously, then give up.
506 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000507 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000508 CommonValue = V;
509 }
510
511 return CommonValue;
512}
513
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000514static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
515 Value *&Op0, Value *&Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000516 const SimplifyQuery &Q) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000517 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
518 if (auto *CRHS = dyn_cast<Constant>(Op1))
519 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
520
521 // Canonicalize the constant to the RHS if this is a commutative operation.
522 if (Instruction::isCommutative(Opcode))
523 std::swap(Op0, Op1);
524 }
525 return nullptr;
526}
527
Sanjay Patel472cc782016-01-11 22:14:42 +0000528/// Given operands for an Add, see if we can fold the result.
529/// If not, this returns null.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000530static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000531 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000532 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
533 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000534
Duncan Sands0a2c41682010-12-15 14:07:39 +0000535 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000536 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000537 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 // X + 0 -> X
540 if (match(Op1, m_Zero()))
541 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Chen Zhengfdf13ef2018-07-12 03:06:04 +0000543 // If two operands are negative, return 0.
544 if (isKnownNegation(Op0, Op1))
545 return Constant::getNullValue(Op0->getType());
546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + (Y - X) -> Y
548 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000549 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000550 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000553 return Y;
554
555 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000556 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000557 if (match(Op0, m_Not(m_Specific(Op1))) ||
558 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000559 return Constant::getAllOnesValue(Ty);
560
Craig Topperbcfd2d12017-04-20 16:56:25 +0000561 // add nsw/nuw (xor Y, signmask), signmask --> Y
Sanjay Patelfe672552017-02-18 21:59:09 +0000562 // The no-wrapping add guarantees that the top bit will be set by the add.
563 // Therefore, the xor must be clearing the already set sign bit of Y.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000564 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
Craig Topperbcfd2d12017-04-20 16:56:25 +0000565 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000566 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000567
Roman Lebedevb060ce42018-06-08 15:44:47 +0000568 // add nuw %x, -1 -> -1, because %x can only be 0.
Roman Lebedevf87321a2018-06-08 15:44:53 +0000569 if (IsNUW && match(Op1, m_AllOnes()))
Roman Lebedevb060ce42018-06-08 15:44:47 +0000570 return Op1; // Which is -1.
571
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000572 /// i1 add -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000573 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(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
Roman Lebedevf87321a2018-06-08 15:44:53 +0000594Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000595 const SimplifyQuery &Query) {
Roman Lebedevf87321a2018-06-08 15:44:53 +0000596 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000597}
598
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000599/// Compute the base pointer and cumulative constant offsets for V.
Chandler Carrutha0796552012-03-12 11:19:31 +0000600///
601/// This strips all constant offsets off of V, leaving it the base pointer, and
602/// accumulates the total constant offset applied in the returned constant. It
603/// returns 0 if V is not a pointer, and returns the constant '0' if there are
604/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000605///
606/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
607/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
608/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000609static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000610 bool AllowNonInbounds = false) {
Craig Topper95d23472017-07-09 07:04:00 +0000611 assert(V->getType()->isPtrOrPtrVectorTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000612
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000613 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000614 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000615
616 // Even though we don't look through PHI nodes, we could be called on an
617 // instruction in an unreachable block, which may be on a cycle.
618 SmallPtrSet<Value *, 4> Visited;
619 Visited.insert(V);
620 do {
621 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000622 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000623 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000624 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000625 V = GEP->getPointerOperand();
626 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000627 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000628 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000629 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000630 break;
631 V = GA->getAliasee();
632 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000633 if (auto CS = CallSite(V))
634 if (Value *RV = CS.getReturnedArgOperand()) {
635 V = RV;
636 continue;
637 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000638 break;
639 }
Craig Topper95d23472017-07-09 07:04:00 +0000640 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000641 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000642
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000643 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
644 if (V->getType()->isVectorTy())
645 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
646 OffsetIntPtr);
647 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000648}
649
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000650/// Compute the constant difference between two pointer values.
Chandler Carrutha0796552012-03-12 11:19:31 +0000651/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000652static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
653 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000654 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
655 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000656
657 // If LHS and RHS are not related via constant offsets to the same base
658 // value, there is nothing we can do here.
659 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000660 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000661
662 // Otherwise, the difference of LHS - RHS can be computed as:
663 // LHS - RHS
664 // = (LHSOffset + Base) - (RHSOffset + Base)
665 // = LHSOffset - RHSOffset
666 return ConstantExpr::getSub(LHSOffset, RHSOffset);
667}
668
Sanjay Patel472cc782016-01-11 22:14:42 +0000669/// Given operands for a Sub, see if we can fold the result.
670/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000671static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000672 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000673 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
674 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000675
676 // X - undef -> undef
677 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000678 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000679 return UndefValue::get(Op0->getType());
680
681 // X - 0 -> X
682 if (match(Op1, m_Zero()))
683 return Op0;
684
685 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000686 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000687 return Constant::getNullValue(Op0->getType());
688
Sanjay Patelefd88852016-10-19 21:23:45 +0000689 // Is this a negation?
690 if (match(Op0, m_Zero())) {
691 // 0 - X -> 0 if the sub is NUW.
692 if (isNUW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000693 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000694
Craig Topper8205a1a2017-05-24 16:53:07 +0000695 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +0000696 if (Known.Zero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000697 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
698 // Op1 must be 0 because negating the minimum signed value is undefined.
699 if (isNSW)
Sanjay Patel30be6652018-04-22 17:07:44 +0000700 return Constant::getNullValue(Op0->getType());
Sanjay Patelefd88852016-10-19 21:23:45 +0000701
702 // 0 - X -> X if X is 0 or the minimum signed value.
703 return Op1;
704 }
705 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000706
Duncan Sands99589d02011-01-18 11:50:19 +0000707 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
708 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000709 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000710 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
711 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000712 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000713 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000714 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000715 // It does, we successfully reassociated!
716 ++NumReassoc;
717 return W;
718 }
719 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000720 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000721 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000722 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // It does, we successfully reassociated!
724 ++NumReassoc;
725 return W;
726 }
727 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000728
Duncan Sands99589d02011-01-18 11:50:19 +0000729 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
730 // For example, X - (X + 1) -> -1
731 X = Op0;
732 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
733 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000734 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000735 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000736 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000737 // It does, we successfully reassociated!
738 ++NumReassoc;
739 return W;
740 }
741 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000742 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000743 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000744 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000745 // It does, we successfully reassociated!
746 ++NumReassoc;
747 return W;
748 }
749 }
750
751 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
752 // For example, X - (X - Y) -> Y.
753 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000754 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
755 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000756 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000757 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000758 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000759 // It does, we successfully reassociated!
760 ++NumReassoc;
761 return W;
762 }
763
Duncan Sands395ac42d2012-03-13 14:07:05 +0000764 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
765 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
766 match(Op1, m_Trunc(m_Value(Y))))
767 if (X->getType() == Y->getType())
768 // See if "V === X - Y" simplifies.
769 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
770 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000771 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
772 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000773 // It does, return the simplified "trunc V".
774 return W;
775
776 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000777 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000778 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000779 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000780 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
781
Duncan Sands99589d02011-01-18 11:50:19 +0000782 // i1 sub -> xor.
Craig Topperfde47232017-07-09 07:04:03 +0000783 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000784 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000785 return V;
786
Duncan Sands0a2c41682010-12-15 14:07:39 +0000787 // Threading Sub over selects and phi nodes is pointless, so don't bother.
788 // Threading over the select in "A - select(cond, B, C)" means evaluating
789 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
790 // only if B and C are equal. If B and C are equal then (since we assume
791 // that operands have already been simplified) "select(cond, B, C)" should
792 // have been simplified to the common value of B and C already. Analysing
793 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
794 // for threading over phi nodes.
795
Craig Topper9f008862014-04-15 04:59:12 +0000796 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000797}
798
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000799Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000800 const SimplifyQuery &Q) {
801 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
802}
803
Sanjay Patel472cc782016-01-11 22:14:42 +0000804/// Given operands for a Mul, see if we can fold the result.
805/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000806static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000807 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000808 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
809 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000810
811 // X * undef -> 0
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000812 // X * 0 -> 0
Sanjay Patel30be6652018-04-22 17:07:44 +0000813 if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
814 return Constant::getNullValue(Op0->getType());
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000815
816 // X * 1 -> X
817 if (match(Op1, m_One()))
818 return Op0;
819
Duncan Sandsb67edc62011-01-30 18:03:50 +0000820 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000821 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000822 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
823 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
824 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000825
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000826 // i1 mul -> and.
Craig Topperfde47232017-07-09 07:04:03 +0000827 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000828 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000829 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000830
831 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000832 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000833 MaxRecurse))
834 return V;
835
Dmitry Venikovd2257be2018-01-02 05:47:42 +0000836 // Mul distributes over Add. Try some generic simplifications based on this.
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000837 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000838 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000839 return V;
840
841 // If the operation is with the result of a select instruction, check whether
842 // operating on either branch of the select always yields the same value.
843 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000844 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000845 MaxRecurse))
846 return V;
847
848 // If the operation is with the result of a phi instruction, check whether
849 // operating on all incoming values of the phi always yields the same value.
850 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000851 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000852 MaxRecurse))
853 return V;
854
Craig Topper9f008862014-04-15 04:59:12 +0000855 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000856}
857
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000858Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
859 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
860}
861
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000862/// Check for common or similar folds of integer division or integer remainder.
Sanjay Patelfa877fd2017-09-11 13:34:27 +0000863/// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000864static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
865 Type *Ty = Op0->getType();
866
867 // X / undef -> undef
868 // X % undef -> undef
869 if (match(Op1, m_Undef()))
870 return Op1;
871
872 // X / 0 -> undef
873 // X % 0 -> undef
874 // We don't need to preserve faults!
875 if (match(Op1, m_Zero()))
876 return UndefValue::get(Ty);
877
Zvi Rackover51f0d642018-01-24 17:22:00 +0000878 // If any element of a constant divisor vector is zero or undef, the whole op
879 // is undef.
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000880 auto *Op1C = dyn_cast<Constant>(Op1);
881 if (Op1C && Ty->isVectorTy()) {
882 unsigned NumElts = Ty->getVectorNumElements();
883 for (unsigned i = 0; i != NumElts; ++i) {
884 Constant *Elt = Op1C->getAggregateElement(i);
Zvi Rackover51f0d642018-01-24 17:22:00 +0000885 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000886 return UndefValue::get(Ty);
887 }
888 }
889
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000890 // undef / X -> 0
891 // undef % X -> 0
892 if (match(Op0, m_Undef()))
893 return Constant::getNullValue(Ty);
894
895 // 0 / X -> 0
896 // 0 % X -> 0
897 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +0000898 return Constant::getNullValue(Op0->getType());
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000899
900 // X / X -> 1
901 // X % X -> 0
902 if (Op0 == Op1)
903 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
904
905 // X / 1 -> X
906 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +0000907 // If this is a boolean op (single-bit element type), we can't have
908 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
Sanjay Patel1e911fa2018-06-25 18:51:21 +0000909 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
910 Value *X;
911 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
912 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000913 return IsDiv ? Op0 : Constant::getNullValue(Ty);
914
915 return nullptr;
916}
917
Sanjay Patelcca8f782017-09-14 14:09:11 +0000918/// Given a predicate and two operands, return true if the comparison is true.
919/// This is a helper for div/rem simplification where we return some other value
920/// when we can prove a relationship between the operands.
921static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
922 const SimplifyQuery &Q, unsigned MaxRecurse) {
923 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
924 Constant *C = dyn_cast_or_null<Constant>(V);
925 return (C && C->isAllOnesValue());
926}
927
928/// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
929/// to simplify X % Y to X.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000930static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
Sanjay Patelcca8f782017-09-14 14:09:11 +0000931 unsigned MaxRecurse, bool IsSigned) {
932 // Recursion is always used, so bail out at once if we already hit the limit.
933 if (!MaxRecurse--)
934 return false;
935
936 if (IsSigned) {
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000937 // |X| / |Y| --> 0
938 //
939 // We require that 1 operand is a simple constant. That could be extended to
940 // 2 variables if we computed the sign bit for each.
941 //
942 // Make sure that a constant is not the minimum signed value because taking
943 // the abs() of that is undefined.
944 Type *Ty = X->getType();
945 const APInt *C;
946 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
947 // Is the variable divisor magnitude always greater than the constant
948 // dividend magnitude?
949 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
950 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
951 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
952 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
953 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
954 return true;
955 }
956 if (match(Y, m_APInt(C))) {
957 // Special-case: we can't take the abs() of a minimum signed value. If
958 // that's the divisor, then all we have to do is prove that the dividend
959 // is also not the minimum signed value.
960 if (C->isMinSignedValue())
961 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
962
963 // Is the variable dividend magnitude always less than the constant
964 // divisor magnitude?
965 // |X| < |C| --> X > -abs(C) and X < abs(C)
966 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
967 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
968 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
969 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
970 return true;
971 }
Sanjay Patelcca8f782017-09-14 14:09:11 +0000972 return false;
973 }
974
975 // IsSigned == false.
Sanjay Patel0d4fd5b2017-09-14 14:59:07 +0000976 // Is the dividend unsigned less than the divisor?
977 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
Sanjay Patelcca8f782017-09-14 14:09:11 +0000978}
979
Sanjay Patelfa877fd2017-09-11 13:34:27 +0000980/// These are simplifications common to SDiv and UDiv.
981static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000982 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000983 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
984 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +0000985
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000986 if (Value *V = simplifyDivRem(Op0, Op1, true))
987 return V;
988
Sanjay Patelcca8f782017-09-14 14:09:11 +0000989 bool IsSigned = Opcode == Instruction::SDiv;
Duncan Sands65995fa2011-01-28 18:50:50 +0000990
Duncan Sands771e82a2011-01-28 16:51:11 +0000991 // (X * Y) / Y -> X if the multiplication does not overflow.
Sanjay Patel33cb8452018-01-19 16:12:55 +0000992 Value *X;
993 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
994 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
995 // If the Mul does not overflow, then we are good to go.
Sanjay Patelcca8f782017-09-14 14:09:11 +0000996 if ((IsSigned && Mul->hasNoSignedWrap()) ||
997 (!IsSigned && Mul->hasNoUnsignedWrap()))
Duncan Sands5747aba2011-02-02 20:52:00 +0000998 return X;
Sanjay Patel33cb8452018-01-19 16:12:55 +0000999 // If X has the form X = A / Y, then X * Y cannot overflow.
1000 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1001 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1002 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001003 }
1004
Duncan Sands65995fa2011-01-28 18:50:50 +00001005 // (X rem Y) / Y -> 0
Sanjay Patelcca8f782017-09-14 14:09:11 +00001006 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1007 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
Duncan Sands65995fa2011-01-28 18:50:50 +00001008 return Constant::getNullValue(Op0->getType());
1009
David Majnemercb9d5962014-10-11 10:20:01 +00001010 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1011 ConstantInt *C1, *C2;
Sanjay Patelcca8f782017-09-14 14:09:11 +00001012 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
David Majnemercb9d5962014-10-11 10:20:01 +00001013 match(Op1, m_ConstantInt(C2))) {
1014 bool Overflow;
Craig Topper9b71a402017-04-19 21:09:45 +00001015 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
David Majnemercb9d5962014-10-11 10:20:01 +00001016 if (Overflow)
1017 return Constant::getNullValue(Op0->getType());
1018 }
1019
Duncan Sands65995fa2011-01-28 18:50:50 +00001020 // If the operation is with the result of a select instruction, check whether
1021 // operating on either branch of the select always yields the same value.
1022 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001023 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001024 return V;
1025
1026 // If the operation is with the result of a phi instruction, check whether
1027 // operating on all incoming values of the phi always yields the same value.
1028 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001029 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001030 return V;
1031
Sanjay Patelcca8f782017-09-14 14:09:11 +00001032 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1033 return Constant::getNullValue(Op0->getType());
1034
Craig Topper9f008862014-04-15 04:59:12 +00001035 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001036}
1037
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001038/// These are simplifications common to SRem and URem.
1039static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001040 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001041 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1042 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001043
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001044 if (Value *V = simplifyDivRem(Op0, Op1, false))
1045 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001046
David Majnemerb435a422014-09-17 04:16:35 +00001047 // (X % Y) % Y -> X % Y
1048 if ((Opcode == Instruction::SRem &&
1049 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1050 (Opcode == Instruction::URem &&
1051 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001052 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001053
Anton Bikineev82f61152018-01-23 09:27:47 +00001054 // (X << Y) % X -> 0
1055 if ((Opcode == Instruction::SRem &&
1056 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1057 (Opcode == Instruction::URem &&
1058 match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))
1059 return Constant::getNullValue(Op0->getType());
1060
Duncan Sandsa3e36992011-05-02 16:27:02 +00001061 // If the operation is with the result of a select instruction, check whether
1062 // operating on either branch of the select always yields the same value.
1063 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001064 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001065 return V;
1066
1067 // If the operation is with the result of a phi instruction, check whether
1068 // operating on all incoming values of the phi always yields the same value.
1069 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001070 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001071 return V;
1072
Sanjay Patelcca8f782017-09-14 14:09:11 +00001073 // If X / Y == 0, then X % Y == X.
1074 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1075 return Op0;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001076
1077 return nullptr;
1078}
1079
1080/// Given operands for an SDiv, see if we can fold the result.
1081/// If not, this returns null.
1082static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1083 unsigned MaxRecurse) {
Chen Zheng69bb0642018-07-21 12:27:54 +00001084 // If two operands are negated and no signed overflow, return -1.
1085 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1086 return Constant::getAllOnesValue(Op0->getType());
1087
Sanjay Patelcca8f782017-09-14 14:09:11 +00001088 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001089}
1090
1091Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1092 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1093}
1094
1095/// Given operands for a UDiv, see if we can fold the result.
1096/// If not, this returns null.
1097static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1098 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001099 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00001100}
1101
1102Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1103 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1104}
1105
Sanjay Patel472cc782016-01-11 22:14:42 +00001106/// Given operands for an SRem, see if we can fold the result.
1107/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001108static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001109 unsigned MaxRecurse) {
Sanjay Patel2b7e3102018-06-26 15:32:54 +00001110 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1111 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1112 Value *X;
1113 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1114 return ConstantInt::getNullValue(Op0->getType());
1115
Chen Zhengf801d0f2018-07-20 13:00:47 +00001116 // If the two operands are negated, return 0.
1117 if (isKnownNegation(Op0, Op1))
Chen Zheng69bb0642018-07-21 12:27:54 +00001118 return ConstantInt::getNullValue(Op0->getType());
Chen Zhengf801d0f2018-07-20 13:00:47 +00001119
Sanjay Patelcca8f782017-09-14 14:09:11 +00001120 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001121}
1122
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001123Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1124 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1125}
1126
Sanjay Patel472cc782016-01-11 22:14:42 +00001127/// Given operands for a URem, see if we can fold the result.
1128/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001129static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001130 unsigned MaxRecurse) {
Sanjay Patelcca8f782017-09-14 14:09:11 +00001131 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001132}
1133
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001134Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1135 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1136}
1137
Sanjay Patel472cc782016-01-11 22:14:42 +00001138/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001139static bool isUndefShift(Value *Amount) {
1140 Constant *C = dyn_cast<Constant>(Amount);
1141 if (!C)
1142 return false;
1143
1144 // X shift by undef -> undef because it may shift by the bitwidth.
1145 if (isa<UndefValue>(C))
1146 return true;
1147
1148 // Shifting by the bitwidth or more is undefined.
1149 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1150 if (CI->getValue().getLimitedValue() >=
1151 CI->getType()->getScalarSizeInBits())
1152 return true;
1153
1154 // If all lanes of a vector shift are undefined the whole shift is.
1155 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1156 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1157 if (!isUndefShift(C->getAggregateElement(I)))
1158 return false;
1159 return true;
1160 }
1161
1162 return false;
1163}
1164
Sanjay Patel472cc782016-01-11 22:14:42 +00001165/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1166/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001167static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001168 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001169 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1170 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001171
Duncan Sands571fd9a2011-01-14 14:44:12 +00001172 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001173 if (match(Op0, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001174 return Constant::getNullValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001175
Duncan Sands571fd9a2011-01-14 14:44:12 +00001176 // X shift by 0 -> X
Sanjay Patelad0bfb82018-06-26 17:31:38 +00001177 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1178 // would be poison.
1179 Value *X;
1180 if (match(Op1, m_Zero()) ||
1181 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001182 return Op0;
1183
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001184 // Fold undefined shifts.
1185 if (isUndefShift(Op1))
1186 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001187
Duncan Sands571fd9a2011-01-14 14:44:12 +00001188 // If the operation is with the result of a select instruction, check whether
1189 // operating on either branch of the select always yields the same value.
1190 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001191 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001192 return V;
1193
1194 // If the operation is with the result of a phi instruction, check whether
1195 // operating on all incoming values of the phi always yields the same value.
1196 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001197 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001198 return V;
1199
Sanjay Patel6786bc52016-05-10 20:46:54 +00001200 // If any bits in the shift amount make that value greater than or equal to
1201 // the number of bits in the type, the shift is undefined.
Craig Topper8205a1a2017-05-24 16:53:07 +00001202 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1203 if (Known.One.getLimitedValue() >= Known.getBitWidth())
Sanjay Patel6786bc52016-05-10 20:46:54 +00001204 return UndefValue::get(Op0->getType());
1205
1206 // If all valid bits in the shift amount are known zero, the first operand is
1207 // unchanged.
Craig Topper8205a1a2017-05-24 16:53:07 +00001208 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
Craig Topper8df66c62017-05-12 17:20:30 +00001209 if (Known.countMinTrailingZeros() >= NumValidShiftBits)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001210 return Op0;
1211
Craig Topper9f008862014-04-15 04:59:12 +00001212 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001213}
1214
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001215/// Given operands for an Shl, LShr or AShr, see if we can
David Majnemerbf7550e2014-11-05 00:59:59 +00001216/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001217static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001218 Value *Op1, bool isExact, const SimplifyQuery &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001219 unsigned MaxRecurse) {
1220 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1221 return V;
1222
1223 // X >> X -> 0
1224 if (Op0 == Op1)
1225 return Constant::getNullValue(Op0->getType());
1226
David Majnemer65c52ae2014-12-17 01:54:33 +00001227 // undef >> X -> 0
1228 // undef >> X -> undef (if it's exact)
1229 if (match(Op0, m_Undef()))
1230 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1231
David Majnemerbf7550e2014-11-05 00:59:59 +00001232 // The low bit cannot be shifted out of an exact shift if it is set.
1233 if (isExact) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001234 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
Craig Topperb45eabc2017-04-26 16:39:58 +00001235 if (Op0Known.One[0])
David Majnemerbf7550e2014-11-05 00:59:59 +00001236 return Op0;
1237 }
1238
1239 return nullptr;
1240}
1241
Sanjay Patel472cc782016-01-11 22:14:42 +00001242/// Given operands for an Shl, see if we can fold the result.
1243/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001244static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001245 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001246 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001247 return V;
1248
1249 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001250 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001251 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001252 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001253
Chris Lattner9e4aa022011-02-09 17:15:04 +00001254 // (X >> A) << A -> X
1255 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001256 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001257 return X;
Roman Lebedev26838022018-06-07 20:03:45 +00001258
1259 // shl nuw i8 C, %x -> C iff C has sign bit set.
1260 if (isNUW && match(Op0, m_Negative()))
1261 return Op0;
1262 // NOTE: could use computeKnownBits() / LazyValueInfo,
1263 // but the cost-benefit analysis suggests it isn't worth it.
1264
Craig Topper9f008862014-04-15 04:59:12 +00001265 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001266}
1267
Chris Lattner9e4aa022011-02-09 17:15:04 +00001268Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001269 const SimplifyQuery &Q) {
1270 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1271}
1272
Sanjay Patel472cc782016-01-11 22:14:42 +00001273/// Given operands for an LShr, see if we can fold the result.
1274/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001275static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001276 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001277 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1278 MaxRecurse))
1279 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001280
Chris Lattner9e4aa022011-02-09 17:15:04 +00001281 // (X << A) >> A -> X
1282 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001283 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001284 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001285
Craig Topper9f008862014-04-15 04:59:12 +00001286 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001287}
1288
Chris Lattner9e4aa022011-02-09 17:15:04 +00001289Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001290 const SimplifyQuery &Q) {
1291 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1292}
1293
Sanjay Patel472cc782016-01-11 22:14:42 +00001294/// Given operands for an AShr, see if we can fold the result.
1295/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001296static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001297 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001298 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1299 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001300 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001301
Sanjay Pateladf6e882018-02-18 18:05:08 +00001302 // all ones >>a X -> -1
1303 // Do not return Op0 because it may contain undef elements if it's a vector.
Duncan Sands7f60dc12011-01-14 00:37:45 +00001304 if (match(Op0, m_AllOnes()))
Sanjay Pateladf6e882018-02-18 18:05:08 +00001305 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001306
Chris Lattner9e4aa022011-02-09 17:15:04 +00001307 // (X << A) >> A -> X
1308 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001309 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001310 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001311
Suyog Sarda68862412014-07-17 06:28:15 +00001312 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001313 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001314 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1315 return Op0;
1316
Craig Topper9f008862014-04-15 04:59:12 +00001317 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001318}
1319
Chris Lattner9e4aa022011-02-09 17:15:04 +00001320Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001321 const SimplifyQuery &Q) {
1322 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1323}
1324
Craig Topper348314d2017-05-26 22:42:34 +00001325/// Commuted variants are assumed to be handled by calling this function again
1326/// with the parameters swapped.
David Majnemer1af36e52014-12-06 10:51:40 +00001327static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1328 ICmpInst *UnsignedICmp, bool IsAnd) {
1329 Value *X, *Y;
1330
1331 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001332 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1333 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001334 return nullptr;
1335
1336 ICmpInst::Predicate UnsignedPred;
1337 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1338 ICmpInst::isUnsigned(UnsignedPred))
1339 ;
1340 else if (match(UnsignedICmp,
Sanjay Patel0c57de42018-06-20 14:22:49 +00001341 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
David Majnemer1af36e52014-12-06 10:51:40 +00001342 ICmpInst::isUnsigned(UnsignedPred))
1343 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1344 else
1345 return nullptr;
1346
1347 // X < Y && Y != 0 --> X < Y
1348 // X < Y || Y != 0 --> Y != 0
1349 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1350 return IsAnd ? UnsignedICmp : ZeroICmp;
1351
1352 // X >= Y || Y != 0 --> true
1353 // X >= Y || Y == 0 --> X >= Y
1354 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1355 if (EqPred == ICmpInst::ICMP_NE)
1356 return getTrue(UnsignedICmp->getType());
1357 return UnsignedICmp;
1358 }
1359
David Majnemerd5b3aa42014-12-08 18:30:43 +00001360 // X < Y && Y == 0 --> false
1361 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1362 IsAnd)
1363 return getFalse(UnsignedICmp->getType());
1364
David Majnemer1af36e52014-12-06 10:51:40 +00001365 return nullptr;
1366}
1367
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001368/// Commuted variants are assumed to be handled by calling this function again
1369/// with the parameters swapped.
1370static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1371 ICmpInst::Predicate Pred0, Pred1;
1372 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001373 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1374 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001375 return nullptr;
1376
1377 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1378 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1379 // can eliminate Op1 from this 'and'.
1380 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1381 return Op0;
1382
1383 // Check for any combination of predicates that are guaranteed to be disjoint.
1384 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1385 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1386 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1387 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1388 return getFalse(Op0->getType());
1389
1390 return nullptr;
1391}
1392
1393/// Commuted variants are assumed to be handled by calling this function again
1394/// with the parameters swapped.
Sanjay Patel142cb832017-05-04 18:19:17 +00001395static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1396 ICmpInst::Predicate Pred0, Pred1;
1397 Value *A ,*B;
1398 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1399 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1400 return nullptr;
1401
1402 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1403 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1404 // can eliminate Op0 from this 'or'.
1405 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1406 return Op1;
1407
1408 // Check for any combination of predicates that cover the entire range of
1409 // possibilities.
1410 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1411 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1412 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1413 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1414 return getTrue(Op0->getType());
1415
1416 return nullptr;
1417}
1418
Sanjay Patel599e65b2017-05-07 15:11:40 +00001419/// Test if a pair of compares with a shared operand and 2 constants has an
1420/// empty set intersection, full set union, or if one compare is a superset of
1421/// the other.
1422static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1423 bool IsAnd) {
1424 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1425 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1426 return nullptr;
1427
1428 const APInt *C0, *C1;
1429 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1430 !match(Cmp1->getOperand(1), m_APInt(C1)))
1431 return nullptr;
1432
1433 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1434 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1435
Sanjay Patel67454472017-05-08 16:35:02 +00001436 // For and-of-compares, check if the intersection is empty:
Sanjay Patel599e65b2017-05-07 15:11:40 +00001437 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1438 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1439 return getFalse(Cmp0->getType());
1440
1441 // For or-of-compares, check if the union is full:
1442 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1443 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1444 return getTrue(Cmp0->getType());
1445
1446 // Is one range a superset of the other?
1447 // If this is and-of-compares, take the smaller set:
1448 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1449 // If this is or-of-compares, take the larger set:
1450 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1451 if (Range0.contains(Range1))
1452 return IsAnd ? Cmp1 : Cmp0;
1453 if (Range1.contains(Range0))
1454 return IsAnd ? Cmp0 : Cmp1;
1455
1456 return nullptr;
1457}
1458
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001459static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1460 bool IsAnd) {
1461 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1462 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1463 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1464 return nullptr;
1465
1466 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1467 return nullptr;
1468
Sanjay Patel4158eff2018-01-13 15:44:44 +00001469 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001470 Value *X = Cmp0->getOperand(0);
1471 Value *Y = Cmp1->getOperand(0);
1472
1473 // If one of the compares is a masked version of a (not) null check, then
Sanjay Patel4158eff2018-01-13 15:44:44 +00001474 // that compare implies the other, so we eliminate the other. Optionally, look
1475 // through a pointer-to-int cast to match a null check of a pointer type.
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001476
Sanjay Patel9568f422018-01-14 15:58:18 +00001477 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1478 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1479 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1480 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001481 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1482 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001483 return Cmp1;
1484
Sanjay Patel9568f422018-01-14 15:58:18 +00001485 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1486 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1487 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1488 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
Sanjay Patel4158eff2018-01-13 15:44:44 +00001489 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1490 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001491 return Cmp0;
1492
1493 return nullptr;
1494}
1495
Craig Topper348314d2017-05-26 22:42:34 +00001496static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
Sanjay Patel599e65b2017-05-07 15:11:40 +00001497 // (icmp (add V, C0), C1) & (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001498 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001499 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001500 Value *V;
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001501 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001502 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001503
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001504 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001505 return nullptr;
1506
David Majnemera315bd82014-09-15 08:15:28 +00001507 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001508 if (AddInst->getOperand(1) != Op1->getOperand(1))
1509 return nullptr;
1510
Craig Topper9bce1ad2017-05-26 19:04:02 +00001511 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001512 bool isNSW = AddInst->hasNoSignedWrap();
1513 bool isNUW = AddInst->hasNoUnsignedWrap();
1514
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001515 const APInt Delta = *C1 - *C0;
1516 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001517 if (Delta == 2) {
1518 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1519 return getFalse(ITy);
1520 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1521 return getFalse(ITy);
1522 }
1523 if (Delta == 1) {
1524 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1525 return getFalse(ITy);
1526 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1527 return getFalse(ITy);
1528 }
1529 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001530 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001531 if (Delta == 2)
1532 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1533 return getFalse(ITy);
1534 if (Delta == 1)
1535 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1536 return getFalse(ITy);
1537 }
1538
1539 return nullptr;
1540}
1541
Craig Topper348314d2017-05-26 22:42:34 +00001542static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1543 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1544 return X;
1545 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true))
Sanjay Patel142cb832017-05-04 18:19:17 +00001546 return X;
1547
Craig Topper348314d2017-05-26 22:42:34 +00001548 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1549 return X;
1550 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
Sanjay Patel142cb832017-05-04 18:19:17 +00001551 return X;
1552
Craig Topper348314d2017-05-26 22:42:34 +00001553 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
Sanjay Patel599e65b2017-05-07 15:11:40 +00001554 return X;
1555
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001556 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1557 return X;
1558
Craig Topper348314d2017-05-26 22:42:34 +00001559 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1))
1560 return X;
1561 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0))
1562 return X;
1563
1564 return nullptr;
1565}
1566
1567static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) {
Sanjay Patel142cb832017-05-04 18:19:17 +00001568 // (icmp (add V, C0), C1) | (icmp V, C0)
1569 ICmpInst::Predicate Pred0, Pred1;
1570 const APInt *C0, *C1;
1571 Value *V;
1572 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1573 return nullptr;
1574
1575 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1576 return nullptr;
1577
1578 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1579 if (AddInst->getOperand(1) != Op1->getOperand(1))
1580 return nullptr;
1581
1582 Type *ITy = Op0->getType();
1583 bool isNSW = AddInst->hasNoSignedWrap();
1584 bool isNUW = AddInst->hasNoUnsignedWrap();
1585
1586 const APInt Delta = *C1 - *C0;
1587 if (C0->isStrictlyPositive()) {
1588 if (Delta == 2) {
1589 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1590 return getTrue(ITy);
1591 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1592 return getTrue(ITy);
1593 }
1594 if (Delta == 1) {
1595 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1596 return getTrue(ITy);
1597 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1598 return getTrue(ITy);
1599 }
1600 }
1601 if (C0->getBoolValue() && isNUW) {
1602 if (Delta == 2)
1603 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1604 return getTrue(ITy);
1605 if (Delta == 1)
1606 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1607 return getTrue(ITy);
1608 }
1609
1610 return nullptr;
1611}
1612
Craig Topper348314d2017-05-26 22:42:34 +00001613static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1614 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1615 return X;
1616 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false))
1617 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001618
Craig Topper348314d2017-05-26 22:42:34 +00001619 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1620 return X;
1621 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1622 return X;
1623
1624 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1625 return X;
1626
Sanjay Patel6ef6aa92018-01-11 23:27:37 +00001627 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1628 return X;
1629
Craig Topper348314d2017-05-26 22:42:34 +00001630 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1))
1631 return X;
1632 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0))
1633 return X;
Sanjay Patele42b4d52017-05-04 19:51:34 +00001634
1635 return nullptr;
1636}
1637
Sanjay Pateleb731b02017-11-19 15:34:27 +00001638static Value *simplifyAndOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1639 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1640 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1641 if (LHS0->getType() != RHS0->getType())
1642 return nullptr;
1643
1644 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1645 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1646 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1647 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1648 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1649 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1650 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1651 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1652 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1653 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1654 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1655 if ((isKnownNeverNaN(LHS0) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1656 (isKnownNeverNaN(LHS1) && (LHS0 == RHS0 || LHS0 == RHS1)))
1657 return RHS;
1658
1659 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1660 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1661 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1662 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1663 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1664 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1665 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1666 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1667 if ((isKnownNeverNaN(RHS0) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1668 (isKnownNeverNaN(RHS1) && (RHS0 == LHS0 || RHS0 == LHS1)))
1669 return LHS;
1670 }
1671
1672 return nullptr;
1673}
1674
1675static Value *simplifyAndOrOfCmps(Value *Op0, Value *Op1, bool IsAnd) {
Sanjay Patele42b4d52017-05-04 19:51:34 +00001676 // Look through casts of the 'and' operands to find compares.
1677 auto *Cast0 = dyn_cast<CastInst>(Op0);
1678 auto *Cast1 = dyn_cast<CastInst>(Op1);
1679 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1680 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1681 Op0 = Cast0->getOperand(0);
1682 Op1 = Cast1->getOperand(0);
1683 }
1684
Sanjay Pateleb731b02017-11-19 15:34:27 +00001685 Value *V = nullptr;
1686 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1687 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1688 if (ICmp0 && ICmp1)
1689 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1) :
1690 simplifyOrOfICmps(ICmp0, ICmp1);
Sanjay Patele42b4d52017-05-04 19:51:34 +00001691
Sanjay Pateleb731b02017-11-19 15:34:27 +00001692 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1693 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1694 if (FCmp0 && FCmp1)
1695 V = simplifyAndOrOfFCmps(FCmp0, FCmp1, IsAnd);
1696
Craig Topper348314d2017-05-26 22:42:34 +00001697 if (!V)
1698 return nullptr;
1699 if (!Cast0)
Sanjay Patele42b4d52017-05-04 19:51:34 +00001700 return V;
Craig Topper348314d2017-05-26 22:42:34 +00001701
1702 // If we looked through casts, we can only handle a constant simplification
1703 // because we are not allowed to create a cast instruction here.
1704 if (auto *C = dyn_cast<Constant>(V))
1705 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
Sanjay Patele42b4d52017-05-04 19:51:34 +00001706
1707 return nullptr;
1708}
1709
Sanjay Patel472cc782016-01-11 22:14:42 +00001710/// Given operands for an And, see if we can fold the result.
1711/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001712static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001713 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001714 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1715 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001716
Chris Lattnera71e9d62009-11-10 00:55:12 +00001717 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001718 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001719 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001720
Chris Lattnera71e9d62009-11-10 00:55:12 +00001721 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001722 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001723 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001724
Duncan Sandsc89ac072010-11-17 18:52:15 +00001725 // X & 0 = 0
1726 if (match(Op1, m_Zero()))
Sanjay Patel30be6652018-04-22 17:07:44 +00001727 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001728
Duncan Sandsc89ac072010-11-17 18:52:15 +00001729 // X & -1 = X
1730 if (match(Op1, m_AllOnes()))
1731 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001732
Chris Lattnera71e9d62009-11-10 00:55:12 +00001733 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001734 if (match(Op0, m_Not(m_Specific(Op1))) ||
1735 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001736 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001737
Chris Lattnera71e9d62009-11-10 00:55:12 +00001738 // (A | ?) & A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001739 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001740 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001741
Chris Lattnera71e9d62009-11-10 00:55:12 +00001742 // A & (A | ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001743 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001744 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001745
Sanjay Patel877364f2017-05-16 21:51:04 +00001746 // A mask that only clears known zeros of a shifted value is a no-op.
1747 Value *X;
1748 const APInt *Mask;
1749 const APInt *ShAmt;
1750 if (match(Op1, m_APInt(Mask))) {
1751 // If all bits in the inverted and shifted mask are clear:
1752 // and (shl X, ShAmt), Mask --> shl X, ShAmt
1753 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1754 (~(*Mask)).lshr(*ShAmt).isNullValue())
1755 return Op0;
1756
1757 // If all bits in the inverted and shifted mask are clear:
1758 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1759 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1760 (~(*Mask)).shl(*ShAmt).isNullValue())
1761 return Op0;
1762 }
1763
Duncan Sandsba286d72011-10-26 20:55:21 +00001764 // A & (-A) = A if A is a power of two or zero.
1765 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1766 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001767 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1768 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001769 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001770 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1771 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001772 return Op1;
1773 }
1774
Sanjay Pateleb731b02017-11-19 15:34:27 +00001775 if (Value *V = simplifyAndOrOfCmps(Op0, Op1, true))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001776 return V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001777
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001778 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001779 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1780 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001781 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001782
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001783 // And distributes over Or. Try some generic simplifications based on this.
1784 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001785 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001786 return V;
1787
1788 // And distributes over Xor. Try some generic simplifications based on this.
1789 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001790 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001791 return V;
1792
Duncan Sandsb0579e92010-11-10 13:00:08 +00001793 // If the operation is with the result of a select instruction, check whether
1794 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001795 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001796 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1797 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001798 return V;
1799
1800 // If the operation is with the result of a phi instruction, check whether
1801 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001802 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001803 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001804 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001805 return V;
1806
Craig Topper9f008862014-04-15 04:59:12 +00001807 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001808}
1809
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001810Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1811 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1812}
1813
Sanjay Patel472cc782016-01-11 22:14:42 +00001814/// Given operands for an Or, see if we can fold the result.
1815/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001816static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001817 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001818 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1819 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001820
Chris Lattnera71e9d62009-11-10 00:55:12 +00001821 // X | undef -> -1
Sanjay Pateladf6e882018-02-18 18:05:08 +00001822 // X | -1 = -1
1823 // Do not return Op1 because it may contain undef elements if it's a vector.
1824 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001825 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001826
Chris Lattnera71e9d62009-11-10 00:55:12 +00001827 // X | X = X
Duncan Sandsc89ac072010-11-17 18:52:15 +00001828 // X | 0 = X
Sanjay Pateladf6e882018-02-18 18:05:08 +00001829 if (Op0 == Op1 || match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001830 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001831
Chris Lattnera71e9d62009-11-10 00:55:12 +00001832 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001833 if (match(Op0, m_Not(m_Specific(Op1))) ||
1834 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001835 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001836
Chris Lattnera71e9d62009-11-10 00:55:12 +00001837 // (A & ?) | A = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001838 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001839 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001840
Chris Lattnera71e9d62009-11-10 00:55:12 +00001841 // A | (A & ?) = A
Craig Topperdad7d8d2017-07-16 06:57:41 +00001842 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001843 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001844
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001845 // ~(A & ?) | A = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001846 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001847 return Constant::getAllOnesValue(Op1->getType());
1848
1849 // A | ~(A & ?) = -1
Craig Topperdad7d8d2017-07-16 06:57:41 +00001850 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001851 return Constant::getAllOnesValue(Op0->getType());
1852
Craig Topperdad7d8d2017-07-16 06:57:41 +00001853 Value *A, *B;
Sanjay Patel08892252017-04-24 18:24:36 +00001854 // (A & ~B) | (A ^ B) -> (A ^ B)
1855 // (~B & A) | (A ^ B) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001856 // (A & ~B) | (B ^ A) -> (B ^ A)
1857 // (~B & A) | (B ^ A) -> (B ^ A)
1858 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1859 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1860 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001861 return Op1;
1862
1863 // Commute the 'or' operands.
1864 // (A ^ B) | (A & ~B) -> (A ^ B)
1865 // (A ^ B) | (~B & A) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001866 // (B ^ A) | (A & ~B) -> (B ^ A)
1867 // (B ^ A) | (~B & A) -> (B ^ A)
1868 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1869 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1870 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001871 return Op0;
1872
Craig Topper479daaf2017-05-14 07:54:43 +00001873 // (A & B) | (~A ^ B) -> (~A ^ B)
1874 // (B & A) | (~A ^ B) -> (~A ^ B)
1875 // (A & B) | (B ^ ~A) -> (B ^ ~A)
1876 // (B & A) | (B ^ ~A) -> (B ^ ~A)
1877 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1878 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1879 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1880 return Op1;
1881
1882 // (~A ^ B) | (A & B) -> (~A ^ B)
1883 // (~A ^ B) | (B & A) -> (~A ^ B)
1884 // (B ^ ~A) | (A & B) -> (B ^ ~A)
1885 // (B ^ ~A) | (B & A) -> (B ^ ~A)
1886 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1887 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
1888 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
1889 return Op0;
1890
Sanjay Pateleb731b02017-11-19 15:34:27 +00001891 if (Value *V = simplifyAndOrOfCmps(Op0, Op1, false))
Sanjay Patele42b4d52017-05-04 19:51:34 +00001892 return V;
David Majnemera315bd82014-09-15 08:15:28 +00001893
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001894 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001895 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1896 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001897 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001898
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001899 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001900 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1901 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001902 return V;
1903
Duncan Sandsb0579e92010-11-10 13:00:08 +00001904 // If the operation is with the result of a select instruction, check whether
1905 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001906 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001907 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001908 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001909 return V;
1910
Craig Topper50500d52017-05-26 05:16:20 +00001911 // (A & C1)|(B & C2)
Craig Topper1da22c32017-05-26 19:03:53 +00001912 const APInt *C1, *C2;
1913 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
1914 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
1915 if (*C1 == ~*C2) {
Nick Lewycky8561a492014-06-19 03:51:46 +00001916 // (A & C1)|(B & C2)
1917 // If we have: ((V + N) & C1) | (V & C2)
1918 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1919 // replace with V+N.
Craig Topperc8bebb12017-05-26 19:03:59 +00001920 Value *N;
Craig Topper1da22c32017-05-26 19:03:53 +00001921 if (C2->isMask() && // C2 == 0+1+
Craig Topperc8bebb12017-05-26 19:03:59 +00001922 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00001923 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00001924 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001925 return A;
1926 }
1927 // Or commutes, try both ways.
Craig Topper1da22c32017-05-26 19:03:53 +00001928 if (C1->isMask() &&
Craig Topperc8bebb12017-05-26 19:03:59 +00001929 match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
Nick Lewycky8561a492014-06-19 03:51:46 +00001930 // Add commutes, try both ways.
Craig Topperc8bebb12017-05-26 19:03:59 +00001931 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001932 return B;
1933 }
1934 }
1935 }
1936
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001937 // If the operation is with the result of a phi instruction, check whether
1938 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001939 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001940 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001941 return V;
1942
Craig Topper9f008862014-04-15 04:59:12 +00001943 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001944}
1945
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001946Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1947 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
1948}
1949
Sanjay Patel472cc782016-01-11 22:14:42 +00001950/// Given operands for a Xor, see if we can fold the result.
1951/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001952static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001953 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001954 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
1955 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001956
1957 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001958 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001959 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001960
1961 // A ^ 0 = A
1962 if (match(Op1, m_Zero()))
1963 return Op0;
1964
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001965 // A ^ A = 0
1966 if (Op0 == Op1)
1967 return Constant::getNullValue(Op0->getType());
1968
Duncan Sandsc89ac072010-11-17 18:52:15 +00001969 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001970 if (match(Op0, m_Not(m_Specific(Op1))) ||
1971 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001972 return Constant::getAllOnesValue(Op0->getType());
1973
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001974 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001975 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1976 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001977 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001978
Duncan Sandsb238de02010-11-19 09:20:39 +00001979 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1980 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1981 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1982 // only if B and C are equal. If B and C are equal then (since we assume
1983 // that operands have already been simplified) "select(cond, B, C)" should
1984 // have been simplified to the common value of B and C already. Analysing
1985 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1986 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001987
Craig Topper9f008862014-04-15 04:59:12 +00001988 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001989}
1990
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001991Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1992 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
1993}
1994
1995
Chris Lattner229907c2011-07-18 04:54:35 +00001996static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001997 return CmpInst::makeCmpResultType(Op->getType());
1998}
1999
Sanjay Patel472cc782016-01-11 22:14:42 +00002000/// Rummage around inside V looking for something equivalent to the comparison
2001/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2002/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002003static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2004 Value *LHS, Value *RHS) {
2005 SelectInst *SI = dyn_cast<SelectInst>(V);
2006 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002007 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002008 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2009 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002010 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002011 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2012 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2013 return Cmp;
2014 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2015 LHS == CmpRHS && RHS == CmpLHS)
2016 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002017 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002018}
2019
Dan Gohman9631d902013-02-01 00:49:06 +00002020// A significant optimization not implemented here is assuming that alloca
2021// addresses are not equal to incoming argument values. They don't *alias*,
2022// as we say, but that doesn't mean they aren't equal, so we take a
2023// conservative approach.
2024//
2025// This is inspired in part by C++11 5.10p1:
2026// "Two pointers of the same type compare equal if and only if they are both
2027// null, both point to the same function, or both represent the same
2028// address."
2029//
2030// This is pretty permissive.
2031//
2032// It's also partly due to C11 6.5.9p6:
2033// "Two pointers compare equal if and only if both are null pointers, both are
2034// pointers to the same object (including a pointer to an object and a
2035// subobject at its beginning) or function, both are pointers to one past the
2036// last element of the same array object, or one is a pointer to one past the
2037// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002038// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002039// object in the address space.)
2040//
2041// C11's version is more restrictive, however there's no reason why an argument
2042// couldn't be a one-past-the-end value for a stack object in the caller and be
2043// equal to the beginning of a stack object in the callee.
2044//
2045// If the C and C++ standards are ever made sufficiently restrictive in this
2046// area, it may be possible to update LLVM's semantics accordingly and reinstate
2047// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002048static Constant *
2049computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2050 const DominatorTree *DT, CmpInst::Predicate Pred,
Nuno Lopes404f1062017-09-09 18:23:11 +00002051 AssumptionCache *AC, const Instruction *CxtI,
2052 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002053 // First, skip past any trivial no-ops.
2054 LHS = LHS->stripPointerCasts();
2055 RHS = RHS->stripPointerCasts();
2056
2057 // A non-null pointer is not equal to a null pointer.
Nuno Lopes404f1062017-09-09 18:23:11 +00002058 if (llvm::isKnownNonZero(LHS, DL) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002059 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2060 return ConstantInt::get(GetCompareTy(LHS),
2061 !CmpInst::isTrueWhenEqual(Pred));
2062
Chandler Carruth8059c842012-03-25 21:28:14 +00002063 // We can only fold certain predicates on pointer comparisons.
2064 switch (Pred) {
2065 default:
Craig Topper9f008862014-04-15 04:59:12 +00002066 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002067
2068 // Equality comaprisons are easy to fold.
2069 case CmpInst::ICMP_EQ:
2070 case CmpInst::ICMP_NE:
2071 break;
2072
2073 // We can only handle unsigned relational comparisons because 'inbounds' on
2074 // a GEP only protects against unsigned wrapping.
2075 case CmpInst::ICMP_UGT:
2076 case CmpInst::ICMP_UGE:
2077 case CmpInst::ICMP_ULT:
2078 case CmpInst::ICMP_ULE:
2079 // However, we have to switch them to their signed variants to handle
2080 // negative indices from the base pointer.
2081 Pred = ICmpInst::getSignedPredicate(Pred);
2082 break;
2083 }
2084
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002085 // Strip off any constant offsets so that we can reason about them.
2086 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2087 // here and compare base addresses like AliasAnalysis does, however there are
2088 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2089 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2090 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002091 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2092 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002093
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002094 // If LHS and RHS are related via constant offsets to the same base
2095 // value, we can replace it with an icmp which just compares the offsets.
2096 if (LHS == RHS)
2097 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002098
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002099 // Various optimizations for (in)equality comparisons.
2100 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2101 // Different non-empty allocations that exist at the same time have
2102 // different addresses (if the program can tell). Global variables always
2103 // exist, so they always exist during the lifetime of each other and all
2104 // allocas. Two different allocas usually have different addresses...
2105 //
2106 // However, if there's an @llvm.stackrestore dynamically in between two
2107 // allocas, they may have the same address. It's tempting to reduce the
2108 // scope of the problem by only looking at *static* allocas here. That would
2109 // cover the majority of allocas while significantly reducing the likelihood
2110 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2111 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2112 // an entry block. Also, if we have a block that's not attached to a
2113 // function, we can't tell if it's "static" under the current definition.
2114 // Theoretically, this problem could be fixed by creating a new kind of
2115 // instruction kind specifically for static allocas. Such a new instruction
2116 // could be required to be at the top of the entry block, thus preventing it
2117 // from being subject to a @llvm.stackrestore. Instcombine could even
2118 // convert regular allocas into these special allocas. It'd be nifty.
2119 // However, until then, this problem remains open.
2120 //
2121 // So, we'll assume that two non-empty allocas have different addresses
2122 // for now.
2123 //
2124 // With all that, if the offsets are within the bounds of their allocations
2125 // (and not one-past-the-end! so we can't use inbounds!), and their
2126 // allocations aren't the same, the pointers are not equal.
2127 //
2128 // Note that it's not necessary to check for LHS being a global variable
2129 // address, due to canonicalization and constant folding.
2130 if (isa<AllocaInst>(LHS) &&
2131 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002132 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2133 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002134 uint64_t LHSSize, RHSSize;
Manoj Gupta77eeac32018-07-09 22:27:23 +00002135 ObjectSizeOpts Opts;
2136 Opts.NullIsUnknownSize =
2137 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002138 if (LHSOffsetCI && RHSOffsetCI &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00002139 getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2140 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002141 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2142 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002143 if (!LHSOffsetValue.isNegative() &&
2144 !RHSOffsetValue.isNegative() &&
2145 LHSOffsetValue.ult(LHSSize) &&
2146 RHSOffsetValue.ult(RHSSize)) {
2147 return ConstantInt::get(GetCompareTy(LHS),
2148 !CmpInst::isTrueWhenEqual(Pred));
2149 }
2150 }
2151
2152 // Repeat the above check but this time without depending on DataLayout
2153 // or being able to compute a precise size.
2154 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2155 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2156 LHSOffset->isNullValue() &&
2157 RHSOffset->isNullValue())
2158 return ConstantInt::get(GetCompareTy(LHS),
2159 !CmpInst::isTrueWhenEqual(Pred));
2160 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002161
2162 // Even if an non-inbounds GEP occurs along the path we can still optimize
2163 // equality comparisons concerning the result. We avoid walking the whole
2164 // chain again by starting where the last calls to
2165 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002166 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2167 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002168 if (LHS == RHS)
2169 return ConstantExpr::getICmp(Pred,
2170 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2171 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002172
2173 // If one side of the equality comparison must come from a noalias call
2174 // (meaning a system memory allocation function), and the other side must
2175 // come from a pointer that cannot overlap with dynamically-allocated
2176 // memory within the lifetime of the current function (allocas, byval
2177 // arguments, globals), then determine the comparison result here.
2178 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2179 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2180 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2181
2182 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002183 auto IsNAC = [](ArrayRef<Value *> Objects) {
2184 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002185 };
2186
2187 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002188 // noalias calls. For allocas, we consider only static ones (dynamic
2189 // allocas might be transformed into calls to malloc not simultaneously
2190 // live with the compared-to allocation). For globals, we exclude symbols
2191 // that might be resolve lazily to symbols in another dynamically-loaded
2192 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002193 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2194 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002195 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2196 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2197 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2198 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002199 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002200 !GV->isThreadLocal();
2201 if (const Argument *A = dyn_cast<Argument>(V))
2202 return A->hasByValAttr();
2203 return false;
2204 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002205 };
2206
2207 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2208 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2209 return ConstantInt::get(GetCompareTy(LHS),
2210 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002211
2212 // Fold comparisons for non-escaping pointer even if the allocation call
2213 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2214 // dynamic allocation call could be either of the operands.
2215 Value *MI = nullptr;
Nuno Lopes404f1062017-09-09 18:23:11 +00002216 if (isAllocLikeFn(LHS, TLI) &&
2217 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002218 MI = LHS;
Nuno Lopes404f1062017-09-09 18:23:11 +00002219 else if (isAllocLikeFn(RHS, TLI) &&
2220 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002221 MI = RHS;
2222 // FIXME: We should also fold the compare when the pointer escapes, but the
2223 // compare dominates the pointer escape
2224 if (MI && !PointerMayBeCaptured(MI, true, true))
2225 return ConstantInt::get(GetCompareTy(LHS),
2226 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002227 }
2228
2229 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002230 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002231}
Chris Lattner01990f02012-02-24 19:01:58 +00002232
Sanjay Pateldc65a272016-12-03 17:30:22 +00002233/// Fold an icmp when its operands have i1 scalar type.
2234static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002235 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002236 Type *ITy = GetCompareTy(LHS); // The return type.
2237 Type *OpTy = LHS->getType(); // The operand type.
Craig Topperfde47232017-07-09 07:04:03 +00002238 if (!OpTy->isIntOrIntVectorTy(1))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002239 return nullptr;
2240
Sanjay Patele2787b92017-05-17 20:27:55 +00002241 // A boolean compared to true/false can be simplified in 14 out of the 20
2242 // (10 predicates * 2 constants) possible combinations. Cases not handled here
2243 // require a 'not' of the LHS, so those must be transformed in InstCombine.
2244 if (match(RHS, m_Zero())) {
2245 switch (Pred) {
2246 case CmpInst::ICMP_NE: // X != 0 -> X
2247 case CmpInst::ICMP_UGT: // X >u 0 -> X
2248 case CmpInst::ICMP_SLT: // X <s 0 -> X
2249 return LHS;
2250
2251 case CmpInst::ICMP_ULT: // X <u 0 -> false
2252 case CmpInst::ICMP_SGT: // X >s 0 -> false
2253 return getFalse(ITy);
2254
2255 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2256 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2257 return getTrue(ITy);
2258
2259 default: break;
2260 }
2261 } else if (match(RHS, m_One())) {
2262 switch (Pred) {
2263 case CmpInst::ICMP_EQ: // X == 1 -> X
2264 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2265 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2266 return LHS;
2267
2268 case CmpInst::ICMP_UGT: // X >u 1 -> false
2269 case CmpInst::ICMP_SLT: // X <s -1 -> false
2270 return getFalse(ITy);
2271
2272 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2273 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2274 return getTrue(ITy);
2275
2276 default: break;
2277 }
2278 }
2279
Sanjay Pateldc65a272016-12-03 17:30:22 +00002280 switch (Pred) {
2281 default:
2282 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002283 case ICmpInst::ICMP_UGE:
Sanjay Pateldc65a272016-12-03 17:30:22 +00002284 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2285 return getTrue(ITy);
2286 break;
2287 case ICmpInst::ICMP_SGE:
2288 /// For signed comparison, the values for an i1 are 0 and -1
2289 /// respectively. This maps into a truth table of:
2290 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2291 /// 0 | 0 | 1 (0 >= 0) | 1
2292 /// 0 | 1 | 1 (0 >= -1) | 1
2293 /// 1 | 0 | 0 (-1 >= 0) | 0
2294 /// 1 | 1 | 1 (-1 >= -1) | 1
2295 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2296 return getTrue(ITy);
2297 break;
Sanjay Pateldc65a272016-12-03 17:30:22 +00002298 case ICmpInst::ICMP_ULE:
2299 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2300 return getTrue(ITy);
2301 break;
2302 }
2303
2304 return nullptr;
2305}
2306
2307/// Try hard to fold icmp with zero RHS because this is a common case.
2308static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002309 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002310 if (!match(RHS, m_Zero()))
2311 return nullptr;
2312
2313 Type *ITy = GetCompareTy(LHS); // The return type.
Sanjay Pateldc65a272016-12-03 17:30:22 +00002314 switch (Pred) {
2315 default:
2316 llvm_unreachable("Unknown ICmp predicate!");
2317 case ICmpInst::ICMP_ULT:
2318 return getFalse(ITy);
2319 case ICmpInst::ICMP_UGE:
2320 return getTrue(ITy);
2321 case ICmpInst::ICMP_EQ:
2322 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002323 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002324 return getFalse(ITy);
2325 break;
2326 case ICmpInst::ICMP_NE:
2327 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002328 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002329 return getTrue(ITy);
2330 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002331 case ICmpInst::ICMP_SLT: {
2332 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2333 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002334 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002335 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002336 return getFalse(ITy);
2337 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002338 }
2339 case ICmpInst::ICMP_SLE: {
2340 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2341 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002342 return getTrue(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002343 if (LHSKnown.isNonNegative() &&
2344 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002345 return getFalse(ITy);
2346 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002347 }
2348 case ICmpInst::ICMP_SGE: {
2349 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2350 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002351 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002352 if (LHSKnown.isNonNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002353 return getTrue(ITy);
2354 break;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002355 }
2356 case ICmpInst::ICMP_SGT: {
2357 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2358 if (LHSKnown.isNegative())
Sanjay Pateldc65a272016-12-03 17:30:22 +00002359 return getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002360 if (LHSKnown.isNonNegative() &&
2361 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002362 return getTrue(ITy);
2363 break;
2364 }
Craig Topper1a36b7d2017-05-15 06:39:41 +00002365 }
Sanjay Pateldc65a272016-12-03 17:30:22 +00002366
2367 return nullptr;
2368}
2369
Sanjay Patelbe332132017-01-23 18:22:26 +00002370/// Many binary operators with a constant operand have an easy-to-compute
2371/// range of outputs. This can be used to fold a comparison to always true or
2372/// always false.
2373static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2374 unsigned Width = Lower.getBitWidth();
2375 const APInt *C;
2376 switch (BO.getOpcode()) {
2377 case Instruction::Add:
Craig Topper73ba1c82017-06-07 07:40:37 +00002378 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
Sanjay Patel56227252017-01-24 17:03:24 +00002379 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2380 if (BO.hasNoUnsignedWrap()) {
2381 // 'add nuw x, C' produces [C, UINT_MAX].
2382 Lower = *C;
2383 } else if (BO.hasNoSignedWrap()) {
2384 if (C->isNegative()) {
2385 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2386 Lower = APInt::getSignedMinValue(Width);
2387 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2388 } else {
2389 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2390 Lower = APInt::getSignedMinValue(Width) + *C;
2391 Upper = APInt::getSignedMaxValue(Width) + 1;
2392 }
2393 }
2394 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002395 break;
2396
2397 case Instruction::And:
2398 if (match(BO.getOperand(1), m_APInt(C)))
2399 // 'and x, C' produces [0, C].
2400 Upper = *C + 1;
2401 break;
2402
2403 case Instruction::Or:
2404 if (match(BO.getOperand(1), m_APInt(C)))
2405 // 'or x, C' produces [C, UINT_MAX].
2406 Lower = *C;
2407 break;
2408
2409 case Instruction::AShr:
2410 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2411 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2412 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2413 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2414 } else if (match(BO.getOperand(0), m_APInt(C))) {
2415 unsigned ShiftAmount = Width - 1;
Craig Topper73ba1c82017-06-07 07:40:37 +00002416 if (!C->isNullValue() && BO.isExact())
Sanjay Patelbe332132017-01-23 18:22:26 +00002417 ShiftAmount = C->countTrailingZeros();
2418 if (C->isNegative()) {
2419 // 'ashr C, x' produces [C, C >> (Width-1)]
2420 Lower = *C;
2421 Upper = C->ashr(ShiftAmount) + 1;
2422 } else {
2423 // 'ashr C, x' produces [C >> (Width-1), C]
2424 Lower = C->ashr(ShiftAmount);
2425 Upper = *C + 1;
2426 }
2427 }
2428 break;
2429
2430 case Instruction::LShr:
2431 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2432 // 'lshr x, C' produces [0, UINT_MAX >> C].
2433 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2434 } else if (match(BO.getOperand(0), m_APInt(C))) {
2435 // 'lshr C, x' produces [C >> (Width-1), C].
2436 unsigned ShiftAmount = Width - 1;
Craig Topper73ba1c82017-06-07 07:40:37 +00002437 if (!C->isNullValue() && BO.isExact())
Sanjay Patelbe332132017-01-23 18:22:26 +00002438 ShiftAmount = C->countTrailingZeros();
2439 Lower = C->lshr(ShiftAmount);
2440 Upper = *C + 1;
2441 }
2442 break;
2443
2444 case Instruction::Shl:
2445 if (match(BO.getOperand(0), m_APInt(C))) {
2446 if (BO.hasNoUnsignedWrap()) {
2447 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2448 Lower = *C;
2449 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2450 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2451 if (C->isNegative()) {
2452 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2453 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2454 Lower = C->shl(ShiftAmount);
2455 Upper = *C + 1;
2456 } else {
2457 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2458 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2459 Lower = *C;
2460 Upper = C->shl(ShiftAmount) + 1;
2461 }
2462 }
2463 }
2464 break;
2465
2466 case Instruction::SDiv:
2467 if (match(BO.getOperand(1), m_APInt(C))) {
2468 APInt IntMin = APInt::getSignedMinValue(Width);
2469 APInt IntMax = APInt::getSignedMaxValue(Width);
2470 if (C->isAllOnesValue()) {
2471 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2472 // where C != -1 and C != 0 and C != 1
2473 Lower = IntMin + 1;
2474 Upper = IntMax + 1;
2475 } else if (C->countLeadingZeros() < Width - 1) {
2476 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2477 // where C != -1 and C != 0 and C != 1
2478 Lower = IntMin.sdiv(*C);
2479 Upper = IntMax.sdiv(*C);
2480 if (Lower.sgt(Upper))
2481 std::swap(Lower, Upper);
2482 Upper = Upper + 1;
2483 assert(Upper != Lower && "Upper part of range has wrapped!");
2484 }
2485 } else if (match(BO.getOperand(0), m_APInt(C))) {
2486 if (C->isMinSignedValue()) {
2487 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2488 Lower = *C;
2489 Upper = Lower.lshr(1) + 1;
2490 } else {
2491 // 'sdiv C, x' produces [-|C|, |C|].
2492 Upper = C->abs() + 1;
2493 Lower = (-Upper) + 1;
2494 }
2495 }
2496 break;
2497
2498 case Instruction::UDiv:
Craig Topper73ba1c82017-06-07 07:40:37 +00002499 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) {
Sanjay Patelbe332132017-01-23 18:22:26 +00002500 // 'udiv x, C' produces [0, UINT_MAX / C].
2501 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2502 } else if (match(BO.getOperand(0), m_APInt(C))) {
2503 // 'udiv C, x' produces [0, C].
2504 Upper = *C + 1;
2505 }
2506 break;
2507
2508 case Instruction::SRem:
2509 if (match(BO.getOperand(1), m_APInt(C))) {
2510 // 'srem x, C' produces (-|C|, |C|).
2511 Upper = C->abs();
2512 Lower = (-Upper) + 1;
2513 }
2514 break;
2515
2516 case Instruction::URem:
2517 if (match(BO.getOperand(1), m_APInt(C)))
2518 // 'urem x, C' produces [0, C).
2519 Upper = *C;
2520 break;
2521
2522 default:
2523 break;
2524 }
2525}
2526
Sanjay Patel67bde282016-08-22 23:12:02 +00002527static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2528 Value *RHS) {
Roman Lebedev0c43d722018-03-15 16:17:40 +00002529 Type *ITy = GetCompareTy(RHS); // The return type.
2530
Roman Lebedev6aca3352018-03-15 16:17:46 +00002531 Value *X;
2532 // Sign-bit checks can be optimized to true/false after unsigned
2533 // floating-point casts:
2534 // icmp slt (bitcast (uitofp X)), 0 --> false
2535 // icmp sgt (bitcast (uitofp X)), -1 --> true
2536 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2537 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2538 return ConstantInt::getFalse(ITy);
2539 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2540 return ConstantInt::getTrue(ITy);
2541 }
2542
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002543 const APInt *C;
2544 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002545 return nullptr;
2546
2547 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002548 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002549 if (RHS_CR.isEmptySet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002550 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002551 if (RHS_CR.isFullSet())
Roman Lebedev0c43d722018-03-15 16:17:40 +00002552 return ConstantInt::getTrue(ITy);
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002553
Sanjay Patelbe332132017-01-23 18:22:26 +00002554 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002555 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002556 APInt Lower = APInt(Width, 0);
2557 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002558 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2559 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002560
2561 ConstantRange LHS_CR =
2562 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2563
2564 if (auto *I = dyn_cast<Instruction>(LHS))
2565 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2566 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2567
2568 if (!LHS_CR.isFullSet()) {
2569 if (RHS_CR.contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002570 return ConstantInt::getTrue(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002571 if (RHS_CR.inverse().contains(LHS_CR))
Roman Lebedev0c43d722018-03-15 16:17:40 +00002572 return ConstantInt::getFalse(ITy);
Sanjay Patel67bde282016-08-22 23:12:02 +00002573 }
2574
2575 return nullptr;
2576}
2577
Sanjay Patel2df38a82017-05-08 16:21:55 +00002578/// TODO: A large part of this logic is duplicated in InstCombine's
2579/// foldICmpBinOp(). We should be able to share that and avoid the code
2580/// duplication.
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002581static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002582 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002583 unsigned MaxRecurse) {
2584 Type *ITy = GetCompareTy(LHS); // The return type.
2585
2586 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2587 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2588 if (MaxRecurse && (LBO || RBO)) {
2589 // Analyze the case when either LHS or RHS is an add instruction.
2590 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2591 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2592 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2593 if (LBO && LBO->getOpcode() == Instruction::Add) {
2594 A = LBO->getOperand(0);
2595 B = LBO->getOperand(1);
2596 NoLHSWrapProblem =
2597 ICmpInst::isEquality(Pred) ||
2598 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2599 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2600 }
2601 if (RBO && RBO->getOpcode() == Instruction::Add) {
2602 C = RBO->getOperand(0);
2603 D = RBO->getOperand(1);
2604 NoRHSWrapProblem =
2605 ICmpInst::isEquality(Pred) ||
2606 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2607 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2608 }
2609
2610 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2611 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2612 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2613 Constant::getNullValue(RHS->getType()), Q,
2614 MaxRecurse - 1))
2615 return V;
2616
2617 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2618 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2619 if (Value *V =
2620 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2621 C == LHS ? D : C, Q, MaxRecurse - 1))
2622 return V;
2623
2624 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2625 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2626 NoRHSWrapProblem) {
2627 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2628 Value *Y, *Z;
2629 if (A == C) {
2630 // C + B == C + D -> B == D
2631 Y = B;
2632 Z = D;
2633 } else if (A == D) {
2634 // D + B == C + D -> B == C
2635 Y = B;
2636 Z = C;
2637 } else if (B == C) {
2638 // A + C == C + D -> A == D
2639 Y = A;
2640 Z = D;
2641 } else {
2642 assert(B == D);
2643 // A + D == C + D -> A == C
2644 Y = A;
2645 Z = C;
2646 }
2647 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2648 return V;
2649 }
2650 }
2651
2652 {
2653 Value *Y = nullptr;
2654 // icmp pred (or X, Y), X
2655 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2656 if (Pred == ICmpInst::ICMP_ULT)
2657 return getFalse(ITy);
2658 if (Pred == ICmpInst::ICMP_UGE)
2659 return getTrue(ITy);
2660
2661 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002662 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2663 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2664 if (RHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002665 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002666 if (RHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002667 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2668 }
2669 }
2670 // icmp pred X, (or X, Y)
2671 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2672 if (Pred == ICmpInst::ICMP_ULE)
2673 return getTrue(ITy);
2674 if (Pred == ICmpInst::ICMP_UGT)
2675 return getFalse(ITy);
2676
2677 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
Craig Topper1a36b7d2017-05-15 06:39:41 +00002678 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2679 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2680 if (LHSKnown.isNonNegative() && YKnown.isNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002681 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
Craig Topper1a36b7d2017-05-15 06:39:41 +00002682 if (LHSKnown.isNegative() || YKnown.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002683 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2684 }
2685 }
2686 }
2687
2688 // icmp pred (and X, Y), X
Craig Topper72ee6942017-06-24 06:24:01 +00002689 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002690 if (Pred == ICmpInst::ICMP_UGT)
2691 return getFalse(ITy);
2692 if (Pred == ICmpInst::ICMP_ULE)
2693 return getTrue(ITy);
2694 }
2695 // icmp pred X, (and X, Y)
Craig Topper72ee6942017-06-24 06:24:01 +00002696 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002697 if (Pred == ICmpInst::ICMP_UGE)
2698 return getTrue(ITy);
2699 if (Pred == ICmpInst::ICMP_ULT)
2700 return getFalse(ITy);
2701 }
2702
2703 // 0 - (zext X) pred C
2704 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2705 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2706 if (RHSC->getValue().isStrictlyPositive()) {
2707 if (Pred == ICmpInst::ICMP_SLT)
2708 return ConstantInt::getTrue(RHSC->getContext());
2709 if (Pred == ICmpInst::ICMP_SGE)
2710 return ConstantInt::getFalse(RHSC->getContext());
2711 if (Pred == ICmpInst::ICMP_EQ)
2712 return ConstantInt::getFalse(RHSC->getContext());
2713 if (Pred == ICmpInst::ICMP_NE)
2714 return ConstantInt::getTrue(RHSC->getContext());
2715 }
2716 if (RHSC->getValue().isNonNegative()) {
2717 if (Pred == ICmpInst::ICMP_SLE)
2718 return ConstantInt::getTrue(RHSC->getContext());
2719 if (Pred == ICmpInst::ICMP_SGT)
2720 return ConstantInt::getFalse(RHSC->getContext());
2721 }
2722 }
2723 }
2724
2725 // icmp pred (urem X, Y), Y
2726 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002727 switch (Pred) {
2728 default:
2729 break;
2730 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002731 case ICmpInst::ICMP_SGE: {
2732 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2733 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002734 break;
2735 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002736 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002737 case ICmpInst::ICMP_EQ:
2738 case ICmpInst::ICMP_UGT:
2739 case ICmpInst::ICMP_UGE:
2740 return getFalse(ITy);
2741 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002742 case ICmpInst::ICMP_SLE: {
2743 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2744 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002745 break;
2746 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002747 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002748 case ICmpInst::ICMP_NE:
2749 case ICmpInst::ICMP_ULT:
2750 case ICmpInst::ICMP_ULE:
2751 return getTrue(ITy);
2752 }
2753 }
2754
2755 // icmp pred X, (urem Y, X)
2756 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002757 switch (Pred) {
2758 default:
2759 break;
2760 case ICmpInst::ICMP_SGT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002761 case ICmpInst::ICMP_SGE: {
2762 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2763 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002764 break;
2765 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002766 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002767 case ICmpInst::ICMP_NE:
2768 case ICmpInst::ICMP_UGT:
2769 case ICmpInst::ICMP_UGE:
2770 return getTrue(ITy);
2771 case ICmpInst::ICMP_SLT:
Craig Topper1a36b7d2017-05-15 06:39:41 +00002772 case ICmpInst::ICMP_SLE: {
2773 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2774 if (!Known.isNonNegative())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002775 break;
2776 LLVM_FALLTHROUGH;
Craig Topper1a36b7d2017-05-15 06:39:41 +00002777 }
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002778 case ICmpInst::ICMP_EQ:
2779 case ICmpInst::ICMP_ULT:
2780 case ICmpInst::ICMP_ULE:
2781 return getFalse(ITy);
2782 }
2783 }
2784
2785 // x >> y <=u x
2786 // x udiv y <=u x.
2787 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2788 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2789 // icmp pred (X op Y), X
2790 if (Pred == ICmpInst::ICMP_UGT)
2791 return getFalse(ITy);
2792 if (Pred == ICmpInst::ICMP_ULE)
2793 return getTrue(ITy);
2794 }
2795
2796 // x >=u x >> y
2797 // x >=u x udiv y.
2798 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2799 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2800 // icmp pred X, (X op Y)
2801 if (Pred == ICmpInst::ICMP_ULT)
2802 return getFalse(ITy);
2803 if (Pred == ICmpInst::ICMP_UGE)
2804 return getTrue(ITy);
2805 }
2806
2807 // handle:
2808 // CI2 << X == CI
2809 // CI2 << X != CI
2810 //
2811 // where CI2 is a power of 2 and CI isn't
2812 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2813 const APInt *CI2Val, *CIVal = &CI->getValue();
2814 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2815 CI2Val->isPowerOf2()) {
2816 if (!CIVal->isPowerOf2()) {
2817 // CI2 << X can equal zero in some circumstances,
2818 // this simplification is unsafe if CI is zero.
2819 //
2820 // We know it is safe if:
2821 // - The shift is nsw, we can't shift out the one bit.
2822 // - The shift is nuw, we can't shift out the one bit.
2823 // - CI2 is one
2824 // - CI isn't zero
2825 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
Craig Topper73ba1c82017-06-07 07:40:37 +00002826 CI2Val->isOneValue() || !CI->isZero()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002827 if (Pred == ICmpInst::ICMP_EQ)
2828 return ConstantInt::getFalse(RHS->getContext());
2829 if (Pred == ICmpInst::ICMP_NE)
2830 return ConstantInt::getTrue(RHS->getContext());
2831 }
2832 }
Craig Topper73ba1c82017-06-07 07:40:37 +00002833 if (CIVal->isSignMask() && CI2Val->isOneValue()) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002834 if (Pred == ICmpInst::ICMP_UGT)
2835 return ConstantInt::getFalse(RHS->getContext());
2836 if (Pred == ICmpInst::ICMP_ULE)
2837 return ConstantInt::getTrue(RHS->getContext());
2838 }
2839 }
2840 }
2841
2842 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2843 LBO->getOperand(1) == RBO->getOperand(1)) {
2844 switch (LBO->getOpcode()) {
2845 default:
2846 break;
2847 case Instruction::UDiv:
2848 case Instruction::LShr:
Sanjay Patela23b1412017-05-15 19:16:49 +00002849 if (ICmpInst::isSigned(Pred) || !LBO->isExact() || !RBO->isExact())
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002850 break;
Sanjay Patela23b1412017-05-15 19:16:49 +00002851 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2852 RBO->getOperand(0), Q, MaxRecurse - 1))
2853 return V;
2854 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002855 case Instruction::SDiv:
Sanjay Patela23b1412017-05-15 19:16:49 +00002856 if (!ICmpInst::isEquality(Pred) || !LBO->isExact() || !RBO->isExact())
2857 break;
2858 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2859 RBO->getOperand(0), Q, MaxRecurse - 1))
2860 return V;
2861 break;
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002862 case Instruction::AShr:
2863 if (!LBO->isExact() || !RBO->isExact())
2864 break;
2865 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2866 RBO->getOperand(0), Q, MaxRecurse - 1))
2867 return V;
2868 break;
2869 case Instruction::Shl: {
2870 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2871 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2872 if (!NUW && !NSW)
2873 break;
2874 if (!NSW && ICmpInst::isSigned(Pred))
2875 break;
2876 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2877 RBO->getOperand(0), Q, MaxRecurse - 1))
2878 return V;
2879 break;
2880 }
2881 }
2882 }
2883 return nullptr;
2884}
2885
Sanjay Patel35289c62016-12-10 17:40:47 +00002886/// Simplify integer comparisons where at least one operand of the compare
2887/// matches an integer min/max idiom.
2888static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002889 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel35289c62016-12-10 17:40:47 +00002890 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002891 Type *ITy = GetCompareTy(LHS); // The return type.
2892 Value *A, *B;
2893 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2894 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2895
2896 // Signed variants on "max(a,b)>=a -> true".
2897 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2898 if (A != RHS)
2899 std::swap(A, B); // smax(A, B) pred A.
2900 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2901 // We analyze this as smax(A, B) pred A.
2902 P = Pred;
2903 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2904 (A == LHS || B == LHS)) {
2905 if (A != LHS)
2906 std::swap(A, B); // A pred smax(A, B).
2907 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2908 // We analyze this as smax(A, B) swapped-pred A.
2909 P = CmpInst::getSwappedPredicate(Pred);
2910 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2911 (A == RHS || B == RHS)) {
2912 if (A != RHS)
2913 std::swap(A, B); // smin(A, B) pred A.
2914 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2915 // We analyze this as smax(-A, -B) swapped-pred -A.
2916 // Note that we do not need to actually form -A or -B thanks to EqP.
2917 P = CmpInst::getSwappedPredicate(Pred);
2918 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2919 (A == LHS || B == LHS)) {
2920 if (A != LHS)
2921 std::swap(A, B); // A pred smin(A, B).
2922 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2923 // We analyze this as smax(-A, -B) pred -A.
2924 // Note that we do not need to actually form -A or -B thanks to EqP.
2925 P = Pred;
2926 }
2927 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2928 // Cases correspond to "max(A, B) p A".
2929 switch (P) {
2930 default:
2931 break;
2932 case CmpInst::ICMP_EQ:
2933 case CmpInst::ICMP_SLE:
2934 // Equivalent to "A EqP B". This may be the same as the condition tested
2935 // in the max/min; if so, we can just return that.
2936 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2937 return V;
2938 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2939 return V;
2940 // Otherwise, see if "A EqP B" simplifies.
2941 if (MaxRecurse)
2942 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2943 return V;
2944 break;
2945 case CmpInst::ICMP_NE:
2946 case CmpInst::ICMP_SGT: {
2947 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2948 // Equivalent to "A InvEqP B". This may be the same as the condition
2949 // tested in the max/min; if so, we can just return that.
2950 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2951 return V;
2952 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2953 return V;
2954 // Otherwise, see if "A InvEqP B" simplifies.
2955 if (MaxRecurse)
2956 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2957 return V;
2958 break;
2959 }
2960 case CmpInst::ICMP_SGE:
2961 // Always true.
2962 return getTrue(ITy);
2963 case CmpInst::ICMP_SLT:
2964 // Always false.
2965 return getFalse(ITy);
2966 }
2967 }
2968
2969 // Unsigned variants on "max(a,b)>=a -> true".
2970 P = CmpInst::BAD_ICMP_PREDICATE;
2971 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2972 if (A != RHS)
2973 std::swap(A, B); // umax(A, B) pred A.
2974 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2975 // We analyze this as umax(A, B) pred A.
2976 P = Pred;
2977 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2978 (A == LHS || B == LHS)) {
2979 if (A != LHS)
2980 std::swap(A, B); // A pred umax(A, B).
2981 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2982 // We analyze this as umax(A, B) swapped-pred A.
2983 P = CmpInst::getSwappedPredicate(Pred);
2984 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2985 (A == RHS || B == RHS)) {
2986 if (A != RHS)
2987 std::swap(A, B); // umin(A, B) pred A.
2988 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2989 // We analyze this as umax(-A, -B) swapped-pred -A.
2990 // Note that we do not need to actually form -A or -B thanks to EqP.
2991 P = CmpInst::getSwappedPredicate(Pred);
2992 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2993 (A == LHS || B == LHS)) {
2994 if (A != LHS)
2995 std::swap(A, B); // A pred umin(A, B).
2996 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2997 // We analyze this as umax(-A, -B) pred -A.
2998 // Note that we do not need to actually form -A or -B thanks to EqP.
2999 P = Pred;
3000 }
3001 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3002 // Cases correspond to "max(A, B) p A".
3003 switch (P) {
3004 default:
3005 break;
3006 case CmpInst::ICMP_EQ:
3007 case CmpInst::ICMP_ULE:
3008 // Equivalent to "A EqP B". This may be the same as the condition tested
3009 // in the max/min; if so, we can just return that.
3010 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3011 return V;
3012 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3013 return V;
3014 // Otherwise, see if "A EqP B" simplifies.
3015 if (MaxRecurse)
3016 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3017 return V;
3018 break;
3019 case CmpInst::ICMP_NE:
3020 case CmpInst::ICMP_UGT: {
3021 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3022 // Equivalent to "A InvEqP B". This may be the same as the condition
3023 // tested in the max/min; if so, we can just return that.
3024 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3025 return V;
3026 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3027 return V;
3028 // Otherwise, see if "A InvEqP B" simplifies.
3029 if (MaxRecurse)
3030 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3031 return V;
3032 break;
3033 }
3034 case CmpInst::ICMP_UGE:
3035 // Always true.
3036 return getTrue(ITy);
3037 case CmpInst::ICMP_ULT:
3038 // Always false.
3039 return getFalse(ITy);
3040 }
3041 }
3042
3043 // Variants on "max(x,y) >= min(x,z)".
3044 Value *C, *D;
3045 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3046 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3047 (A == C || A == D || B == C || B == D)) {
3048 // max(x, ?) pred min(x, ?).
3049 if (Pred == CmpInst::ICMP_SGE)
3050 // Always true.
3051 return getTrue(ITy);
3052 if (Pred == CmpInst::ICMP_SLT)
3053 // Always false.
3054 return getFalse(ITy);
3055 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3056 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3057 (A == C || A == D || B == C || B == D)) {
3058 // min(x, ?) pred max(x, ?).
3059 if (Pred == CmpInst::ICMP_SLE)
3060 // Always true.
3061 return getTrue(ITy);
3062 if (Pred == CmpInst::ICMP_SGT)
3063 // Always false.
3064 return getFalse(ITy);
3065 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3066 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3067 (A == C || A == D || B == C || B == D)) {
3068 // max(x, ?) pred min(x, ?).
3069 if (Pred == CmpInst::ICMP_UGE)
3070 // Always true.
3071 return getTrue(ITy);
3072 if (Pred == CmpInst::ICMP_ULT)
3073 // Always false.
3074 return getFalse(ITy);
3075 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3076 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3077 (A == C || A == D || B == C || B == D)) {
3078 // min(x, ?) pred max(x, ?).
3079 if (Pred == CmpInst::ICMP_ULE)
3080 // Always true.
3081 return getTrue(ITy);
3082 if (Pred == CmpInst::ICMP_UGT)
3083 // Always false.
3084 return getFalse(ITy);
3085 }
3086
3087 return nullptr;
3088}
3089
Sanjay Patel472cc782016-01-11 22:14:42 +00003090/// Given operands for an ICmpInst, see if we can fold the result.
3091/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003092static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003093 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003094 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003095 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003096
Chris Lattnera71e9d62009-11-10 00:55:12 +00003097 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003098 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003099 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003100
3101 // If we have a constant, make sure it is on the RHS.
3102 std::swap(LHS, RHS);
3103 Pred = CmpInst::getSwappedPredicate(Pred);
3104 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003105
Chris Lattner229907c2011-07-18 04:54:35 +00003106 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003107
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003108 // icmp X, X -> true/false
Sanjay Patel30be6652018-04-22 17:07:44 +00003109 // icmp X, undef -> true/false because undef could be X.
Duncan Sands772749a2011-01-01 20:08:02 +00003110 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003111 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003112
Sanjay Pateldc65a272016-12-03 17:30:22 +00003113 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3114 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003115
Sanjay Pateldc65a272016-12-03 17:30:22 +00003116 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3117 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003118
Sanjay Patel67bde282016-08-22 23:12:02 +00003119 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3120 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003121
Chen Li7452d952015-09-26 03:26:47 +00003122 // If both operands have range metadata, use the metadata
3123 // to simplify the comparison.
3124 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
Craig Topper0c198612017-04-10 19:37:10 +00003125 auto RHS_Instr = cast<Instruction>(RHS);
3126 auto LHS_Instr = cast<Instruction>(LHS);
Chen Li7452d952015-09-26 03:26:47 +00003127
3128 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3129 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003130 auto RHS_CR = getConstantRangeFromMetadata(
3131 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3132 auto LHS_CR = getConstantRangeFromMetadata(
3133 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003134
3135 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3136 if (Satisfied_CR.contains(LHS_CR))
3137 return ConstantInt::getTrue(RHS->getContext());
3138
3139 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3140 CmpInst::getInversePredicate(Pred), RHS_CR);
3141 if (InversedSatisfied_CR.contains(LHS_CR))
3142 return ConstantInt::getFalse(RHS->getContext());
3143 }
3144 }
3145
Duncan Sands8fb2c382011-01-20 13:21:55 +00003146 // Compare of cast, for example (zext X) != 0 -> X != 0
3147 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3148 Instruction *LI = cast<CastInst>(LHS);
3149 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003150 Type *SrcTy = SrcOp->getType();
3151 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003152
3153 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3154 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003155 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3156 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003157 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3158 // Transfer the cast to the constant.
3159 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3160 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003161 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003162 return V;
3163 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3164 if (RI->getOperand(0)->getType() == SrcTy)
3165 // Compare without the cast.
3166 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003167 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003168 return V;
3169 }
3170 }
3171
3172 if (isa<ZExtInst>(LHS)) {
3173 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3174 // same type.
3175 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3176 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3177 // Compare X and Y. Note that signed predicates become unsigned.
3178 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003179 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003180 MaxRecurse-1))
3181 return V;
3182 }
3183 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3184 // too. If not, then try to deduce the result of the comparison.
3185 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3186 // Compute the constant that would happen if we truncated to SrcTy then
3187 // reextended to DstTy.
3188 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3189 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3190
3191 // If the re-extended constant didn't change then this is effectively
3192 // also a case of comparing two zero-extended values.
3193 if (RExt == CI && MaxRecurse)
3194 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003195 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003196 return V;
3197
3198 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3199 // there. Use this to work out the result of the comparison.
3200 if (RExt != CI) {
3201 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003202 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003203 // LHS <u RHS.
3204 case ICmpInst::ICMP_EQ:
3205 case ICmpInst::ICMP_UGT:
3206 case ICmpInst::ICMP_UGE:
3207 return ConstantInt::getFalse(CI->getContext());
3208
3209 case ICmpInst::ICMP_NE:
3210 case ICmpInst::ICMP_ULT:
3211 case ICmpInst::ICMP_ULE:
3212 return ConstantInt::getTrue(CI->getContext());
3213
3214 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3215 // is non-negative then LHS <s RHS.
3216 case ICmpInst::ICMP_SGT:
3217 case ICmpInst::ICMP_SGE:
3218 return CI->getValue().isNegative() ?
3219 ConstantInt::getTrue(CI->getContext()) :
3220 ConstantInt::getFalse(CI->getContext());
3221
3222 case ICmpInst::ICMP_SLT:
3223 case ICmpInst::ICMP_SLE:
3224 return CI->getValue().isNegative() ?
3225 ConstantInt::getFalse(CI->getContext()) :
3226 ConstantInt::getTrue(CI->getContext());
3227 }
3228 }
3229 }
3230 }
3231
3232 if (isa<SExtInst>(LHS)) {
3233 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3234 // same type.
3235 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3236 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3237 // Compare X and Y. Note that the predicate does not change.
3238 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003239 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003240 return V;
3241 }
3242 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3243 // too. If not, then try to deduce the result of the comparison.
3244 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3245 // Compute the constant that would happen if we truncated to SrcTy then
3246 // reextended to DstTy.
3247 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3248 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3249
3250 // If the re-extended constant didn't change then this is effectively
3251 // also a case of comparing two sign-extended values.
3252 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003253 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003254 return V;
3255
3256 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3257 // bits there. Use this to work out the result of the comparison.
3258 if (RExt != CI) {
3259 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003260 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003261 case ICmpInst::ICMP_EQ:
3262 return ConstantInt::getFalse(CI->getContext());
3263 case ICmpInst::ICMP_NE:
3264 return ConstantInt::getTrue(CI->getContext());
3265
3266 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3267 // LHS >s RHS.
3268 case ICmpInst::ICMP_SGT:
3269 case ICmpInst::ICMP_SGE:
3270 return CI->getValue().isNegative() ?
3271 ConstantInt::getTrue(CI->getContext()) :
3272 ConstantInt::getFalse(CI->getContext());
3273 case ICmpInst::ICMP_SLT:
3274 case ICmpInst::ICMP_SLE:
3275 return CI->getValue().isNegative() ?
3276 ConstantInt::getFalse(CI->getContext()) :
3277 ConstantInt::getTrue(CI->getContext());
3278
3279 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3280 // LHS >u RHS.
3281 case ICmpInst::ICMP_UGT:
3282 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003283 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003284 if (MaxRecurse)
3285 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3286 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003287 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003288 return V;
3289 break;
3290 case ICmpInst::ICMP_ULT:
3291 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003292 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003293 if (MaxRecurse)
3294 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3295 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003296 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003297 return V;
3298 break;
3299 }
3300 }
3301 }
3302 }
3303 }
3304
James Molloy1d88d6f2015-10-22 13:18:42 +00003305 // icmp eq|ne X, Y -> false|true if X != Y
Craig Topperc2790ec2017-06-06 07:13:04 +00003306 if (ICmpInst::isEquality(Pred) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003307 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
Craig Topper2dfb4802017-06-06 07:13:13 +00003308 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
James Molloy1d88d6f2015-10-22 13:18:42 +00003309 }
Junmo Park53470fc2016-04-05 21:14:31 +00003310
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003311 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3312 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003313
Sanjay Patel35289c62016-12-10 17:40:47 +00003314 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003315 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003316
Chandler Carruth8059c842012-03-25 21:28:14 +00003317 // Simplify comparisons of related pointers using a powerful, recursive
3318 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003319 if (LHS->getType()->isPointerTy())
Nuno Lopes404f1062017-09-09 18:23:11 +00003320 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, LHS,
3321 RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003322 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003323 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3324 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3325 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3326 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3327 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3328 Q.DL.getTypeSizeInBits(CRHS->getType()))
Nuno Lopes404f1062017-09-09 18:23:11 +00003329 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
David Majnemerdc8767a2016-08-07 07:58:10 +00003330 CLHS->getPointerOperand(),
3331 CRHS->getPointerOperand()))
3332 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003333
Nick Lewycky3db143e2012-02-26 02:09:49 +00003334 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3335 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3336 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3337 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3338 (ICmpInst::isEquality(Pred) ||
3339 (GLHS->isInBounds() && GRHS->isInBounds() &&
3340 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3341 // The bases are equal and the indices are constant. Build a constant
3342 // expression GEP with the same indices and a null base pointer to see
3343 // what constant folding can make out of it.
3344 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3345 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003346 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3347 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003348
3349 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003350 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3351 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003352 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3353 }
3354 }
3355 }
3356
Duncan Sandsf532d312010-11-07 16:12:23 +00003357 // If the comparison is with the result of a select instruction, check whether
3358 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003359 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003360 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003361 return V;
3362
3363 // If the comparison is with the result of a phi instruction, check whether
3364 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003365 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003366 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003367 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003368
Craig Topper9f008862014-04-15 04:59:12 +00003369 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003370}
3371
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003372Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003373 const SimplifyQuery &Q) {
3374 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3375}
3376
Sanjay Patel472cc782016-01-11 22:14:42 +00003377/// Given operands for an FCmpInst, see if we can fold the result.
3378/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003379static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003380 FastMathFlags FMF, const SimplifyQuery &Q,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003381 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003382 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3383 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3384
Chris Lattnera71e9d62009-11-10 00:55:12 +00003385 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003386 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003387 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003388
Chris Lattnera71e9d62009-11-10 00:55:12 +00003389 // If we have a constant, make sure it is on the RHS.
3390 std::swap(LHS, RHS);
3391 Pred = CmpInst::getSwappedPredicate(Pred);
3392 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003393
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003394 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003395 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003396 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003397 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003398 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003399 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003400
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003401 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3402 if (FMF.noNaNs()) {
3403 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003404 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003405 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003406 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003407 }
3408
Sanjay Patel46b083e2018-03-02 18:36:08 +00003409 // NaN is unordered; NaN is not ordered.
3410 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
3411 "Comparison must be either ordered or unordered");
3412 if (match(RHS, m_NaN()))
3413 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3414
Mehdi Aminieb242a52015-03-09 03:20:25 +00003415 // fcmp pred x, undef and fcmp pred undef, x
3416 // fold to true if unordered, false if ordered
3417 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3418 // Choosing NaN for the undef will always make unordered comparison succeed
3419 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003420 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003421 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003422
3423 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003424 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003425 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003426 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003427 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003428 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003429 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003430
Sanjay Patel4ca99682017-11-27 16:37:09 +00003431 // Handle fcmp with constant RHS.
3432 const APFloat *C;
3433 if (match(RHS, m_APFloat(C))) {
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003434 // Check whether the constant is an infinity.
Sanjay Patel4ca99682017-11-27 16:37:09 +00003435 if (C->isInfinity()) {
3436 if (C->isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003437 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003438 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003439 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003440 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003441 case FCmpInst::FCMP_UGE:
3442 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003443 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003444 default:
3445 break;
3446 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003447 } else {
3448 switch (Pred) {
3449 case FCmpInst::FCMP_OGT:
3450 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003451 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003452 case FCmpInst::FCMP_ULE:
3453 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003454 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003455 default:
3456 break;
3457 }
3458 }
3459 }
Sanjay Patel4ca99682017-11-27 16:37:09 +00003460 if (C->isZero()) {
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003461 switch (Pred) {
3462 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003463 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003464 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003465 break;
3466 case FCmpInst::FCMP_OLT:
3467 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003468 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003469 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003470 break;
3471 default:
3472 break;
3473 }
Florian Hahn30932a32017-12-01 12:34:16 +00003474 } else if (C->isNegative()) {
3475 assert(!C->isNaN() && "Unexpected NaN constant!");
3476 // TODO: We can catch more cases by using a range check rather than
3477 // relying on CannotBeOrderedLessThanZero.
3478 switch (Pred) {
3479 case FCmpInst::FCMP_UGE:
3480 case FCmpInst::FCMP_UGT:
3481 case FCmpInst::FCMP_UNE:
3482 // (X >= 0) implies (X > C) when (C < 0)
3483 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3484 return getTrue(RetTy);
3485 break;
3486 case FCmpInst::FCMP_OEQ:
3487 case FCmpInst::FCMP_OLE:
3488 case FCmpInst::FCMP_OLT:
3489 // (X >= 0) implies !(X < C) when (C < 0)
3490 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3491 return getFalse(RetTy);
3492 break;
3493 default:
3494 break;
3495 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003496 }
3497 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003498
Duncan Sandsa620bd12010-11-07 16:46:25 +00003499 // If the comparison is with the result of a select instruction, check whether
3500 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003501 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003502 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003503 return V;
3504
3505 // If the comparison is with the result of a phi instruction, check whether
3506 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003507 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003508 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003509 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003510
Craig Topper9f008862014-04-15 04:59:12 +00003511 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003512}
3513
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003514Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003515 FastMathFlags FMF, const SimplifyQuery &Q) {
3516 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003517}
3518
Sanjay Patel472cc782016-01-11 22:14:42 +00003519/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003520static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003521 const SimplifyQuery &Q,
David Majnemer3f0fb982015-06-06 22:40:21 +00003522 unsigned MaxRecurse) {
3523 // Trivial replacement.
3524 if (V == Op)
3525 return RepOp;
3526
Tim Northover997f5f12017-05-22 21:28:08 +00003527 // We cannot replace a constant, and shouldn't even try.
3528 if (isa<Constant>(Op))
3529 return nullptr;
3530
David Majnemer3f0fb982015-06-06 22:40:21 +00003531 auto *I = dyn_cast<Instruction>(V);
3532 if (!I)
3533 return nullptr;
3534
3535 // If this is a binary operator, try to simplify it with the replaced op.
3536 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3537 // Consider:
3538 // %cmp = icmp eq i32 %x, 2147483647
3539 // %add = add nsw i32 %x, 1
3540 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3541 //
3542 // We can't replace %sel with %add unless we strip away the flags.
3543 if (isa<OverflowingBinaryOperator>(B))
3544 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3545 return nullptr;
3546 if (isa<PossiblyExactOperator>(B))
3547 if (B->isExact())
3548 return nullptr;
3549
3550 if (MaxRecurse) {
3551 if (B->getOperand(0) == Op)
3552 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3553 MaxRecurse - 1);
3554 if (B->getOperand(1) == Op)
3555 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3556 MaxRecurse - 1);
3557 }
3558 }
3559
3560 // Same for CmpInsts.
3561 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3562 if (MaxRecurse) {
3563 if (C->getOperand(0) == Op)
3564 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3565 MaxRecurse - 1);
3566 if (C->getOperand(1) == Op)
3567 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3568 MaxRecurse - 1);
3569 }
3570 }
3571
George Burgess IV8e807bf2018-04-24 00:25:01 +00003572 // Same for GEPs.
3573 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3574 if (MaxRecurse) {
3575 SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3576 transform(GEP->operands(), NewOps.begin(),
3577 [&](Value *V) { return V == Op ? RepOp : V; });
3578 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3579 MaxRecurse - 1);
3580 }
3581 }
3582
David Majnemer3f0fb982015-06-06 22:40:21 +00003583 // TODO: We could hand off more cases to instsimplify here.
3584
3585 // If all operands are constant after substituting Op for RepOp then we can
3586 // constant fold the instruction.
3587 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3588 // Build a list of all constant operands.
3589 SmallVector<Constant *, 8> ConstOps;
3590 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3591 if (I->getOperand(i) == Op)
3592 ConstOps.push_back(CRepOp);
3593 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3594 ConstOps.push_back(COp);
3595 else
3596 break;
3597 }
3598
3599 // All operands were constants, fold it.
3600 if (ConstOps.size() == I->getNumOperands()) {
3601 if (CmpInst *C = dyn_cast<CmpInst>(I))
3602 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3603 ConstOps[1], Q.DL, Q.TLI);
3604
3605 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3606 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003607 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003608
Manuel Jacobe9024592016-01-21 06:33:22 +00003609 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003610 }
3611 }
3612
3613 return nullptr;
3614}
3615
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003616/// Try to simplify a select instruction when its condition operand is an
3617/// integer comparison where one operand of the compare is a constant.
3618static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3619 const APInt *Y, bool TrueWhenUnset) {
3620 const APInt *C;
3621
3622 // (X & Y) == 0 ? X & ~Y : X --> X
3623 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3624 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3625 *Y == ~*C)
3626 return TrueWhenUnset ? FalseVal : TrueVal;
3627
3628 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3629 // (X & Y) != 0 ? X : X & ~Y --> X
3630 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3631 *Y == ~*C)
3632 return TrueWhenUnset ? FalseVal : TrueVal;
3633
3634 if (Y->isPowerOf2()) {
3635 // (X & Y) == 0 ? X | Y : X --> X | Y
3636 // (X & Y) != 0 ? X | Y : X --> X
3637 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3638 *Y == *C)
3639 return TrueWhenUnset ? TrueVal : FalseVal;
3640
3641 // (X & Y) == 0 ? X : X | Y --> X
3642 // (X & Y) != 0 ? X : X | Y --> X | Y
3643 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3644 *Y == *C)
3645 return TrueWhenUnset ? TrueVal : FalseVal;
3646 }
Matt Arsenault82606662017-01-11 00:57:54 +00003647
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003648 return nullptr;
3649}
3650
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003651/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3652/// eq/ne.
Craig Topper0aa3a192017-08-14 21:39:51 +00003653static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
3654 ICmpInst::Predicate Pred,
3655 Value *TrueVal, Value *FalseVal) {
3656 Value *X;
3657 APInt Mask;
3658 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3659 return nullptr;
3660
Craig Topper0aa3a192017-08-14 21:39:51 +00003661 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3662 Pred == ICmpInst::ICMP_EQ);
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003663}
3664
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003665/// Try to simplify a select instruction when its condition operand is an
3666/// integer comparison.
3667static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003668 Value *FalseVal, const SimplifyQuery &Q,
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003669 unsigned MaxRecurse) {
3670 ICmpInst::Predicate Pred;
3671 Value *CmpLHS, *CmpRHS;
3672 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3673 return nullptr;
3674
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003675 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3676 Value *X;
3677 const APInt *Y;
3678 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3679 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3680 Pred == ICmpInst::ICMP_EQ))
3681 return V;
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003682 }
3683
Craig Topper0aa3a192017-08-14 21:39:51 +00003684 // Check for other compares that behave like bit test.
3685 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3686 TrueVal, FalseVal))
3687 return V;
3688
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003689 // If we have an equality comparison, then we know the value in one of the
3690 // arms of the select. See if substituting this value into the arm and
3691 // simplifying the result yields the same value as the other arm.
3692 if (Pred == ICmpInst::ICMP_EQ) {
3693 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3694 TrueVal ||
3695 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3696 TrueVal)
3697 return FalseVal;
3698 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3699 FalseVal ||
3700 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3701 FalseVal)
3702 return FalseVal;
3703 } else if (Pred == ICmpInst::ICMP_NE) {
3704 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3705 FalseVal ||
3706 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3707 FalseVal)
3708 return TrueVal;
3709 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3710 TrueVal ||
3711 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3712 TrueVal)
3713 return TrueVal;
3714 }
3715
3716 return nullptr;
3717}
3718
Sanjay Patel472cc782016-01-11 22:14:42 +00003719/// Given operands for a SelectInst, see if we can fold the result.
3720/// If not, this returns null.
Sanjay Patelac395202018-02-17 14:50:13 +00003721static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3722 const SimplifyQuery &Q, unsigned MaxRecurse) {
3723 if (auto *CondC = dyn_cast<Constant>(Cond)) {
3724 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3725 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3726 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3727
3728 // select undef, X, Y -> X or Y
3729 if (isa<UndefValue>(CondC))
3730 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3731
3732 // TODO: Vector constants with undef elements don't simplify.
3733
3734 // select true, X, Y -> X
3735 if (CondC->isAllOnesValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003736 return TrueVal;
Sanjay Patelac395202018-02-17 14:50:13 +00003737 // select false, X, Y -> Y
3738 if (CondC->isNullValue())
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003739 return FalseVal;
3740 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003741
Sanjay Patelac395202018-02-17 14:50:13 +00003742 // select ?, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003743 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003744 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003745
Sanjay Patelac395202018-02-17 14:50:13 +00003746 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00003747 return FalseVal;
Sanjay Patelac395202018-02-17 14:50:13 +00003748 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
Dan Gohman54664ed2011-07-01 01:03:43 +00003749 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003750
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003751 if (Value *V =
Sanjay Patelac395202018-02-17 14:50:13 +00003752 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003753 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003754
Craig Topper9f008862014-04-15 04:59:12 +00003755 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003756}
3757
Duncan Sandsb8cee002012-03-13 11:42:19 +00003758Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003759 const SimplifyQuery &Q) {
3760 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003761}
3762
Sanjay Patel472cc782016-01-11 22:14:42 +00003763/// Given operands for an GetElementPtrInst, see if we can fold the result.
3764/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003765static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003766 const SimplifyQuery &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003767 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003768 unsigned AS =
3769 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003770
Chris Lattner8574aba2009-11-27 00:29:05 +00003771 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003772 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003773 return Ops[0];
3774
Nico Weber48c82402014-08-27 20:06:19 +00003775 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003776 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003777 Type *GEPTy = PointerType::get(LastType, AS);
3778 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3779 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Davide Italianoa9f047a2017-04-19 14:23:42 +00003780 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3781 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Nico Weber48c82402014-08-27 20:06:19 +00003782
3783 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003784 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003785
Jay Foadb992a632011-07-19 15:07:52 +00003786 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003787 // getelementptr P, 0 -> P.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00003788 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003789 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003790
David Blaikie4a2e73b2015-04-02 18:55:32 +00003791 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003792 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003793 Value *P;
3794 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003795 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003796 // getelementptr P, N -> P if P points to a type of zero size.
Matthew Simpsonc1c4ad62018-03-15 16:00:29 +00003797 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003798 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003799
3800 // The following transforms are only safe if the ptrtoint cast
3801 // doesn't truncate the pointers.
3802 if (Ops[1]->getType()->getScalarSizeInBits() ==
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003803 Q.DL.getIndexSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003804 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3805 if (match(P, m_Zero()))
3806 return Constant::getNullValue(GEPTy);
3807 Value *Temp;
3808 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003809 if (Temp->getType() == GEPTy)
3810 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003811 return nullptr;
3812 };
3813
3814 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3815 if (TyAllocSize == 1 &&
3816 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3817 if (Value *R = PtrToIntOrZero(P))
3818 return R;
3819
3820 // getelementptr V, (ashr (sub P, V), C) -> Q
3821 // if P points to a type of size 1 << C.
3822 if (match(Ops[1],
3823 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3824 m_ConstantInt(C))) &&
3825 TyAllocSize == 1ULL << C)
3826 if (Value *R = PtrToIntOrZero(P))
3827 return R;
3828
3829 // getelementptr V, (sdiv (sub P, V), C) -> Q
3830 // if P points to a type of size C.
3831 if (match(Ops[1],
3832 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3833 m_SpecificInt(TyAllocSize))))
3834 if (Value *R = PtrToIntOrZero(P))
3835 return R;
3836 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003837 }
3838 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003839
David Majnemerd1501372016-08-07 07:58:12 +00003840 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3841 all_of(Ops.slice(1).drop_back(1),
3842 [](Value *Idx) { return match(Idx, m_Zero()); })) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003843 unsigned IdxWidth =
3844 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3845 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
3846 APInt BasePtrOffset(IdxWidth, 0);
David Majnemerd1501372016-08-07 07:58:12 +00003847 Value *StrippedBasePtr =
3848 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3849 BasePtrOffset);
3850
David Majnemer5c5df622016-08-16 06:13:46 +00003851 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003852 if (match(Ops.back(),
3853 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3854 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3855 return ConstantExpr::getIntToPtr(CI, GEPTy);
3856 }
David Majnemer5c5df622016-08-16 06:13:46 +00003857 // gep (gep V, C), (xor V, -1) -> C-1
3858 if (match(Ops.back(),
3859 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3860 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3861 return ConstantExpr::getIntToPtr(CI, GEPTy);
3862 }
David Majnemerd1501372016-08-07 07:58:12 +00003863 }
3864 }
3865
Chris Lattner8574aba2009-11-27 00:29:05 +00003866 // Check to see if this is constant foldable.
Craig Topperda8037f2017-06-04 22:41:56 +00003867 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
3868 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003869
Joey Gouly61eaa632017-06-06 10:17:14 +00003870 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3871 Ops.slice(1));
3872 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
3873 return CEFolded;
3874 return CE;
Chris Lattner8574aba2009-11-27 00:29:05 +00003875}
3876
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003877Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003878 const SimplifyQuery &Q) {
3879 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003880}
3881
Sanjay Patel472cc782016-01-11 22:14:42 +00003882/// Given operands for an InsertValueInst, see if we can fold the result.
3883/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003884static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003885 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003886 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003887 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3888 if (Constant *CVal = dyn_cast<Constant>(Val))
3889 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3890
3891 // insertvalue x, undef, n -> x
3892 if (match(Val, m_Undef()))
3893 return Agg;
3894
3895 // insertvalue x, (extractvalue y, n), n
3896 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003897 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3898 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003899 // insertvalue undef, (extractvalue y, n), n -> y
3900 if (match(Agg, m_Undef()))
3901 return EV->getAggregateOperand();
3902
3903 // insertvalue y, (extractvalue y, n), n -> y
3904 if (Agg == EV->getAggregateOperand())
3905 return Agg;
3906 }
3907
Craig Topper9f008862014-04-15 04:59:12 +00003908 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003909}
3910
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003911Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3912 ArrayRef<unsigned> Idxs,
3913 const SimplifyQuery &Q) {
3914 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3915}
3916
Igor Laevskye0edb662017-12-13 11:21:18 +00003917Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
3918 const SimplifyQuery &Q) {
3919 // Try to constant fold.
3920 auto *VecC = dyn_cast<Constant>(Vec);
3921 auto *ValC = dyn_cast<Constant>(Val);
3922 auto *IdxC = dyn_cast<Constant>(Idx);
3923 if (VecC && ValC && IdxC)
3924 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
3925
3926 // Fold into undef if index is out of bounds.
3927 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
3928 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
Igor Laevskye0edb662017-12-13 11:21:18 +00003929 if (CI->uge(NumElements))
3930 return UndefValue::get(Vec->getType());
3931 }
3932
Philip Reamese499bc32017-12-30 05:54:22 +00003933 // If index is undef, it might be out of bounds (see above case)
3934 if (isa<UndefValue>(Idx))
3935 return UndefValue::get(Vec->getType());
Igor Laevskye0edb662017-12-13 11:21:18 +00003936
3937 return nullptr;
3938}
3939
Sanjay Patel472cc782016-01-11 22:14:42 +00003940/// Given operands for an ExtractValueInst, see if we can fold the result.
3941/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003942static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003943 const SimplifyQuery &, unsigned) {
David Majnemer25a796e2015-07-13 01:15:46 +00003944 if (auto *CAgg = dyn_cast<Constant>(Agg))
3945 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3946
3947 // extractvalue x, (insertvalue y, elt, n), n -> elt
3948 unsigned NumIdxs = Idxs.size();
3949 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3950 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3951 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3952 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3953 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3954 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3955 Idxs.slice(0, NumCommonIdxs)) {
3956 if (NumIdxs == NumInsertValueIdxs)
3957 return IVI->getInsertedValueOperand();
3958 break;
3959 }
3960 }
3961
3962 return nullptr;
3963}
3964
3965Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003966 const SimplifyQuery &Q) {
3967 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
3968}
3969
Sanjay Patel472cc782016-01-11 22:14:42 +00003970/// Given operands for an ExtractElementInst, see if we can fold the result.
3971/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003972static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
David Majnemer599ca442015-07-13 01:15:53 +00003973 unsigned) {
3974 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3975 if (auto *CIdx = dyn_cast<Constant>(Idx))
3976 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3977
3978 // The index is not relevant if our vector is a splat.
3979 if (auto *Splat = CVec->getSplatValue())
3980 return Splat;
3981
3982 if (isa<UndefValue>(Vec))
3983 return UndefValue::get(Vec->getType()->getVectorElementType());
3984 }
3985
3986 // If extracting a specified index from the vector, see if we can recursively
3987 // find a previously computed scalar that was inserted into the vector.
Philip Reamese499bc32017-12-30 05:54:22 +00003988 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
3989 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
3990 // definitely out of bounds, thus undefined result
3991 return UndefValue::get(Vec->getType()->getVectorElementType());
3992 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3993 return Elt;
3994 }
David Majnemer599ca442015-07-13 01:15:53 +00003995
Zvi Rackover2e6e88f2017-12-06 17:51:46 +00003996 // An undef extract index can be arbitrarily chosen to be an out-of-range
3997 // index value, which would result in the instruction being undef.
3998 if (isa<UndefValue>(Idx))
3999 return UndefValue::get(Vec->getType()->getVectorElementType());
4000
David Majnemer599ca442015-07-13 01:15:53 +00004001 return nullptr;
4002}
4003
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004004Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
4005 const SimplifyQuery &Q) {
4006 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
4007}
4008
Sanjay Patel472cc782016-01-11 22:14:42 +00004009/// See if we can fold the given phi. If not, returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004010static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004011 // If all of the PHI's incoming values are the same then replace the PHI node
4012 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004013 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004014 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004015 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004016 // If the incoming value is the phi node itself, it can safely be skipped.
4017 if (Incoming == PN) continue;
4018 if (isa<UndefValue>(Incoming)) {
4019 // Remember that we saw an undef value, but otherwise ignore them.
4020 HasUndefInput = true;
4021 continue;
4022 }
4023 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004024 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004025 CommonValue = Incoming;
4026 }
4027
4028 // If CommonValue is null then all of the incoming values were either undef or
4029 // equal to the phi node itself.
4030 if (!CommonValue)
4031 return UndefValue::get(PN->getType());
4032
4033 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4034 // instruction, we cannot return X as the result of the PHI node unless it
4035 // dominates the PHI block.
4036 if (HasUndefInput)
Sanjay Patel5da361a2018-04-10 18:38:19 +00004037 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004038
4039 return CommonValue;
4040}
4041
David Majnemer6774d612016-07-26 17:58:05 +00004042static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004043 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004044 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004045 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004046
David Majnemer6774d612016-07-26 17:58:05 +00004047 if (auto *CI = dyn_cast<CastInst>(Op)) {
4048 auto *Src = CI->getOperand(0);
4049 Type *SrcTy = Src->getType();
4050 Type *MidTy = CI->getType();
4051 Type *DstTy = Ty;
4052 if (Src->getType() == Ty) {
4053 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4054 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4055 Type *SrcIntPtrTy =
4056 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4057 Type *MidIntPtrTy =
4058 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4059 Type *DstIntPtrTy =
4060 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4061 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4062 SrcIntPtrTy, MidIntPtrTy,
4063 DstIntPtrTy) == Instruction::BitCast)
4064 return Src;
4065 }
4066 }
David Majnemera90a6212016-07-26 05:52:29 +00004067
4068 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004069 if (CastOpc == Instruction::BitCast)
4070 if (Op->getType() == Ty)
4071 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004072
4073 return nullptr;
4074}
4075
David Majnemer6774d612016-07-26 17:58:05 +00004076Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004077 const SimplifyQuery &Q) {
4078 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4079}
4080
Sanjay Patela3c297d2017-04-19 16:48:22 +00004081/// For the given destination element of a shuffle, peek through shuffles to
4082/// match a root vector source operand that contains that element in the same
4083/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4084static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
Zvi Rackover558f86b2017-05-08 15:46:58 +00004085 int MaskVal, Value *RootVec,
Sanjay Patela3c297d2017-04-19 16:48:22 +00004086 unsigned MaxRecurse) {
4087 if (!MaxRecurse--)
4088 return nullptr;
4089
4090 // Bail out if any mask value is undefined. That kind of shuffle may be
4091 // simplified further based on demanded bits or other folds.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004092 if (MaskVal == -1)
4093 return nullptr;
4094
4095 // The mask value chooses which source operand we need to look at next.
Sanjay Patela3c297d2017-04-19 16:48:22 +00004096 int InVecNumElts = Op0->getType()->getVectorNumElements();
Zvi Rackover558f86b2017-05-08 15:46:58 +00004097 int RootElt = MaskVal;
4098 Value *SourceOp = Op0;
4099 if (MaskVal >= InVecNumElts) {
Sanjay Patela3c297d2017-04-19 16:48:22 +00004100 RootElt = MaskVal - InVecNumElts;
4101 SourceOp = Op1;
4102 }
4103
4104 // If the source operand is a shuffle itself, look through it to find the
4105 // matching root vector.
4106 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4107 return foldIdentityShuffles(
4108 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
Zvi Rackover558f86b2017-05-08 15:46:58 +00004109 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004110 }
4111
4112 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4113 // size?
4114
4115 // The source operand is not a shuffle. Initialize the root vector value for
4116 // this shuffle if that has not been done yet.
4117 if (!RootVec)
4118 RootVec = SourceOp;
4119
4120 // Give up as soon as a source operand does not match the existing root value.
4121 if (RootVec != SourceOp)
4122 return nullptr;
4123
4124 // The element must be coming from the same lane in the source vector
4125 // (although it may have crossed lanes in intermediate shuffles).
4126 if (RootElt != DestElt)
4127 return nullptr;
4128
4129 return RootVec;
4130}
4131
Zvi Rackover8f460652017-04-03 22:05:30 +00004132static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004133 Type *RetTy, const SimplifyQuery &Q,
Zvi Rackover8f460652017-04-03 22:05:30 +00004134 unsigned MaxRecurse) {
Zvi Rackover4086e132017-04-30 06:06:26 +00004135 if (isa<UndefValue>(Mask))
4136 return UndefValue::get(RetTy);
4137
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004138 Type *InVecTy = Op0->getType();
Zvi Rackover8f460652017-04-03 22:05:30 +00004139 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004140 unsigned InVecNumElts = InVecTy->getVectorNumElements();
Zvi Rackover8f460652017-04-03 22:05:30 +00004141
Zvi Rackover0411e462017-04-30 06:10:54 +00004142 SmallVector<int, 32> Indices;
4143 ShuffleVectorInst::getShuffleMask(Mask, Indices);
4144 assert(MaskNumElts == Indices.size() &&
4145 "Size of Indices not same as number of mask elements?");
4146
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004147 // Canonicalization: If mask does not select elements from an input vector,
4148 // replace that input vector with undef.
Zvi Rackover8f460652017-04-03 22:05:30 +00004149 bool MaskSelects0 = false, MaskSelects1 = false;
4150 for (unsigned i = 0; i != MaskNumElts; ++i) {
Zvi Rackover0411e462017-04-30 06:10:54 +00004151 if (Indices[i] == -1)
Zvi Rackover8f460652017-04-03 22:05:30 +00004152 continue;
Zvi Rackover0411e462017-04-30 06:10:54 +00004153 if ((unsigned)Indices[i] < InVecNumElts)
Zvi Rackover8f460652017-04-03 22:05:30 +00004154 MaskSelects0 = true;
4155 else
4156 MaskSelects1 = true;
4157 }
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004158 if (!MaskSelects0)
4159 Op0 = UndefValue::get(InVecTy);
4160 if (!MaskSelects1)
4161 Op1 = UndefValue::get(InVecTy);
4162
4163 auto *Op0Const = dyn_cast<Constant>(Op0);
4164 auto *Op1Const = dyn_cast<Constant>(Op1);
4165
4166 // If all operands are constant, constant fold the shuffle.
4167 if (Op0Const && Op1Const)
4168 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4169
4170 // Canonicalization: if only one input vector is constant, it shall be the
4171 // second one.
4172 if (Op0Const && !Op1Const) {
4173 std::swap(Op0, Op1);
Zvi Rackoverdfbd3d72017-05-08 12:40:18 +00004174 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004175 }
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004176
4177 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4178 // value type is same as the input vectors' type.
4179 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
Zvi Rackover973ff7c2017-05-07 18:16:37 +00004180 if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004181 OpShuf->getMask()->getSplatValue())
4182 return Op0;
Zvi Rackover8f460652017-04-03 22:05:30 +00004183
Sanjay Patela3c297d2017-04-19 16:48:22 +00004184 // Don't fold a shuffle with undef mask elements. This may get folded in a
4185 // better way using demanded bits or other analysis.
4186 // TODO: Should we allow this?
Zvi Rackover0411e462017-04-30 06:10:54 +00004187 if (find(Indices, -1) != Indices.end())
4188 return nullptr;
Sanjay Patela3c297d2017-04-19 16:48:22 +00004189
4190 // Check if every element of this shuffle can be mapped back to the
4191 // corresponding element of a single root vector. If so, we don't need this
4192 // shuffle. This handles simple identity shuffles as well as chains of
4193 // shuffles that may widen/narrow and/or move elements across lanes and back.
4194 Value *RootVec = nullptr;
4195 for (unsigned i = 0; i != MaskNumElts; ++i) {
4196 // Note that recursion is limited for each vector element, so if any element
4197 // exceeds the limit, this will fail to simplify.
Zvi Rackover558f86b2017-05-08 15:46:58 +00004198 RootVec =
4199 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
Sanjay Patela3c297d2017-04-19 16:48:22 +00004200
4201 // We can't replace a widening/narrowing shuffle with one of its operands.
4202 if (!RootVec || RootVec->getType() != RetTy)
4203 return nullptr;
4204 }
4205 return RootVec;
Zvi Rackover8f460652017-04-03 22:05:30 +00004206}
4207
4208/// Given operands for a ShuffleVectorInst, fold the result or return null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004209Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4210 Type *RetTy, const SimplifyQuery &Q) {
4211 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
Zvi Rackover8f460652017-04-03 22:05:30 +00004212}
4213
Sanjay Patele2359422018-03-21 19:31:53 +00004214static Constant *propagateNaN(Constant *In) {
4215 // If the input is a vector with undef elements, just return a default NaN.
4216 if (!In->isNaN())
4217 return ConstantFP::getNaN(In->getType());
4218
4219 // Propagate the existing NaN constant when possible.
4220 // TODO: Should we quiet a signaling NaN?
4221 return In;
4222}
4223
4224static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4225 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4226 return ConstantFP::getNaN(Op0->getType());
4227
4228 if (match(Op0, m_NaN()))
4229 return propagateNaN(cast<Constant>(Op0));
4230 if (match(Op1, m_NaN()))
4231 return propagateNaN(cast<Constant>(Op1));
4232
4233 return nullptr;
4234}
4235
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004236/// Given operands for an FAdd, see if we can fold the result. If not, this
4237/// returns null.
4238static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4239 const SimplifyQuery &Q, unsigned MaxRecurse) {
4240 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4241 return C;
4242
Sanjay Patele2359422018-03-21 19:31:53 +00004243 if (Constant *C = simplifyFPBinop(Op0, Op1))
4244 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004245
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004246 // fadd X, -0 ==> X
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004247 if (match(Op1, m_NegZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004248 return Op0;
4249
4250 // fadd X, 0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004251 if (match(Op1, m_PosZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004252 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4253 return Op0;
4254
Sanjay Patel11f7f992018-03-14 21:23:27 +00004255 // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant)
4256 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4257 // Negative zeros are allowed because we always end up with positive zero:
4258 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4259 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4260 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4261 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
Sanjay Patela4f42f22018-03-15 14:29:27 +00004262 if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4263 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))))
Sanjay Patel11f7f992018-03-14 21:23:27 +00004264 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004265
4266 return nullptr;
4267}
4268
4269/// Given operands for an FSub, see if we can fold the result. If not, this
4270/// returns null.
4271static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4272 const SimplifyQuery &Q, unsigned MaxRecurse) {
4273 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4274 return C;
4275
Sanjay Patele2359422018-03-21 19:31:53 +00004276 if (Constant *C = simplifyFPBinop(Op0, Op1))
4277 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004278
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004279 // fsub X, +0 ==> X
4280 if (match(Op1, m_PosZeroFP()))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004281 return Op0;
4282
4283 // fsub X, -0 ==> X, when we know X is not -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004284 if (match(Op1, m_NegZeroFP()) &&
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004285 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4286 return Op0;
4287
4288 // fsub -0.0, (fsub -0.0, X) ==> X
4289 Value *X;
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004290 if (match(Op0, m_NegZeroFP()) &&
4291 match(Op1, m_FSub(m_NegZeroFP(), m_Value(X))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004292 return X;
4293
4294 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Sanjay Patela4f42f22018-03-15 14:29:27 +00004295 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4296 match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))))
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004297 return X;
4298
4299 // fsub nnan x, x ==> 0.0
4300 if (FMF.noNaNs() && Op0 == Op1)
4301 return Constant::getNullValue(Op0->getType());
4302
4303 return nullptr;
4304}
4305
4306/// Given the operands for an FMul, see if we can fold the result
4307static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4308 const SimplifyQuery &Q, unsigned MaxRecurse) {
4309 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4310 return C;
4311
Sanjay Patele2359422018-03-21 19:31:53 +00004312 if (Constant *C = simplifyFPBinop(Op0, Op1))
4313 return C;
Sanjay Patel42227162018-03-10 16:51:28 +00004314
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004315 // fmul X, 1.0 ==> X
4316 if (match(Op1, m_FPOne()))
4317 return Op0;
4318
4319 // fmul nnan nsz X, 0 ==> 0
Sanjay Patela4f42f22018-03-15 14:29:27 +00004320 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4321 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004322
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004323 // sqrt(X) * sqrt(X) --> X, if we can:
4324 // 1. Remove the intermediate rounding (reassociate).
4325 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4326 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
Sanjay Pateldb53d182018-02-23 22:20:13 +00004327 Value *X;
Sanjay Patel95ec4a42018-03-18 14:12:25 +00004328 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4329 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
Sanjay Pateldb53d182018-02-23 22:20:13 +00004330 return X;
4331
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004332 return nullptr;
4333}
4334
4335Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4336 const SimplifyQuery &Q) {
4337 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4338}
4339
4340
4341Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4342 const SimplifyQuery &Q) {
4343 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4344}
4345
4346Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4347 const SimplifyQuery &Q) {
4348 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4349}
4350
4351static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4352 const SimplifyQuery &Q, unsigned) {
4353 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4354 return C;
4355
Sanjay Patele2359422018-03-21 19:31:53 +00004356 if (Constant *C = simplifyFPBinop(Op0, Op1))
4357 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004358
4359 // X / 1.0 -> X
4360 if (match(Op1, m_FPOne()))
4361 return Op0;
4362
4363 // 0 / X -> 0
4364 // Requires that NaNs are off (X could be zero) and signed zeroes are
4365 // ignored (X could be positive or negative, so the output sign is unknown).
Sanjay Patela4f42f22018-03-15 14:29:27 +00004366 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4367 return ConstantFP::getNullValue(Op0->getType());
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004368
4369 if (FMF.noNaNs()) {
4370 // X / X -> 1.0 is legal when NaNs are ignored.
Sanjay Patel83f05662018-01-30 00:18:37 +00004371 // We can ignore infinities because INF/INF is NaN.
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004372 if (Op0 == Op1)
4373 return ConstantFP::get(Op0->getType(), 1.0);
4374
Sanjay Patel83f05662018-01-30 00:18:37 +00004375 // (X * Y) / Y --> X if we can reassociate to the above form.
4376 Value *X;
4377 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4378 return X;
4379
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004380 // -X / X -> -1.0 and
4381 // X / -X -> -1.0 are legal when NaNs are ignored.
4382 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4383 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
4384 BinaryOperator::getFNegArgument(Op0) == Op1) ||
4385 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
4386 BinaryOperator::getFNegArgument(Op1) == Op0))
4387 return ConstantFP::get(Op0->getType(), -1.0);
4388 }
4389
4390 return nullptr;
4391}
4392
4393Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4394 const SimplifyQuery &Q) {
4395 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4396}
4397
4398static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4399 const SimplifyQuery &Q, unsigned) {
4400 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4401 return C;
4402
Sanjay Patele2359422018-03-21 19:31:53 +00004403 if (Constant *C = simplifyFPBinop(Op0, Op1))
4404 return C;
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004405
Sanjay Patel8f063d02018-03-15 14:04:31 +00004406 // Unlike fdiv, the result of frem always matches the sign of the dividend.
4407 // The constant match may include undef elements in a vector, so return a full
4408 // zero constant as the result.
4409 if (FMF.noNaNs()) {
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004410 // +0 % X -> 0
4411 if (match(Op0, m_PosZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004412 return ConstantFP::getNullValue(Op0->getType());
4413 // -0 % X -> -0
Sanjay Patel93e64dd2018-03-25 21:16:33 +00004414 if (match(Op0, m_NegZeroFP()))
Sanjay Patel8f063d02018-03-15 14:04:31 +00004415 return ConstantFP::getNegativeZero(Op0->getType());
4416 }
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004417
4418 return nullptr;
4419}
4420
4421Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
4422 const SimplifyQuery &Q) {
4423 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4424}
4425
Chris Lattnera71e9d62009-11-10 00:55:12 +00004426//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004427
Sanjay Patel472cc782016-01-11 22:14:42 +00004428/// Given operands for a BinaryOperator, see if we can fold the result.
4429/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004430static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004431 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004432 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004433 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004434 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004435 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004436 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004437 case Instruction::Mul:
4438 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004439 case Instruction::SDiv:
4440 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4441 case Instruction::UDiv:
4442 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004443 case Instruction::SRem:
4444 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4445 case Instruction::URem:
4446 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004447 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004448 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004449 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004450 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004451 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004452 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4453 case Instruction::And:
4454 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4455 case Instruction::Or:
4456 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4457 case Instruction::Xor:
4458 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Sanjay Patelfa877fd2017-09-11 13:34:27 +00004459 case Instruction::FAdd:
4460 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4461 case Instruction::FSub:
4462 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4463 case Instruction::FMul:
4464 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4465 case Instruction::FDiv:
4466 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4467 case Instruction::FRem:
4468 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004469 default:
Craig Topper8ef20ea2017-04-06 18:59:08 +00004470 llvm_unreachable("Unexpected opcode");
Chris Lattnera71e9d62009-11-10 00:55:12 +00004471 }
4472}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004473
Sanjay Patel472cc782016-01-11 22:14:42 +00004474/// Given operands for a BinaryOperator, see if we can fold the result.
4475/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004476/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4477/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4478static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004479 const FastMathFlags &FMF, const SimplifyQuery &Q,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004480 unsigned MaxRecurse) {
4481 switch (Opcode) {
4482 case Instruction::FAdd:
4483 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4484 case Instruction::FSub:
4485 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4486 case Instruction::FMul:
4487 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004488 case Instruction::FDiv:
4489 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004490 default:
4491 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4492 }
4493}
4494
Duncan Sands7e800d62010-11-14 11:23:23 +00004495Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004496 const SimplifyQuery &Q) {
4497 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4498}
4499
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004500Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berline8d74dc2017-04-26 04:10:00 +00004501 FastMathFlags FMF, const SimplifyQuery &Q) {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004502 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4503}
4504
Sanjay Patel472cc782016-01-11 22:14:42 +00004505/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004506static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004507 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004508 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004509 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004510 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004511}
4512
4513Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004514 const SimplifyQuery &Q) {
4515 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4516}
4517
Michael Ilseman54857292013-02-07 19:26:05 +00004518static bool IsIdempotent(Intrinsic::ID ID) {
4519 switch (ID) {
4520 default: return false;
4521
4522 // Unary idempotent: f(f(x)) = f(x)
4523 case Intrinsic::fabs:
4524 case Intrinsic::floor:
4525 case Intrinsic::ceil:
4526 case Intrinsic::trunc:
4527 case Intrinsic::rint:
4528 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004529 case Intrinsic::round:
Matt Arsenault3ced3d92017-09-07 01:21:43 +00004530 case Intrinsic::canonicalize:
Michael Ilseman54857292013-02-07 19:26:05 +00004531 return true;
4532 }
4533}
4534
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004535static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4536 const DataLayout &DL) {
4537 GlobalValue *PtrSym;
4538 APInt PtrOffset;
4539 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4540 return nullptr;
4541
4542 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4543 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4544 Type *Int32PtrTy = Int32Ty->getPointerTo();
4545 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4546
4547 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4548 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4549 return nullptr;
4550
4551 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4552 if (OffsetInt % 4 != 0)
4553 return nullptr;
4554
4555 Constant *C = ConstantExpr::getGetElementPtr(
4556 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4557 ConstantInt::get(Int64Ty, OffsetInt / 4));
4558 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4559 if (!Loaded)
4560 return nullptr;
4561
4562 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4563 if (!LoadedCE)
4564 return nullptr;
4565
4566 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4567 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4568 if (!LoadedCE)
4569 return nullptr;
4570 }
4571
4572 if (LoadedCE->getOpcode() != Instruction::Sub)
4573 return nullptr;
4574
4575 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4576 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4577 return nullptr;
4578 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4579
4580 Constant *LoadedRHS = LoadedCE->getOperand(1);
4581 GlobalValue *LoadedRHSSym;
4582 APInt LoadedRHSOffset;
4583 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4584 DL) ||
4585 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4586 return nullptr;
4587
4588 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4589}
4590
David Majnemer17a95aa2016-07-14 06:58:37 +00004591static bool maskIsAllZeroOrUndef(Value *Mask) {
4592 auto *ConstMask = dyn_cast<Constant>(Mask);
4593 if (!ConstMask)
4594 return false;
4595 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4596 return true;
4597 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4598 ++I) {
4599 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4600 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4601 continue;
4602 return false;
4603 }
4604 return true;
4605}
4606
Michael Ilseman54857292013-02-07 19:26:05 +00004607template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004608static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004609 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004610 Intrinsic::ID IID = F->getIntrinsicID();
4611 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004612
4613 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004614 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004615 // Perform idempotent optimizations
4616 if (IsIdempotent(IID)) {
4617 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4618 if (II->getIntrinsicID() == IID)
4619 return II;
4620 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004621 }
4622
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004623 Value *IIOperand = *ArgBegin;
4624 Value *X;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004625 switch (IID) {
4626 case Intrinsic::fabs: {
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004627 if (SignBitMustBeZero(IIOperand, Q.TLI))
4628 return IIOperand;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004629 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004630 }
Philip Reames5000ba62017-12-27 01:14:30 +00004631 case Intrinsic::bswap: {
Philip Reames5000ba62017-12-27 01:14:30 +00004632 // bswap(bswap(x)) -> x
4633 if (match(IIOperand, m_BSwap(m_Value(X))))
4634 return X;
4635 return nullptr;
4636 }
4637 case Intrinsic::bitreverse: {
Philip Reames5000ba62017-12-27 01:14:30 +00004638 // bitreverse(bitreverse(x)) -> x
4639 if (match(IIOperand, m_BitReverse(m_Value(X))))
4640 return X;
4641 return nullptr;
4642 }
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004643 case Intrinsic::exp: {
4644 // exp(log(x)) -> x
Sanjay Patel246d76922018-02-12 23:51:23 +00004645 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004646 match(IIOperand, m_Intrinsic<Intrinsic::log>(m_Value(X))))
4647 return X;
4648 return nullptr;
4649 }
4650 case Intrinsic::exp2: {
4651 // exp2(log2(x)) -> x
Sanjay Patel246d76922018-02-12 23:51:23 +00004652 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004653 match(IIOperand, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
4654 return X;
4655 return nullptr;
4656 }
4657 case Intrinsic::log: {
4658 // log(exp(x)) -> x
Sanjay Patel246d76922018-02-12 23:51:23 +00004659 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004660 match(IIOperand, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
4661 return X;
4662 return nullptr;
4663 }
4664 case Intrinsic::log2: {
4665 // log2(exp2(x)) -> x
Sanjay Patel246d76922018-02-12 23:51:23 +00004666 if (Q.CxtI->hasAllowReassoc() &&
Dmitry Venikov3d8cd342018-01-03 14:37:42 +00004667 match(IIOperand, m_Intrinsic<Intrinsic::exp2>(m_Value(X)))) {
4668 return X;
4669 }
4670 return nullptr;
4671 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004672 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004673 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004674 }
4675 }
Michael Ilseman54857292013-02-07 19:26:05 +00004676
Matt Arsenault82606662017-01-11 00:57:54 +00004677 // Binary Ops
4678 if (NumOperands == 2) {
4679 Value *LHS = *ArgBegin;
4680 Value *RHS = *(ArgBegin + 1);
4681 Type *ReturnType = F->getReturnType();
4682
4683 switch (IID) {
4684 case Intrinsic::usub_with_overflow:
4685 case Intrinsic::ssub_with_overflow: {
4686 // X - X -> { 0, false }
4687 if (LHS == RHS)
4688 return Constant::getNullValue(ReturnType);
4689
4690 // X - undef -> undef
4691 // undef - X -> undef
4692 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4693 return UndefValue::get(ReturnType);
4694
4695 return nullptr;
4696 }
4697 case Intrinsic::uadd_with_overflow:
4698 case Intrinsic::sadd_with_overflow: {
4699 // X + undef -> undef
Craig Topper77e07cc2017-05-24 17:05:28 +00004700 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
Matt Arsenault82606662017-01-11 00:57:54 +00004701 return UndefValue::get(ReturnType);
4702
4703 return nullptr;
4704 }
4705 case Intrinsic::umul_with_overflow:
4706 case Intrinsic::smul_with_overflow: {
Craig Topper77e07cc2017-05-24 17:05:28 +00004707 // 0 * X -> { 0, false }
Matt Arsenault82606662017-01-11 00:57:54 +00004708 // X * 0 -> { 0, false }
Craig Topper77e07cc2017-05-24 17:05:28 +00004709 if (match(LHS, m_Zero()) || match(RHS, m_Zero()))
Matt Arsenault82606662017-01-11 00:57:54 +00004710 return Constant::getNullValue(ReturnType);
4711
Craig Topper77e07cc2017-05-24 17:05:28 +00004712 // undef * X -> { 0, false }
Matt Arsenault82606662017-01-11 00:57:54 +00004713 // X * undef -> { 0, false }
Craig Topper77e07cc2017-05-24 17:05:28 +00004714 if (match(LHS, m_Undef()) || match(RHS, m_Undef()))
Matt Arsenault82606662017-01-11 00:57:54 +00004715 return Constant::getNullValue(ReturnType);
4716
4717 return nullptr;
4718 }
4719 case Intrinsic::load_relative: {
4720 Constant *C0 = dyn_cast<Constant>(LHS);
4721 Constant *C1 = dyn_cast<Constant>(RHS);
4722 if (C0 && C1)
4723 return SimplifyRelativeLoad(C0, C1, Q.DL);
4724 return nullptr;
4725 }
Philip Reames5000ba62017-12-27 01:14:30 +00004726 case Intrinsic::powi:
4727 if (ConstantInt *Power = dyn_cast<ConstantInt>(RHS)) {
4728 // powi(x, 0) -> 1.0
4729 if (Power->isZero())
4730 return ConstantFP::get(LHS->getType(), 1.0);
4731 // powi(x, 1) -> x
4732 if (Power->isOne())
4733 return LHS;
4734 }
4735 return nullptr;
Sanjay Patel92d0c1c122018-07-15 14:52:16 +00004736 case Intrinsic::maxnum:
4737 case Intrinsic::minnum:
4738 // If one argument is NaN, return the other argument.
4739 if (match(LHS, m_NaN()))
4740 return RHS;
4741 if (match(RHS, m_NaN()))
4742 return LHS;
4743 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00004744 default:
4745 return nullptr;
4746 }
4747 }
4748
4749 // Simplify calls to llvm.masked.load.*
4750 switch (IID) {
4751 case Intrinsic::masked_load: {
4752 Value *MaskArg = ArgBegin[2];
4753 Value *PassthruArg = ArgBegin[3];
4754 // If the mask is all zeros or undef, the "passthru" argument is the result.
4755 if (maskIsAllZeroOrUndef(MaskArg))
4756 return PassthruArg;
4757 return nullptr;
4758 }
4759 default:
4760 return nullptr;
4761 }
Michael Ilseman54857292013-02-07 19:26:05 +00004762}
4763
Chandler Carruth9dc35582012-12-28 11:30:55 +00004764template <typename IterTy>
Andrew Kaylor647025f2017-06-09 23:18:11 +00004765static Value *SimplifyCall(ImmutableCallSite CS, Value *V, IterTy ArgBegin,
4766 IterTy ArgEnd, const SimplifyQuery &Q,
4767 unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004768 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004769 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4770 Ty = PTy->getElementType();
4771 FunctionType *FTy = cast<FunctionType>(Ty);
4772
Dan Gohman85977e62011-11-04 18:32:42 +00004773 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004774 // call null -> undef
4775 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004776 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004777
Chandler Carruthf6182152012-12-28 14:23:29 +00004778 Function *F = dyn_cast<Function>(V);
4779 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004780 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004781
David Majnemer15032582015-05-22 03:56:46 +00004782 if (F->isIntrinsic())
4783 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004784 return Ret;
4785
Andrew Kaylor647025f2017-06-09 23:18:11 +00004786 if (!canConstantFoldCallTo(CS, F))
Craig Topper9f008862014-04-15 04:59:12 +00004787 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004788
4789 SmallVector<Constant *, 4> ConstantArgs;
4790 ConstantArgs.reserve(ArgEnd - ArgBegin);
4791 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4792 Constant *C = dyn_cast<Constant>(*I);
4793 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004794 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004795 ConstantArgs.push_back(C);
4796 }
4797
Andrew Kaylor647025f2017-06-09 23:18:11 +00004798 return ConstantFoldCall(CS, F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004799}
4800
Andrew Kaylor647025f2017-06-09 23:18:11 +00004801Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
4802 User::op_iterator ArgBegin, User::op_iterator ArgEnd,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004803 const SimplifyQuery &Q) {
Andrew Kaylor647025f2017-06-09 23:18:11 +00004804 return ::SimplifyCall(CS, V, ArgBegin, ArgEnd, Q, RecursionLimit);
4805}
4806
4807Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V,
4808 ArrayRef<Value *> Args, const SimplifyQuery &Q) {
4809 return ::SimplifyCall(CS, V, Args.begin(), Args.end(), Q, RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004810}
4811
Philip Reames7a6db4f2017-12-27 00:16:12 +00004812Value *llvm::SimplifyCall(ImmutableCallSite ICS, const SimplifyQuery &Q) {
4813 CallSite CS(const_cast<Instruction*>(ICS.getInstruction()));
4814 return ::SimplifyCall(CS, CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
4815 Q, RecursionLimit);
4816}
4817
Sanjay Patel472cc782016-01-11 22:14:42 +00004818/// See if we can compute a simplified version of this instruction.
4819/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004820
Daniel Berlin4d0fe642017-04-28 19:55:38 +00004821Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004822 OptimizationRemarkEmitter *ORE) {
Daniel Berlin4d0fe642017-04-28 19:55:38 +00004823 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004824 Value *Result;
4825
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004826 switch (I->getOpcode()) {
4827 default:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004828 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004829 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004830 case Instruction::FAdd:
4831 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004832 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004833 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004834 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004835 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4836 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004837 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004838 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004839 case Instruction::FSub:
4840 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004841 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004842 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004843 case Instruction::Sub:
4844 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4845 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004846 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004847 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004848 case Instruction::FMul:
4849 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004850 I->getFastMathFlags(), Q);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004851 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004852 case Instruction::Mul:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004853 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004854 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004855 case Instruction::SDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004856 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00004857 break;
4858 case Instruction::UDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004859 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00004860 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004861 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004862 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004863 I->getFastMathFlags(), Q);
Frits van Bommelc2549662011-01-29 15:26:31 +00004864 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004865 case Instruction::SRem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004866 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004867 break;
4868 case Instruction::URem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004869 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004870 break;
4871 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004872 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004873 I->getFastMathFlags(), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004874 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004875 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004876 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4877 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004878 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004879 break;
4880 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004881 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004882 cast<BinaryOperator>(I)->isExact(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004883 break;
4884 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004885 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004886 cast<BinaryOperator>(I)->isExact(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004887 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004888 case Instruction::And:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004889 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004890 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004891 case Instruction::Or:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004892 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004893 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004894 case Instruction::Xor:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004895 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004896 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004897 case Instruction::ICmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004898 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
4899 I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004900 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004901 case Instruction::FCmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004902 Result =
4903 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
4904 I->getOperand(1), I->getFastMathFlags(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004905 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004906 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004907 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004908 I->getOperand(2), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004909 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004910 case Instruction::GetElementPtr: {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004911 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004912 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004913 Ops, Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004914 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004915 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004916 case Instruction::InsertValue: {
4917 InsertValueInst *IV = cast<InsertValueInst>(I);
4918 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4919 IV->getInsertedValueOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004920 IV->getIndices(), Q);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004921 break;
4922 }
Igor Laevskye0edb662017-12-13 11:21:18 +00004923 case Instruction::InsertElement: {
4924 auto *IE = cast<InsertElementInst>(I);
4925 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1),
4926 IE->getOperand(2), Q);
4927 break;
4928 }
David Majnemer25a796e2015-07-13 01:15:46 +00004929 case Instruction::ExtractValue: {
4930 auto *EVI = cast<ExtractValueInst>(I);
4931 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004932 EVI->getIndices(), Q);
David Majnemer25a796e2015-07-13 01:15:46 +00004933 break;
4934 }
David Majnemer599ca442015-07-13 01:15:53 +00004935 case Instruction::ExtractElement: {
4936 auto *EEI = cast<ExtractElementInst>(I);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004937 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
4938 EEI->getIndexOperand(), Q);
David Majnemer599ca442015-07-13 01:15:53 +00004939 break;
4940 }
Zvi Rackover8f460652017-04-03 22:05:30 +00004941 case Instruction::ShuffleVector: {
4942 auto *SVI = cast<ShuffleVectorInst>(I);
4943 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004944 SVI->getMask(), SVI->getType(), Q);
Zvi Rackover8f460652017-04-03 22:05:30 +00004945 break;
4946 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004947 case Instruction::PHI:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004948 Result = SimplifyPHINode(cast<PHINode>(I), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004949 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004950 case Instruction::Call: {
4951 CallSite CS(cast<CallInst>(I));
Philip Reames7a6db4f2017-12-27 00:16:12 +00004952 Result = SimplifyCall(CS, Q);
Dan Gohman85977e62011-11-04 18:32:42 +00004953 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004954 }
David Majnemer6774d612016-07-26 17:58:05 +00004955#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4956#include "llvm/IR/Instruction.def"
4957#undef HANDLE_CAST_INST
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004958 Result =
4959 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
David Majnemera90a6212016-07-26 05:52:29 +00004960 break;
Craig Topper81c03a72017-04-12 22:54:24 +00004961 case Instruction::Alloca:
4962 // No simplifications for Alloca and it can't be constant folded.
4963 Result = nullptr;
4964 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004965 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004966
Hal Finkelf2199b22015-10-23 20:37:08 +00004967 // In general, it is possible for computeKnownBits to determine all bits in a
4968 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004969 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00004970 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
Craig Topper8189a872017-05-03 23:12:29 +00004971 if (Known.isConstant())
4972 Result = ConstantInt::get(I->getType(), Known.getConstant());
Hal Finkelf2199b22015-10-23 20:37:08 +00004973 }
4974
Duncan Sands64e41cf2010-11-17 08:35:29 +00004975 /// If called on unreachable code, the above logic may report that the
4976 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004977 /// detecting that case here, returning a safe value instead.
4978 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004979}
4980
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004981/// Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004982/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004983///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004984/// This is the common implementation of the recursive simplification routines.
4985/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4986/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4987/// instructions to process and attempt to simplify it using
4988/// InstructionSimplify.
4989///
4990/// This routine returns 'true' only when *it* simplifies something. The passed
4991/// in simplified value does not count toward this.
4992static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004993 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004994 const DominatorTree *DT,
4995 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004996 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004997 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004998 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004999
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005000 // If we have an explicit value to collapse to, do that round of the
5001 // simplification loop by hand initially.
5002 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00005003 for (User *U : I->users())
5004 if (U != I)
5005 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00005006
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005007 // Replace the instruction with its simplified value.
5008 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00005009
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005010 // Gracefully handle edge cases where the instruction is not wired into any
5011 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00005012 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
5013 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005014 I->eraseFromParent();
5015 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005016 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00005017 }
Duncan Sands7e800d62010-11-14 11:23:23 +00005018
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00005019 // Note that we must test the size on each iteration, the worklist can grow.
5020 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
5021 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00005022
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005023 // See if this instruction simplifies.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005024 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC});
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005025 if (!SimpleV)
5026 continue;
5027
5028 Simplified = true;
5029
5030 // Stash away all the uses of the old instruction so we can check them for
5031 // recursive simplifications after a RAUW. This is cheaper than checking all
5032 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005033 for (User *U : I->users())
5034 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005035
5036 // Replace the instruction with its simplified value.
5037 I->replaceAllUsesWith(SimpleV);
5038
5039 // Gracefully handle edge cases where the instruction is not wired into any
5040 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00005041 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
5042 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005043 I->eraseFromParent();
5044 }
5045 return Simplified;
5046}
5047
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005048bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005049 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005050 const DominatorTree *DT,
5051 AssumptionCache *AC) {
5052 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005053}
5054
5055bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005056 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005057 const DominatorTree *DT,
5058 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00005059 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
5060 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005061 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00005062}
Daniel Berlin4d0fe642017-04-28 19:55:38 +00005063
5064namespace llvm {
5065const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
5066 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
5067 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
5068 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5069 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr;
5070 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
5071 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
5072 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5073}
5074
5075const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
5076 const DataLayout &DL) {
5077 return {DL, &AR.TLI, &AR.DT, &AR.AC};
5078}
5079
5080template <class T, class... TArgs>
5081const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
5082 Function &F) {
5083 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
5084 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
5085 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
5086 return {F.getParent()->getDataLayout(), TLI, DT, AC};
5087}
5088template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
5089 Function &);
5090}