blob: dc8e8df421ecee1f5218bfc8df9d31c4ff785701 [file] [log] [blame]
Chris Lattner1e7b7b52010-01-05 06:05:07 +00001//===- InstCombineSelect.cpp ----------------------------------------------===//
Chris Lattner8f771cb2010-01-05 06:03:12 +00002//
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//
Chris Lattner1e7b7b52010-01-05 06:05:07 +000010// This file implements the visitSelect function.
Chris Lattner8f771cb2010-01-05 06:03:12 +000011//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Analysis/AssumptionCache.h"
Craig Topper882f2962017-08-16 21:52:07 +000020#include "llvm/Analysis/CmpInstAnalysis.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000021#include "llvm/Analysis/InstructionSimplify.h"
James Molloy71b91c22015-05-11 14:42:20 +000022#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000034#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000035#include "llvm/IR/Type.h"
36#include "llvm/IR/User.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/Casting.h"
39#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000040#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000041#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42#include <cassert>
43#include <utility>
44
Chris Lattner8f771cb2010-01-05 06:03:12 +000045using namespace llvm;
46using namespace PatternMatch;
47
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "instcombine"
49
Sanjay Patel7ed0bc22018-03-06 16:57:55 +000050static Value *createMinMax(InstCombiner::BuilderTy &Builder,
51 SelectPatternFlavor SPF, Value *A, Value *B) {
52 CmpInst::Predicate Pred = getMinMaxPred(SPF);
53 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
Craig Topperbb4069e2017-07-07 23:16:26 +000054 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
Sanjoy Das08e95b42015-04-30 04:56:04 +000055}
56
Sanjay Patel85e17bb2018-08-10 20:30:35 +000057/// Replace a select operand based on an equality comparison with the identity
58/// constant of a binop.
David Bolvansky6737b3a2018-07-30 20:38:53 +000059static Instruction *foldSelectBinOpIdentity(SelectInst &Sel) {
Sanjay Patel85e17bb2018-08-10 20:30:35 +000060 // The select condition must be an equality compare with a constant operand.
61 // TODO: Support FP compares.
62 Value *X;
David Bolvansky6737b3a2018-07-30 20:38:53 +000063 Constant *C;
64 CmpInst::Predicate Pred;
Sanjay Patel85e17bb2018-08-10 20:30:35 +000065 if (!match(Sel.getCondition(), m_ICmp(Pred, m_Value(X), m_Constant(C))) ||
David Bolvansky6737b3a2018-07-30 20:38:53 +000066 !ICmpInst::isEquality(Pred))
67 return nullptr;
68
Sanjay Patel85e17bb2018-08-10 20:30:35 +000069 // A select operand must be a binop, and the compare constant must be the
70 // identity constant for that binop.
David Bolvansky6737b3a2018-07-30 20:38:53 +000071 bool IsEq = Pred == ICmpInst::ICMP_EQ;
Sanjay Patel85e17bb2018-08-10 20:30:35 +000072 BinaryOperator *BO;
73 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)) ||
David Bolvansky01d98cc2018-08-12 17:30:07 +000074 ConstantExpr::getBinOpIdentity(BO->getOpcode(), BO->getType(), true) != C)
Sanjay Patel85e17bb2018-08-10 20:30:35 +000075 return nullptr;
76
77 // Last, match the compare variable operand with a binop operand.
78 Value *Y;
David Bolvansky01d98cc2018-08-12 17:30:07 +000079 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
80 return nullptr;
Sanjay Patel85e17bb2018-08-10 20:30:35 +000081 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
82 return nullptr;
83
84 // BO = binop Y, X
85 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
86 // =>
87 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
88 Sel.setOperand(IsEq ? 1 : 2, Y);
89 return &Sel;
David Bolvansky6737b3a2018-07-30 20:38:53 +000090}
91
Craig Topper28d6d962017-09-05 05:26:37 +000092/// This folds:
Sanjay Patel807ddee2018-04-25 16:34:01 +000093/// select (icmp eq (and X, C1)), TC, FC
94/// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
Craig Topper28d6d962017-09-05 05:26:37 +000095/// To something like:
Sanjay Patel807ddee2018-04-25 16:34:01 +000096/// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
Craig Topper28d6d962017-09-05 05:26:37 +000097/// Or:
Sanjay Patel807ddee2018-04-25 16:34:01 +000098/// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
99/// With some variations depending if FC is larger than TC, or the shift
Craig Topper28d6d962017-09-05 05:26:37 +0000100/// isn't needed, or the bit widths don't match.
Sanjay Patel807ddee2018-04-25 16:34:01 +0000101static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
Craig Topper28d6d962017-09-05 05:26:37 +0000102 InstCombiner::BuilderTy &Builder) {
Sanjay Patel807ddee2018-04-25 16:34:01 +0000103 const APInt *SelTC, *SelFC;
104 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
105 !match(Sel.getFalseValue(), m_APInt(SelFC)))
106 return nullptr;
Craig Topper28d6d962017-09-05 05:26:37 +0000107
108 // If this is a vector select, we need a vector compare.
Sanjay Patel807ddee2018-04-25 16:34:01 +0000109 Type *SelType = Sel.getType();
110 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
Craig Topper28d6d962017-09-05 05:26:37 +0000111 return nullptr;
112
113 Value *V;
114 APInt AndMask;
115 bool CreateAnd = false;
Sanjay Patel807ddee2018-04-25 16:34:01 +0000116 ICmpInst::Predicate Pred = Cmp->getPredicate();
Craig Topper28d6d962017-09-05 05:26:37 +0000117 if (ICmpInst::isEquality(Pred)) {
Sanjay Patel807ddee2018-04-25 16:34:01 +0000118 if (!match(Cmp->getOperand(1), m_Zero()))
Craig Topper28d6d962017-09-05 05:26:37 +0000119 return nullptr;
120
Sanjay Patel807ddee2018-04-25 16:34:01 +0000121 V = Cmp->getOperand(0);
Craig Topper28d6d962017-09-05 05:26:37 +0000122 const APInt *AndRHS;
123 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
124 return nullptr;
125
126 AndMask = *AndRHS;
Sanjay Patel807ddee2018-04-25 16:34:01 +0000127 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
Craig Topper28d6d962017-09-05 05:26:37 +0000128 Pred, V, AndMask)) {
129 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
Craig Topper28d6d962017-09-05 05:26:37 +0000130 if (!AndMask.isPowerOf2())
131 return nullptr;
132
133 CreateAnd = true;
134 } else {
135 return nullptr;
136 }
137
Sanjay Patele7b66542018-05-03 21:58:44 +0000138 // In general, when both constants are non-zero, we would need an offset to
139 // replace the select. This would require more instructions than we started
140 // with. But there's one special-case that we handle here because it can
141 // simplify/reduce the instructions.
Sanjay Patel807ddee2018-04-25 16:34:01 +0000142 APInt TC = *SelTC;
143 APInt FC = *SelFC;
Sanjay Patel807ddee2018-04-25 16:34:01 +0000144 if (!TC.isNullValue() && !FC.isNullValue()) {
Sanjay Patele7b66542018-05-03 21:58:44 +0000145 // If the select constants differ by exactly one bit and that's the same
146 // bit that is masked and checked by the select condition, the select can
147 // be replaced by bitwise logic to set/clear one bit of the constant result.
148 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
Craig Topper28d6d962017-09-05 05:26:37 +0000149 return nullptr;
Sanjay Patele7b66542018-05-03 21:58:44 +0000150 if (CreateAnd) {
151 // If we have to create an 'and', then we must kill the cmp to not
152 // increase the instruction count.
153 if (!Cmp->hasOneUse())
154 return nullptr;
155 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
156 }
157 bool ExtraBitInTC = TC.ugt(FC);
158 if (Pred == ICmpInst::ICMP_EQ) {
159 // If the masked bit in V is clear, clear or set the bit in the result:
160 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
161 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
162 Constant *C = ConstantInt::get(SelType, TC);
163 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
164 }
165 if (Pred == ICmpInst::ICMP_NE) {
166 // If the masked bit in V is set, set or clear the bit in the result:
167 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
168 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
169 Constant *C = ConstantInt::get(SelType, FC);
170 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
171 }
172 llvm_unreachable("Only expecting equality predicates");
Craig Topper28d6d962017-09-05 05:26:37 +0000173 }
174
Sanjay Patel807ddee2018-04-25 16:34:01 +0000175 // Make sure one of the select arms is a power-of-2.
176 if (!TC.isPowerOf2() && !FC.isPowerOf2())
Craig Topper28d6d962017-09-05 05:26:37 +0000177 return nullptr;
178
179 // Determine which shift is needed to transform result of the 'and' into the
180 // desired result.
Sanjay Patel807ddee2018-04-25 16:34:01 +0000181 const APInt &ValC = !TC.isNullValue() ? TC : FC;
Craig Topper28d6d962017-09-05 05:26:37 +0000182 unsigned ValZeros = ValC.logBase2();
183 unsigned AndZeros = AndMask.logBase2();
184
Sanjay Patel807ddee2018-04-25 16:34:01 +0000185 // Insert the 'and' instruction on the input to the truncate.
186 if (CreateAnd)
Craig Topper28d6d962017-09-05 05:26:37 +0000187 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
Craig Topper28d6d962017-09-05 05:26:37 +0000188
Sanjay Patel807ddee2018-04-25 16:34:01 +0000189 // If types don't match, we can still convert the select by introducing a zext
Craig Topper28d6d962017-09-05 05:26:37 +0000190 // or a trunc of the 'and'.
191 if (ValZeros > AndZeros) {
192 V = Builder.CreateZExtOrTrunc(V, SelType);
193 V = Builder.CreateShl(V, ValZeros - AndZeros);
194 } else if (ValZeros < AndZeros) {
195 V = Builder.CreateLShr(V, AndZeros - ValZeros);
196 V = Builder.CreateZExtOrTrunc(V, SelType);
Sanjay Patel807ddee2018-04-25 16:34:01 +0000197 } else {
Craig Topper28d6d962017-09-05 05:26:37 +0000198 V = Builder.CreateZExtOrTrunc(V, SelType);
Sanjay Patel807ddee2018-04-25 16:34:01 +0000199 }
Craig Topper28d6d962017-09-05 05:26:37 +0000200
201 // Okay, now we know that everything is set up, we just don't know whether we
202 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
Sanjay Patel807ddee2018-04-25 16:34:01 +0000203 bool ShouldNotVal = !TC.isNullValue();
Craig Topper28d6d962017-09-05 05:26:37 +0000204 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
205 if (ShouldNotVal)
206 V = Builder.CreateXor(V, ValC);
207
Craig Topper28d6d962017-09-05 05:26:37 +0000208 return V;
209}
210
Sanjay Patel6eccf482015-09-09 15:24:36 +0000211/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000212/// %C = or %A, %B
213/// %D = select %cond, %C, %A
214/// into:
215/// %C = select %cond, %B, 0
216/// %D = or %A, %C
217///
218/// Assuming that the specified instruction is an operand to the select, return
219/// a bitmask indicating which operands of this instruction are foldable if they
220/// equal the other incoming value of the select.
Craig Topper8e351e92017-08-08 06:19:24 +0000221static unsigned getSelectFoldableOperands(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000222 switch (I->getOpcode()) {
223 case Instruction::Add:
224 case Instruction::Mul:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor:
228 return 3; // Can fold through either operand.
229 case Instruction::Sub: // Can only fold on the amount subtracted.
230 case Instruction::Shl: // Can only fold on the shift amount.
231 case Instruction::LShr:
232 case Instruction::AShr:
233 return 1;
234 default:
235 return 0; // Cannot fold
236 }
237}
238
Sanjay Patel6eccf482015-09-09 15:24:36 +0000239/// For the same transformation as the previous function, return the identity
240/// constant that goes into the select.
Craig Topper4c766a02017-09-05 05:26:36 +0000241static APInt getSelectFoldableConstant(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000242 switch (I->getOpcode()) {
243 default: llvm_unreachable("This cannot happen!");
244 case Instruction::Add:
245 case Instruction::Sub:
246 case Instruction::Or:
247 case Instruction::Xor:
248 case Instruction::Shl:
249 case Instruction::LShr:
250 case Instruction::AShr:
Craig Topper4c766a02017-09-05 05:26:36 +0000251 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000252 case Instruction::And:
Craig Topper4c766a02017-09-05 05:26:36 +0000253 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000254 case Instruction::Mul:
Craig Topper4c766a02017-09-05 05:26:36 +0000255 return APInt(I->getType()->getScalarSizeInBits(), 1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000256 }
257}
258
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000259/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000260Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000261 Instruction *FI) {
Sanjay Patel6105bb52017-03-16 20:42:45 +0000262 // Don't break up min/max patterns. The hasOneUse checks below prevent that
263 // for most cases, but vector min/max with bitcasts can be transformed. If the
264 // one-use restrictions are eased for other patterns, we still don't want to
265 // obfuscate min/max.
266 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
267 match(&SI, m_SMax(m_Value(), m_Value())) ||
268 match(&SI, m_UMin(m_Value(), m_Value())) ||
269 match(&SI, m_UMax(m_Value(), m_Value()))))
270 return nullptr;
271
Sanjay Patel384d0f22016-06-08 20:31:52 +0000272 // If this is a cast from the same type, merge.
273 if (TI->getNumOperands() == 1 && TI->isCast()) {
274 Type *FIOpndTy = FI->getOperand(0)->getType();
275 if (TI->getOperand(0)->getType() != FIOpndTy)
276 return nullptr;
277
278 // The select condition may be a vector. We may only change the operand
279 // type if the vector width remains the same (and matches the condition).
280 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000281 if (CondTy->isVectorTy()) {
282 if (!FIOpndTy->isVectorTy())
283 return nullptr;
284 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
285 return nullptr;
286
287 // TODO: If the backend knew how to deal with casts better, we could
288 // remove this limitation. For now, there's too much potential to create
289 // worse codegen by promoting the select ahead of size-altering casts
290 // (PR28160).
291 //
292 // Note that ValueTracking's matchSelectPattern() looks through casts
293 // without checking 'hasOneUse' when it matches min/max patterns, so this
294 // transform may end up happening anyway.
295 if (TI->getOpcode() != Instruction::BitCast &&
296 (!TI->hasOneUse() || !FI->hasOneUse()))
297 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000298 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
299 // TODO: The one-use restrictions for a scalar select could be eased if
300 // the fold of a select in visitLoadInst() was enhanced to match a pattern
301 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000302 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000303 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000304
305 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000306 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000307 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
308 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000309 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000310 TI->getType());
311 }
312
John Brawn2867bd72018-01-19 10:05:15 +0000313 // Only handle binary operators (including two-operand getelementptr) with
314 // one-use here. As with the cast case above, it may be possible to relax the
315 // one-use constraint, but that needs be examined carefully since it may not
316 // reduce the total number of instructions.
317 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
318 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
319 !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000320 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000321
322 // Figure out if the operations have any operands in common.
323 Value *MatchOp, *OtherOpT, *OtherOpF;
324 bool MatchIsOpZero;
325 if (TI->getOperand(0) == FI->getOperand(0)) {
326 MatchOp = TI->getOperand(0);
327 OtherOpT = TI->getOperand(1);
328 OtherOpF = FI->getOperand(1);
329 MatchIsOpZero = true;
330 } else if (TI->getOperand(1) == FI->getOperand(1)) {
331 MatchOp = TI->getOperand(1);
332 OtherOpT = TI->getOperand(0);
333 OtherOpF = FI->getOperand(0);
334 MatchIsOpZero = false;
335 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000336 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000337 } else if (TI->getOperand(0) == FI->getOperand(1)) {
338 MatchOp = TI->getOperand(0);
339 OtherOpT = TI->getOperand(1);
340 OtherOpF = FI->getOperand(0);
341 MatchIsOpZero = true;
342 } else if (TI->getOperand(1) == FI->getOperand(0)) {
343 MatchOp = TI->getOperand(1);
344 OtherOpT = TI->getOperand(0);
345 OtherOpF = FI->getOperand(1);
346 MatchIsOpZero = true;
347 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000348 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000349 }
350
351 // If we reach here, they do have operations in common.
Craig Topperbb4069e2017-07-07 23:16:26 +0000352 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
353 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000354 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
355 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
John Brawn2867bd72018-01-19 10:05:15 +0000356 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
357 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
358 }
359 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
360 auto *FGEP = cast<GetElementPtrInst>(FI);
361 Type *ElementType = TGEP->getResultElementType();
362 return TGEP->isInBounds() && FGEP->isInBounds()
363 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
364 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
365 }
366 llvm_unreachable("Expected BinaryOperator or GEP");
367 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000368}
369
Craig Topper4c766a02017-09-05 05:26:36 +0000370static bool isSelect01(const APInt &C1I, const APInt &C2I) {
371 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000372 return false;
Craig Topper4c766a02017-09-05 05:26:36 +0000373 return C1I.isOneValue() || C1I.isAllOnesValue() ||
374 C2I.isOneValue() || C2I.isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000375}
376
Sanjay Patel6eccf482015-09-09 15:24:36 +0000377/// Try to fold the select into one of the operands to allow further
378/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000379Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000380 Value *FalseVal) {
381 // See the comment above GetSelectFoldableOperands for a description of the
382 // transformation we are doing here.
Craig Topper8e351e92017-08-08 06:19:24 +0000383 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
384 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000385 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000386 unsigned OpToFold = 0;
387 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
388 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000389 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000390 OpToFold = 2;
391 }
392
393 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000394 APInt CI = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000395 Value *OOp = TVI->getOperand(2-OpToFold);
396 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000397 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000398 const APInt *OOpC;
399 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
400 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
401 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000402 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000403 NewSel->takeName(TVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000404 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000405 FalseVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000406 BO->copyIRFlags(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000407 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000408 }
409 }
410 }
411 }
412 }
413
Craig Topper8e351e92017-08-08 06:19:24 +0000414 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
415 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000416 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000417 unsigned OpToFold = 0;
418 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
419 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000420 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000421 OpToFold = 2;
422 }
423
424 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000425 APInt CI = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000426 Value *OOp = FVI->getOperand(2-OpToFold);
427 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000428 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000429 const APInt *OOpC;
430 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
431 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
432 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000433 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000434 NewSel->takeName(FVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000435 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000436 TrueVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000437 BO->copyIRFlags(FVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000438 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000439 }
440 }
441 }
442 }
443 }
444
Craig Topperf40110f2014-04-25 05:29:35 +0000445 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000446}
447
Sanjay Patel6eccf482015-09-09 15:24:36 +0000448/// We want to turn:
Roman Lebedev41922f12018-04-07 10:37:24 +0000449/// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
450/// into:
451/// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
452/// Note:
453/// Z may be 0 if lshr is missing.
Roman Lebedevc0065932018-04-13 09:57:57 +0000454/// Worst-case scenario is that we will replace 5 instructions with 5 different
Roman Lebedev41922f12018-04-07 10:37:24 +0000455/// instructions, but we got rid of select.
Roman Lebedevc0065932018-04-13 09:57:57 +0000456static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
457 Value *TVal, Value *FVal,
Roman Lebedev41922f12018-04-07 10:37:24 +0000458 InstCombiner::BuilderTy &Builder) {
Roman Lebedevc0065932018-04-13 09:57:57 +0000459 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
460 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
461 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
Roman Lebedev41922f12018-04-07 10:37:24 +0000462 return nullptr;
463
Roman Lebedevc0065932018-04-13 09:57:57 +0000464 // The TrueVal has general form of: and %B, 1
Roman Lebedev41922f12018-04-07 10:37:24 +0000465 Value *B;
Roman Lebedevc0065932018-04-13 09:57:57 +0000466 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
Roman Lebedev41922f12018-04-07 10:37:24 +0000467 return nullptr;
468
Roman Lebedevc0065932018-04-13 09:57:57 +0000469 // Where %B may be optionally shifted: lshr %X, %Z.
470 Value *X, *Z;
471 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
472 if (!HasShift)
473 X = B;
474
475 Value *Y;
476 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
Roman Lebedev41922f12018-04-07 10:37:24 +0000477 return nullptr;
478
Roman Lebedevc0065932018-04-13 09:57:57 +0000479 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
480 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
481 Constant *One = ConstantInt::get(SelType, 1);
482 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
Roman Lebedev41922f12018-04-07 10:37:24 +0000483 Value *FullMask = Builder.CreateOr(Y, MaskB);
484 Value *MaskedX = Builder.CreateAnd(X, FullMask);
485 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
486 return new ZExtInst(ICmpNeZero, SelType);
487}
488
489/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000490/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
491/// into:
Craig Topperae86cc72017-06-21 16:07:13 +0000492/// (or (shl (and X, C1), C3), Y)
David Majnemer8d048d02013-04-30 08:57:58 +0000493/// iff:
494/// C1 and C2 are both powers of 2
495/// where:
496/// C3 = Log(C2) - Log(C1)
497///
498/// This transform handles cases where:
499/// 1. The icmp predicate is inverted
500/// 2. The select operands are reversed
501/// 3. The magnitude of C2 and C1 are flipped
Craig Topper5d6ddda2017-08-29 00:13:49 +0000502static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000503 Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000504 InstCombiner::BuilderTy &Builder) {
Craig Topper5d6ddda2017-08-29 00:13:49 +0000505 // Only handle integer compares. Also, if this is a vector select, we need a
506 // vector compare.
507 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
508 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000509 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000510
511 Value *CmpLHS = IC->getOperand(0);
512 Value *CmpRHS = IC->getOperand(1);
513
Craig Topperdffbbcb2017-06-22 16:23:30 +0000514 Value *V;
515 unsigned C1Log;
516 bool IsEqualZero;
517 bool NeedAnd = false;
518 if (IC->isEquality()) {
519 if (!match(CmpRHS, m_Zero()))
520 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000521
Craig Topperdffbbcb2017-06-22 16:23:30 +0000522 const APInt *C1;
523 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
524 return nullptr;
525
526 V = CmpLHS;
527 C1Log = C1->logBase2();
528 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
529 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
530 IC->getPredicate() == ICmpInst::ICMP_SGT) {
531 // We also need to recognize (icmp slt (trunc (X)), 0) and
532 // (icmp sgt (trunc (X)), -1).
533 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
534 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
535 (!IsEqualZero && !match(CmpRHS, m_Zero())))
536 return nullptr;
537
538 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
539 return nullptr;
540
541 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
542 NeedAnd = true;
543 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000544 return nullptr;
Craig Topperdffbbcb2017-06-22 16:23:30 +0000545 }
David Majnemer8d048d02013-04-30 08:57:58 +0000546
547 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000548 bool OrOnTrueVal = false;
549 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
550 if (!OrOnFalseVal)
551 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000552
553 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000554 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000555
David Majnemer8d048d02013-04-30 08:57:58 +0000556 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
557
David Majnemer8d048d02013-04-30 08:57:58 +0000558 unsigned C2Log = C2->logBase2();
Craig Topperae86cc72017-06-21 16:07:13 +0000559
Craig Topperdffbbcb2017-06-22 16:23:30 +0000560 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
Craig Topperae86cc72017-06-21 16:07:13 +0000561 bool NeedShift = C1Log != C2Log;
Craig Topper5d6ddda2017-08-29 00:13:49 +0000562 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
563 V->getType()->getScalarSizeInBits();
Craig Topperae86cc72017-06-21 16:07:13 +0000564
565 // Make sure we don't create more instructions than we save.
566 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
567 if ((NeedShift + NeedXor + NeedZExtTrunc) >
568 (IC->hasOneUse() + Or->hasOneUse()))
569 return nullptr;
570
Craig Topperdffbbcb2017-06-22 16:23:30 +0000571 if (NeedAnd) {
572 // Insert the AND instruction on the input to the truncate.
573 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
Craig Topperbb4069e2017-07-07 23:16:26 +0000574 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
Craig Topperdffbbcb2017-06-22 16:23:30 +0000575 }
576
David Majnemer8d048d02013-04-30 08:57:58 +0000577 if (C2Log > C1Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000578 V = Builder.CreateZExtOrTrunc(V, Y->getType());
579 V = Builder.CreateShl(V, C2Log - C1Log);
David Majnemer8d048d02013-04-30 08:57:58 +0000580 } else if (C1Log > C2Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000581 V = Builder.CreateLShr(V, C1Log - C2Log);
582 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000583 } else
Craig Topperbb4069e2017-07-07 23:16:26 +0000584 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000585
Craig Topperae86cc72017-06-21 16:07:13 +0000586 if (NeedXor)
Craig Topperbb4069e2017-07-07 23:16:26 +0000587 V = Builder.CreateXor(V, *C2);
David Majnemer8d048d02013-04-30 08:57:58 +0000588
Craig Topperbb4069e2017-07-07 23:16:26 +0000589 return Builder.CreateOr(V, Y);
David Majnemer8d048d02013-04-30 08:57:58 +0000590}
591
Sanjay Patele9a153f2018-02-05 17:53:29 +0000592/// Transform patterns such as: (a > b) ? a - b : 0
593/// into: ((a > b) ? a : b) - b)
594/// This produces a canonical max pattern that is more easily recognized by the
595/// backend and converted into saturated subtraction instructions if those
596/// exist.
597/// There are 8 commuted/swapped variants of this pattern.
598/// TODO: Also support a - UMIN(a,b) patterns.
599static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
600 const Value *TrueVal,
601 const Value *FalseVal,
602 InstCombiner::BuilderTy &Builder) {
603 ICmpInst::Predicate Pred = ICI->getPredicate();
604 if (!ICmpInst::isUnsigned(Pred))
605 return nullptr;
606
607 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
608 if (match(TrueVal, m_Zero())) {
609 Pred = ICmpInst::getInversePredicate(Pred);
610 std::swap(TrueVal, FalseVal);
611 }
612 if (!match(FalseVal, m_Zero()))
613 return nullptr;
614
615 Value *A = ICI->getOperand(0);
616 Value *B = ICI->getOperand(1);
617 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
618 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
619 std::swap(A, B);
620 Pred = ICmpInst::getSwappedPredicate(Pred);
621 }
622
623 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
624 "Unexpected isUnsigned predicate!");
625
626 // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
627 bool IsNegative = false;
628 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
629 IsNegative = true;
630 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
631 return nullptr;
632
633 // If sub is used anywhere else, we wouldn't be able to eliminate it
634 // afterwards.
635 if (!TrueVal->hasOneUse())
636 return nullptr;
637
638 // All checks passed, convert to canonical unsigned saturated subtraction
639 // form: sub(max()).
640 // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
641 Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
642 return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
643}
644
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000645/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
646/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
647///
648/// For example, we can fold the following code sequence:
649/// \code
650/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
651/// %1 = icmp ne i32 %x, 0
652/// %2 = select i1 %1, i32 %0, i32 32
653/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000654///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000655/// into:
656/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
657static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000658 InstCombiner::BuilderTy &Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000659 ICmpInst::Predicate Pred = ICI->getPredicate();
660 Value *CmpLHS = ICI->getOperand(0);
661 Value *CmpRHS = ICI->getOperand(1);
662
663 // Check if the condition value compares a value for equality against zero.
664 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
665 return nullptr;
666
667 Value *Count = FalseVal;
668 Value *ValueOnZero = TrueVal;
669 if (Pred == ICmpInst::ICMP_NE)
670 std::swap(Count, ValueOnZero);
671
672 // Skip zero extend/truncate.
673 Value *V = nullptr;
674 if (match(Count, m_ZExt(m_Value(V))) ||
675 match(Count, m_Trunc(m_Value(V))))
676 Count = V;
677
678 // Check if the value propagated on zero is a constant number equal to the
679 // sizeof in bits of 'Count'.
680 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
681 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
682 return nullptr;
683
684 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
685 // input to the cttz/ctlz is used as LHS for the compare instruction.
686 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
687 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
688 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000689 // Explicitly clear the 'undef_on_zero' flag.
690 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Craig Topper3b74a682017-08-04 16:07:18 +0000691 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
Craig Topperbb4069e2017-07-07 23:16:26 +0000692 Builder.Insert(NewI);
693 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000694 }
695
696 return nullptr;
697}
698
Sanjay Patel7ce65832016-11-01 17:46:08 +0000699/// Return true if we find and adjust an icmp+select pattern where the compare
700/// is with a constant that can be incremented or decremented to match the
701/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000702static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
703 ICmpInst::Predicate Pred = Cmp.getPredicate();
704 Value *CmpLHS = Cmp.getOperand(0);
705 Value *CmpRHS = Cmp.getOperand(1);
706 Value *TrueVal = Sel.getTrueValue();
707 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000708
Sanjay Patel644d7c32016-11-01 18:15:03 +0000709 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000710 const APInt *CmpC;
711 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000712 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000713
Sanjay Patel86408a82016-11-07 15:52:45 +0000714 // These transforms only work for selects of integers or vector selects of
715 // integer vectors.
716 Type *SelTy = Sel.getType();
717 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
718 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000719 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000720
Sanjay Patel644d7c32016-11-01 18:15:03 +0000721 Constant *AdjustedRHS;
722 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000723 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000724 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000725 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000726 else
727 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000728
Sanjay Patel644d7c32016-11-01 18:15:03 +0000729 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
730 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
731 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
732 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
733 ; // Nothing to do here. Values match without any sign/zero extension.
734 }
735 // Types do not match. Instead of calculating this with mixed types, promote
736 // all to the larger type. This enables scalar evolution to analyze this
737 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000738 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
739 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000740
Sanjay Patel644d7c32016-11-01 18:15:03 +0000741 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
742 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
743 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
744 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
745 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
746 CmpLHS = TrueVal;
747 AdjustedRHS = SextRHS;
748 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
749 SextRHS == TrueVal) {
750 CmpLHS = FalseVal;
751 AdjustedRHS = SextRHS;
752 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000753 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000754 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
755 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
756 // zext + signed compare cannot be changed:
757 // 0xff <s 0x00, but 0x00ff >s 0x0000
758 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
759 CmpLHS = TrueVal;
760 AdjustedRHS = ZextRHS;
761 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
762 ZextRHS == TrueVal) {
763 CmpLHS = FalseVal;
764 AdjustedRHS = ZextRHS;
765 } else {
766 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000767 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000768 } else {
769 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000770 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000771 } else {
772 return false;
773 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000774
Sanjay Patel644d7c32016-11-01 18:15:03 +0000775 Pred = ICmpInst::getSwappedPredicate(Pred);
776 CmpRHS = AdjustedRHS;
777 std::swap(FalseVal, TrueVal);
778 Cmp.setPredicate(Pred);
779 Cmp.setOperand(0, CmpLHS);
780 Cmp.setOperand(1, CmpRHS);
781 Sel.setOperand(1, TrueVal);
782 Sel.setOperand(2, FalseVal);
783 Sel.swapProfMetadata();
784
785 // Move the compare instruction right before the select instruction. Otherwise
786 // the sext/zext value may be defined after the compare instruction uses it.
787 Cmp.moveBefore(&Sel);
788
789 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000790}
791
Sanjay Patelcb731f12017-02-21 19:33:53 +0000792/// If this is an integer min/max (icmp + select) with a constant operand,
793/// create the canonical icmp for the min/max operation and canonicalize the
794/// constant to the 'false' operand of the select:
795/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
796/// Note: if C1 != C2, this will change the icmp constant to the existing
797/// constant operand of the select.
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000798static Instruction *
799canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
800 InstCombiner::BuilderTy &Builder) {
Sanjay Patelcb731f12017-02-21 19:33:53 +0000801 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000802 return nullptr;
803
804 // Canonicalize the compare predicate based on whether we have min or max.
805 Value *LHS, *RHS;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000806 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000807 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
808 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000809
Sanjay Patelcb731f12017-02-21 19:33:53 +0000810 // Is this already canonical?
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000811 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
Sanjay Patelcb731f12017-02-21 19:33:53 +0000812 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000813 Cmp.getPredicate() == CanonicalPred)
Sanjay Patelcb731f12017-02-21 19:33:53 +0000814 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000815
Sanjay Patelcb731f12017-02-21 19:33:53 +0000816 // Create the canonical compare and plug it into the select.
Sanjay Patel1f2f5d12018-03-06 19:01:18 +0000817 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000818
Sanjay Patelcb731f12017-02-21 19:33:53 +0000819 // If the select operands did not change, we're done.
820 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
821 return &Sel;
822
823 // If we are swapping the select operands, swap the metadata too.
824 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
825 "Unexpected results from matchSelectPattern");
826 Sel.setTrueValue(LHS);
827 Sel.setFalseValue(RHS);
828 Sel.swapProfMetadata();
829 return &Sel;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000830}
831
Chen Zheng567485a2018-07-27 01:49:51 +0000832/// There are many select variants for each of ABS/NABS.
833/// In matchSelectPattern(), there are different compare constants, compare
834/// predicates/operands and select operands.
835/// In isKnownNegation(), there are different formats of negated operands.
836/// Canonicalize all these variants to 1 pattern.
Sanjay Patela003c722018-05-20 14:23:23 +0000837/// This makes CSE more likely.
838static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
839 InstCombiner::BuilderTy &Builder) {
840 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
841 return nullptr;
842
843 // Choose a sign-bit check for the compare (likely simpler for codegen).
844 // ABS: (X <s 0) ? -X : X
845 // NABS: (X <s 0) ? X : -X
846 Value *LHS, *RHS;
847 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
848 if (SPF != SelectPatternFlavor::SPF_ABS &&
849 SPF != SelectPatternFlavor::SPF_NABS)
850 return nullptr;
851
Sanjay Patela003c722018-05-20 14:23:23 +0000852 Value *TVal = Sel.getTrueValue();
853 Value *FVal = Sel.getFalseValue();
Chen Zheng567485a2018-07-27 01:49:51 +0000854 assert(isKnownNegation(TVal, FVal) &&
855 "Unexpected result from matchSelectPattern");
856
857 // The compare may use the negated abs()/nabs() operand, or it may use
858 // negation in non-canonical form such as: sub A, B.
859 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
860 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
861
862 bool CmpCanonicalized = !CmpUsesNegatedOp &&
863 match(Cmp.getOperand(1), m_ZeroInt()) &&
864 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
865 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
866
867 // Is this already canonical?
868 if (CmpCanonicalized && RHSCanonicalized)
869 return nullptr;
870
871 // If RHS is used by other instructions except compare and select, don't
872 // canonicalize it to not increase the instruction count.
873 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
874 return nullptr;
875
876 // Create the canonical compare: icmp slt LHS 0.
877 if (!CmpCanonicalized) {
878 Cmp.setPredicate(ICmpInst::ICMP_SLT);
879 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
880 if (CmpUsesNegatedOp)
881 Cmp.setOperand(0, LHS);
882 }
883
884 // Create the canonical RHS: RHS = sub (0, LHS).
885 if (!RHSCanonicalized) {
886 assert(RHS->hasOneUse() && "RHS use number is not right");
887 RHS = Builder.CreateNeg(LHS);
888 if (TVal == LHS) {
889 Sel.setFalseValue(RHS);
890 FVal = RHS;
891 } else {
892 Sel.setTrueValue(RHS);
893 TVal = RHS;
894 }
895 }
896
897 // If the select operands do not change, we're done.
Sanjay Patela003c722018-05-20 14:23:23 +0000898 if (SPF == SelectPatternFlavor::SPF_NABS) {
Chen Zheng567485a2018-07-27 01:49:51 +0000899 if (TVal == LHS)
Sanjay Patela003c722018-05-20 14:23:23 +0000900 return &Sel;
Chen Zheng567485a2018-07-27 01:49:51 +0000901 assert(FVal == LHS && "Unexpected results from matchSelectPattern");
Sanjay Patela003c722018-05-20 14:23:23 +0000902 } else {
Chen Zheng567485a2018-07-27 01:49:51 +0000903 if (FVal == LHS)
Sanjay Patela003c722018-05-20 14:23:23 +0000904 return &Sel;
Chen Zheng567485a2018-07-27 01:49:51 +0000905 assert(TVal == LHS && "Unexpected results from matchSelectPattern");
Sanjay Patela003c722018-05-20 14:23:23 +0000906 }
907
908 // We are swapping the select operands, so swap the metadata too.
909 Sel.setTrueValue(FVal);
910 Sel.setFalseValue(TVal);
911 Sel.swapProfMetadata();
912 return &Sel;
913}
914
Sanjay Patel7ce65832016-11-01 17:46:08 +0000915/// Visit a SelectInst that has an ICmpInst as its first operand.
916Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
917 ICmpInst *ICI) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000918 Value *TrueVal = SI.getTrueValue();
919 Value *FalseVal = SI.getFalseValue();
920
Craig Topperbb4069e2017-07-07 23:16:26 +0000921 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000922 return NewSel;
923
Sanjay Patela003c722018-05-20 14:23:23 +0000924 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
925 return NewAbs;
926
Sanjay Patel644d7c32016-11-01 18:15:03 +0000927 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000928
Sanjay Patel807ddee2018-04-25 16:34:01 +0000929 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
930 return replaceInstUsesWith(SI, V);
Craig Topper74177e12017-08-21 19:02:06 +0000931
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000932 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
Sanjay Patele7b66542018-05-03 21:58:44 +0000933 ICmpInst::Predicate Pred = ICI->getPredicate();
934 Value *CmpLHS = ICI->getOperand(0);
935 Value *CmpRHS = ICI->getOperand(1);
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000936 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000937 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
938 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
939 SI.setOperand(1, CmpRHS);
940 Changed = true;
941 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
942 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
943 SI.setOperand(2, CmpRHS);
944 Changed = true;
945 }
946 }
947
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000948 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
949 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000950 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000951 unsigned BitWidth =
952 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
Craig Topperbcfd2d12017-04-20 16:56:25 +0000953 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000954 Value *X;
955 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000956 bool TrueWhenUnset;
957 bool IsBitTest = false;
958 if (ICmpInst::isEquality(Pred) &&
959 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000960 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000961 IsBitTest = true;
962 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
963 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
964 X = CmpLHS;
965 Y = &MinSignedValue;
966 IsBitTest = true;
967 TrueWhenUnset = false;
968 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
969 X = CmpLHS;
970 Y = &MinSignedValue;
971 IsBitTest = true;
972 TrueWhenUnset = true;
973 }
974 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000975 Value *V = nullptr;
976 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000977 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000978 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000979 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000980 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000981 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000982 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000983 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000984 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000985 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000986 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000987 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000988 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000989 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000990 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000991 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000992
993 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000994 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000995 }
996 }
997
Roman Lebedev41922f12018-04-07 10:37:24 +0000998 if (Instruction *V =
999 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1000 return V;
1001
Craig Topper5d6ddda2017-08-29 00:13:49 +00001002 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001003 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +00001004
Andrea Di Biagio086cbc32015-01-27 15:58:14 +00001005 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001006 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +00001007
Sanjay Patele9a153f2018-02-05 17:53:29 +00001008 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1009 return replaceInstUsesWith(SI, V);
1010
Craig Topperf40110f2014-04-25 05:29:35 +00001011 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001012}
1013
Sanjay Patel6eccf482015-09-09 15:24:36 +00001014/// SI is a select whose condition is a PHI node (but the two may be in
1015/// different blocks). See if the true/false values (V) are live in all of the
1016/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001017///
1018/// X = phi [ C1, BB1], [C2, BB2]
1019/// Y = add
1020/// Z = select X, Y, 0
1021///
1022/// because Y is not live in BB1/BB2.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001023static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001024 const SelectInst &SI) {
1025 // If the value is a non-instruction value like a constant or argument, it
1026 // can always be mapped.
1027 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001028 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001029
Chris Lattner8f771cb2010-01-05 06:03:12 +00001030 // If V is a PHI node defined in the same block as the condition PHI, we can
1031 // map the arguments.
1032 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001033
Chris Lattner8f771cb2010-01-05 06:03:12 +00001034 if (const PHINode *VP = dyn_cast<PHINode>(I))
1035 if (VP->getParent() == CondPHI->getParent())
1036 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001037
Chris Lattner8f771cb2010-01-05 06:03:12 +00001038 // Otherwise, if the PHI and select are defined in the same block and if V is
1039 // defined in a different block, then we can transform it.
1040 if (SI.getParent() == CondPHI->getParent() &&
1041 I->getParent() != CondPHI->getParent())
1042 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001043
Chris Lattner8f771cb2010-01-05 06:03:12 +00001044 // Otherwise we have a 'hard' case and we can't tell without doing more
1045 // detailed dominator based analysis, punt.
1046 return false;
1047}
1048
Sanjay Patel6eccf482015-09-09 15:24:36 +00001049/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001050/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001051Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001052 SelectPatternFlavor SPF1,
1053 Value *A, Value *B,
1054 Instruction &Outer,
1055 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +00001056 if (Outer.getType() != Inner->getType())
1057 return nullptr;
1058
Chris Lattner8f771cb2010-01-05 06:03:12 +00001059 if (C == A || C == B) {
1060 // MAX(MAX(A, B), B) -> MAX(A, B)
1061 // MIN(MIN(a, b), a) -> MIN(a, b)
Craig Topper0198b732018-05-18 21:21:56 +00001062 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
Sanjay Patel4b198802016-02-01 22:23:39 +00001063 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001064
Chris Lattner8f771cb2010-01-05 06:03:12 +00001065 // MAX(MIN(a, b), a) -> a
1066 // MIN(MAX(a, b), a) -> a
1067 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1068 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1069 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1070 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +00001071 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001072 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001073
Dinesh Dwivedif675f422014-05-15 06:13:40 +00001074 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +00001075 const APInt *CB, *CC;
1076 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1077 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1078 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1079 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1080 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1081 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1082 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1083 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +00001084
Sanjay Patelc0de9c92016-10-27 21:19:40 +00001085 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1086 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1087 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1088 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1089 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1090 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1091 Outer.replaceUsesOfWith(Inner, A);
1092 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +00001093 }
1094 }
1095 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +00001096
1097 // ABS(ABS(X)) -> ABS(X)
1098 // NABS(NABS(X)) -> NABS(X)
1099 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001100 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +00001101 }
1102
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +00001103 // ABS(NABS(X)) -> ABS(X)
1104 // NABS(ABS(X)) -> NABS(X)
1105 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1106 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1107 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +00001108 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +00001109 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1110 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +00001111 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +00001112 }
Sanjoy Das08e95b42015-04-30 04:56:04 +00001113
1114 auto IsFreeOrProfitableToInvert =
1115 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1116 if (match(V, m_Not(m_Value(NotV)))) {
1117 // If V has at most 2 uses then we can get rid of the xor operation
1118 // entirely.
1119 ElidesXor |= !V->hasNUsesOrMore(3);
1120 return true;
1121 }
1122
1123 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1124 NotV = nullptr;
1125 return true;
1126 }
1127
1128 return false;
1129 };
1130
1131 Value *NotA, *NotB, *NotC;
1132 bool ElidesXor = false;
1133
1134 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1135 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1136 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1137 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1138 //
1139 // This transform is performance neutral if we can elide at least one xor from
1140 // the set of three operands, since we'll be tacking on an xor at the very
1141 // end.
Anna Thomasec36f3b2017-02-21 14:40:28 +00001142 if (SelectPatternResult::isMinOrMax(SPF1) &&
1143 SelectPatternResult::isMinOrMax(SPF2) &&
1144 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
Sanjoy Das08e95b42015-04-30 04:56:04 +00001145 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1146 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1147 if (!NotA)
Craig Topperbb4069e2017-07-07 23:16:26 +00001148 NotA = Builder.CreateNot(A);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001149 if (!NotB)
Craig Topperbb4069e2017-07-07 23:16:26 +00001150 NotB = Builder.CreateNot(B);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001151 if (!NotC)
Craig Topperbb4069e2017-07-07 23:16:26 +00001152 NotC = Builder.CreateNot(C);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001153
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001154 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1155 NotB);
1156 Value *NewOuter = Builder.CreateNot(
1157 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +00001158 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001159 }
1160
Craig Topperf40110f2014-04-25 05:29:35 +00001161 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001162}
1163
Sanjay Patel39293132016-06-08 21:10:01 +00001164/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1165/// This is even legal for FP.
1166static Instruction *foldAddSubSelect(SelectInst &SI,
1167 InstCombiner::BuilderTy &Builder) {
1168 Value *CondVal = SI.getCondition();
1169 Value *TrueVal = SI.getTrueValue();
1170 Value *FalseVal = SI.getFalseValue();
1171 auto *TI = dyn_cast<Instruction>(TrueVal);
1172 auto *FI = dyn_cast<Instruction>(FalseVal);
1173 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1174 return nullptr;
1175
1176 Instruction *AddOp = nullptr, *SubOp = nullptr;
1177 if ((TI->getOpcode() == Instruction::Sub &&
1178 FI->getOpcode() == Instruction::Add) ||
1179 (TI->getOpcode() == Instruction::FSub &&
1180 FI->getOpcode() == Instruction::FAdd)) {
1181 AddOp = FI;
1182 SubOp = TI;
1183 } else if ((FI->getOpcode() == Instruction::Sub &&
1184 TI->getOpcode() == Instruction::Add) ||
1185 (FI->getOpcode() == Instruction::FSub &&
1186 TI->getOpcode() == Instruction::FAdd)) {
1187 AddOp = TI;
1188 SubOp = FI;
1189 }
1190
1191 if (AddOp) {
1192 Value *OtherAddOp = nullptr;
1193 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1194 OtherAddOp = AddOp->getOperand(1);
1195 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1196 OtherAddOp = AddOp->getOperand(0);
1197 }
1198
1199 if (OtherAddOp) {
1200 // So at this point we know we have (Y -> OtherAddOp):
1201 // select C, (add X, Y), (sub X, Z)
1202 Value *NegVal; // Compute -Z
1203 if (SI.getType()->isFPOrFPVectorTy()) {
1204 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1205 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1206 FastMathFlags Flags = AddOp->getFastMathFlags();
1207 Flags &= SubOp->getFastMathFlags();
1208 NegInst->setFastMathFlags(Flags);
1209 }
1210 } else {
1211 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1212 }
1213
1214 Value *NewTrueOp = OtherAddOp;
1215 Value *NewFalseOp = NegVal;
1216 if (AddOp != TI)
1217 std::swap(NewTrueOp, NewFalseOp);
1218 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +00001219 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +00001220
1221 if (SI.getType()->isFPOrFPVectorTy()) {
1222 Instruction *RI =
1223 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1224
1225 FastMathFlags Flags = AddOp->getFastMathFlags();
1226 Flags &= SubOp->getFastMathFlags();
1227 RI->setFastMathFlags(Flags);
1228 return RI;
1229 } else
1230 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1231 }
1232 }
1233 return nullptr;
1234}
1235
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001236Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
Sanjay Patel26368cd2018-05-31 19:55:27 +00001237 Constant *C;
1238 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1239 !match(Sel.getFalseValue(), m_Constant(C)))
1240 return nullptr;
1241
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001242 Instruction *ExtInst;
1243 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1244 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1245 return nullptr;
1246
1247 auto ExtOpcode = ExtInst->getOpcode();
1248 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1249 return nullptr;
1250
Sanjay Patel26368cd2018-05-31 19:55:27 +00001251 // If we are extending from a boolean type or if we can create a select that
1252 // has the same size operands as its condition, try to narrow the select.
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001253 Value *X = ExtInst->getOperand(0);
1254 Type *SmallType = X->getType();
Sanjay Patel26368cd2018-05-31 19:55:27 +00001255 Value *Cond = Sel.getCondition();
1256 auto *Cmp = dyn_cast<CmpInst>(Cond);
1257 if (!SmallType->isIntOrIntVectorTy(1) &&
1258 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001259 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001260
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001261 // If the constant is the same after truncation to the smaller type and
1262 // extension to the original type, we can narrow the select.
1263 Type *SelType = Sel.getType();
1264 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1265 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1266 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001267 Value *TruncCVal = cast<Value>(TruncC);
1268 if (ExtInst == Sel.getFalseValue())
1269 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001270
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001271 // select Cond, (ext X), C --> ext(select Cond, X, C')
1272 // select Cond, C, (ext X) --> ext(select Cond, C', X)
Craig Topperbb4069e2017-07-07 23:16:26 +00001273 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001274 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +00001275 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001276
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001277 // If one arm of the select is the extend of the condition, replace that arm
1278 // with the extension of the appropriate known bool value.
1279 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001280 if (ExtInst == Sel.getTrueValue()) {
1281 // select X, (sext X), C --> select X, -1, C
1282 // select X, (zext X), C --> select X, 1, C
1283 Constant *One = ConstantInt::getTrue(SmallType);
1284 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001285 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001286 } else {
1287 // select X, C, (sext X) --> select X, C, 0
1288 // select X, C, (zext X) --> select X, C, 0
1289 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001290 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001291 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001292 }
1293
Sanjay Patel453ceff2016-09-29 22:18:30 +00001294 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001295}
1296
Sanjay Patelf26710d2016-09-16 22:16:18 +00001297/// Try to transform a vector select with a constant condition vector into a
1298/// shuffle for easier combining with other shuffles and insert/extract.
1299static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1300 Value *CondVal = SI.getCondition();
1301 Constant *CondC;
1302 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1303 return nullptr;
1304
1305 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1306 SmallVector<Constant *, 16> Mask;
1307 Mask.reserve(NumElts);
1308 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1309 for (unsigned i = 0; i != NumElts; ++i) {
1310 Constant *Elt = CondC->getAggregateElement(i);
1311 if (!Elt)
1312 return nullptr;
1313
1314 if (Elt->isOneValue()) {
1315 // If the select condition element is true, choose from the 1st vector.
1316 Mask.push_back(ConstantInt::get(Int32Ty, i));
1317 } else if (Elt->isNullValue()) {
1318 // If the select condition element is false, choose from the 2nd vector.
1319 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1320 } else if (isa<UndefValue>(Elt)) {
Sanjay Patel6e410182017-04-12 18:39:53 +00001321 // Undef in a select condition (choose one of the operands) does not mean
1322 // the same thing as undef in a shuffle mask (any value is acceptable), so
1323 // give up.
1324 return nullptr;
Sanjay Patelf26710d2016-09-16 22:16:18 +00001325 } else {
1326 // Bail out on a constant expression.
1327 return nullptr;
1328 }
1329 }
1330
1331 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1332 ConstantVector::get(Mask));
1333}
1334
Sanjay Patel978f8272016-10-29 15:22:04 +00001335/// Reuse bitcasted operands between a compare and select:
1336/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1337/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1338static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1339 InstCombiner::BuilderTy &Builder) {
1340 Value *Cond = Sel.getCondition();
1341 Value *TVal = Sel.getTrueValue();
1342 Value *FVal = Sel.getFalseValue();
1343
1344 CmpInst::Predicate Pred;
1345 Value *A, *B;
1346 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1347 return nullptr;
1348
1349 // The select condition is a compare instruction. If the select's true/false
1350 // values are already the same as the compare operands, there's nothing to do.
1351 if (TVal == A || TVal == B || FVal == A || FVal == B)
1352 return nullptr;
1353
1354 Value *C, *D;
1355 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1356 return nullptr;
1357
1358 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1359 Value *TSrc, *FSrc;
1360 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1361 !match(FVal, m_BitCast(m_Value(FSrc))))
1362 return nullptr;
1363
1364 // If the select true/false values are *different bitcasts* of the same source
1365 // operands, make the select operands the same as the compare operands and
1366 // cast the result. This is the canonical select form for min/max.
1367 Value *NewSel;
1368 if (TSrc == C && FSrc == D) {
1369 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1370 // bitcast (select (cmp A, B), A, B)
1371 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1372 } else if (TSrc == D && FSrc == C) {
1373 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1374 // bitcast (select (cmp A, B), B, A)
1375 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1376 } else {
1377 return nullptr;
1378 }
1379 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1380}
1381
Matthew Simpsonb6915fb2017-10-31 12:34:02 +00001382/// Try to eliminate select instructions that test the returned flag of cmpxchg
1383/// instructions.
1384///
1385/// If a select instruction tests the returned flag of a cmpxchg instruction and
1386/// selects between the returned value of the cmpxchg instruction its compare
1387/// operand, the result of the select will always be equal to its false value.
1388/// For example:
1389///
1390/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1391/// %1 = extractvalue { i64, i1 } %0, 1
1392/// %2 = extractvalue { i64, i1 } %0, 0
1393/// %3 = select i1 %1, i64 %compare, i64 %2
1394/// ret i64 %3
1395///
1396/// The returned value of the cmpxchg instruction (%2) is the original value
1397/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1398/// must have been equal to %compare. Thus, the result of the select is always
1399/// equal to %2, and the code can be simplified to:
1400///
1401/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1402/// %1 = extractvalue { i64, i1 } %0, 0
1403/// ret i64 %1
1404///
1405static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1406 // A helper that determines if V is an extractvalue instruction whose
1407 // aggregate operand is a cmpxchg instruction and whose single index is equal
1408 // to I. If such conditions are true, the helper returns the cmpxchg
1409 // instruction; otherwise, a nullptr is returned.
1410 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1411 auto *Extract = dyn_cast<ExtractValueInst>(V);
1412 if (!Extract)
1413 return nullptr;
1414 if (Extract->getIndices()[0] != I)
1415 return nullptr;
1416 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1417 };
1418
1419 // If the select has a single user, and this user is a select instruction that
1420 // we can simplify, skip the cmpxchg simplification for now.
1421 if (SI.hasOneUse())
1422 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1423 if (Select->getCondition() == SI.getCondition())
1424 if (Select->getFalseValue() == SI.getTrueValue() ||
1425 Select->getTrueValue() == SI.getFalseValue())
1426 return nullptr;
1427
1428 // Ensure the select condition is the returned flag of a cmpxchg instruction.
1429 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1430 if (!CmpXchg)
1431 return nullptr;
1432
1433 // Check the true value case: The true value of the select is the returned
1434 // value of the same cmpxchg used by the condition, and the false value is the
1435 // cmpxchg instruction's compare operand.
1436 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1437 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1438 SI.setTrueValue(SI.getFalseValue());
1439 return &SI;
1440 }
1441
1442 // Check the false value case: The false value of the select is the returned
1443 // value of the same cmpxchg used by the condition, and the true value is the
1444 // cmpxchg instruction's compare operand.
1445 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1446 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1447 SI.setTrueValue(SI.getFalseValue());
1448 return &SI;
1449 }
1450
1451 return nullptr;
1452}
1453
Sanjay Patel31b4b762018-01-08 15:05:34 +00001454/// Reduce a sequence of min/max with a common operand.
1455static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1456 Value *RHS,
1457 InstCombiner::BuilderTy &Builder) {
1458 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1459 // TODO: Allow FP min/max with nnan/nsz.
1460 if (!LHS->getType()->isIntOrIntVectorTy())
1461 return nullptr;
1462
1463 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1464 Value *A, *B, *C, *D;
1465 SelectPatternResult L = matchSelectPattern(LHS, A, B);
1466 SelectPatternResult R = matchSelectPattern(RHS, C, D);
1467 if (SPF != L.Flavor || L.Flavor != R.Flavor)
1468 return nullptr;
1469
1470 // Look for a common operand. The use checks are different than usual because
1471 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1472 // the select.
1473 Value *MinMaxOp = nullptr;
1474 Value *ThirdOp = nullptr;
Craig Topperee99aa42018-03-12 18:46:05 +00001475 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
Sanjay Patel31b4b762018-01-08 15:05:34 +00001476 // If the LHS is only used in this chain and the RHS is used outside of it,
1477 // reuse the RHS min/max because that will eliminate the LHS.
1478 if (D == A || C == A) {
1479 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1480 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1481 MinMaxOp = RHS;
1482 ThirdOp = B;
1483 } else if (D == B || C == B) {
1484 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1485 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1486 MinMaxOp = RHS;
1487 ThirdOp = A;
1488 }
Craig Topperee99aa42018-03-12 18:46:05 +00001489 } else if (!RHS->hasNUsesOrMore(3)) {
Sanjay Patel31b4b762018-01-08 15:05:34 +00001490 // Reuse the LHS. This will eliminate the RHS.
1491 if (D == A || D == B) {
1492 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1493 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1494 MinMaxOp = LHS;
1495 ThirdOp = C;
1496 } else if (C == A || C == B) {
1497 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1498 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1499 MinMaxOp = LHS;
1500 ThirdOp = D;
1501 }
1502 }
1503 if (!MinMaxOp || !ThirdOp)
1504 return nullptr;
1505
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001506 CmpInst::Predicate P = getMinMaxPred(SPF);
Sanjay Patel31b4b762018-01-08 15:05:34 +00001507 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1508 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1509}
1510
Chris Lattner8f771cb2010-01-05 06:03:12 +00001511Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1512 Value *CondVal = SI.getCondition();
1513 Value *TrueVal = SI.getTrueValue();
1514 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001515 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001516
Wei Mifc0e2452017-07-25 23:37:17 +00001517 // FIXME: Remove this workaround when freeze related patches are done.
1518 // For select with undef operand which feeds into an equality comparison,
1519 // don't simplify it so loop unswitch can know the equality comparison
1520 // may have an undef operand. This is a workaround for PR31652 caused by
1521 // descrepancy about branch on undef between LoopUnswitch and GVN.
1522 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001523 if (llvm::any_of(SI.users(), [&](User *U) {
Wei Mifc0e2452017-07-25 23:37:17 +00001524 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1525 if (CI && CI->isEquality())
1526 return true;
1527 return false;
1528 })) {
1529 return nullptr;
1530 }
1531 }
1532
Craig Toppera4205622017-06-09 03:21:29 +00001533 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1534 SQ.getWithInstruction(&SI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001535 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001536
Sanjay Patelf26710d2016-09-16 22:16:18 +00001537 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1538 return I;
1539
Sanjay Patel72272762017-06-27 17:53:22 +00001540 // Canonicalize a one-use integer compare with a non-canonical predicate by
1541 // inverting the predicate and swapping the select operands. This matches a
1542 // compare canonicalization for conditional branches.
1543 // TODO: Should we do the same for FP compares?
1544 CmpInst::Predicate Pred;
1545 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1546 !isCanonicalPredicate(Pred)) {
1547 // Swap true/false values and condition.
1548 CmpInst *Cond = cast<CmpInst>(CondVal);
1549 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1550 SI.setOperand(1, FalseVal);
1551 SI.setOperand(2, TrueVal);
1552 SI.swapProfMetadata();
1553 Worklist.Add(Cond);
1554 return &SI;
1555 }
1556
Craig Topperfde47232017-07-09 07:04:03 +00001557 if (SelType->isIntOrIntVectorTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001558 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001559 if (match(TrueVal, m_One())) {
1560 // Change: A = select B, true, C --> A = or B, C
1561 return BinaryOperator::CreateOr(CondVal, FalseVal);
1562 }
1563 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001564 // Change: A = select B, false, C --> A = and !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001565 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001566 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001567 }
Sanjay Patelea234362016-07-06 21:01:26 +00001568 if (match(FalseVal, m_Zero())) {
1569 // Change: A = select B, C, false --> A = and B, C
1570 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1571 }
1572 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001573 // Change: A = select B, C, true --> A = or !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001574 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001575 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001576 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001577
Sanjay Patela1a4e102016-07-03 14:08:19 +00001578 // select a, a, b -> a | b
1579 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001580 if (CondVal == TrueVal)
1581 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001582 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001583 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001584
Sanjay Patela1a4e102016-07-03 14:08:19 +00001585 // select a, ~a, b -> (~a) & b
1586 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001587 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1588 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001589 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001590 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001591 }
1592
Sanjay Patel65a51c22016-07-06 22:23:01 +00001593 // Selecting between two integer or vector splat integer constants?
1594 //
1595 // Note that we don't handle a scalar select of vectors:
1596 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1597 // because that may need 3 instructions to splat the condition value:
1598 // extend, insertelement, shufflevector.
Craig Toppere79b3e72017-07-09 03:25:17 +00001599 if (SelType->isIntOrIntVectorTy() &&
1600 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001601 // select C, 1, 0 -> zext C to int
1602 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001603 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001604
1605 // select C, -1, 0 -> sext C to int
1606 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001607 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001608
1609 // select C, 0, 1 -> zext !C to int
1610 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001611 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001612 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001613 }
1614
1615 // select C, 0, -1 -> sext !C to int
1616 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001617 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001618 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001619 }
1620 }
1621
Chris Lattner8f771cb2010-01-05 06:03:12 +00001622 // See if we are selecting two values based on a comparison of the two values.
1623 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1624 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1625 // Transform (X == Y) ? X : Y -> Y
1626 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001627 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001628 // consider X== -0, Y== +0.
1629 // It becomes safe if either operand is a nonzero constant.
1630 ConstantFP *CFPt, *CFPf;
1631 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1632 !CFPt->getValueAPF().isZero()) ||
1633 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1634 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001635 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001636 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001637 // Transform (X une Y) ? X : Y -> X
1638 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001639 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001640 // consider X== -0, Y== +0.
1641 // It becomes safe if either operand is a nonzero constant.
1642 ConstantFP *CFPt, *CFPf;
1643 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1644 !CFPt->getValueAPF().isZero()) ||
1645 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1646 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001647 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001648 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001649
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001650 // Canonicalize to use ordered comparisons by swapping the select
1651 // operands.
1652 //
1653 // e.g.
1654 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1655 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1656 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001657 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1658 Builder.setFastMathFlags(FCI->getFastMathFlags());
1659 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1660 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001661
1662 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1663 SI.getName() + ".p");
1664 }
1665
1666 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001667 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1668 // Transform (X == Y) ? Y : X -> X
1669 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001670 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001671 // consider X== -0, Y== +0.
1672 // It becomes safe if either operand is a nonzero constant.
1673 ConstantFP *CFPt, *CFPf;
1674 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1675 !CFPt->getValueAPF().isZero()) ||
1676 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1677 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001678 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001679 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001680 // Transform (X une Y) ? Y : X -> Y
1681 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001682 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001683 // consider X== -0, Y== +0.
1684 // It becomes safe if either operand is a nonzero constant.
1685 ConstantFP *CFPt, *CFPf;
1686 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1687 !CFPt->getValueAPF().isZero()) ||
1688 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1689 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001690 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001691 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001692
1693 // Canonicalize to use ordered comparisons by swapping the select
1694 // operands.
1695 //
1696 // e.g.
1697 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1698 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1699 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001700 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1701 Builder.setFastMathFlags(FCI->getFastMathFlags());
1702 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1703 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001704
1705 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1706 SI.getName() + ".p");
1707 }
1708
Chris Lattner8f771cb2010-01-05 06:03:12 +00001709 // NOTE: if we wanted to, this is where to detect MIN/MAX
1710 }
Sanjay Patel0ce30862018-03-19 15:14:30 +00001711
1712 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1713 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1714 // also require nnan because we do not want to unintentionally change the
1715 // sign of a NaN value.
1716 Value *X = FCI->getOperand(0);
1717 FCmpInst::Predicate Pred = FCI->getPredicate();
1718 if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1719 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1720 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
Sanjay Patel93e64dd2018-03-25 21:16:33 +00001721 if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1722 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1723 (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1724 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
Sanjay Patel0ce30862018-03-19 15:14:30 +00001725 Value *Fabs = Builder.CreateIntrinsic(Intrinsic::fabs, { X }, FCI);
1726 return replaceInstUsesWith(SI, Fabs);
1727 }
1728 // With nsz:
1729 // (X < +/-0.0) ? -X : X --> fabs(X)
1730 // (X <= +/-0.0) ? -X : X --> fabs(X)
1731 // (X > +/-0.0) ? X : -X --> fabs(X)
1732 // (X >= +/-0.0) ? X : -X --> fabs(X)
1733 if (FCI->hasNoSignedZeros() &&
1734 ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1735 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1736 (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1737 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1738 Value *Fabs = Builder.CreateIntrinsic(Intrinsic::fabs, { X }, FCI);
1739 return replaceInstUsesWith(SI, Fabs);
1740 }
1741 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001742 }
1743
1744 // See if we are selecting two values based on a comparison of the two values.
1745 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001746 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001747 return Result;
1748
Craig Topperbb4069e2017-07-07 23:16:26 +00001749 if (Instruction *Add = foldAddSubSelect(SI, Builder))
Sanjay Patel39293132016-06-08 21:10:01 +00001750 return Add;
1751
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001752 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001753 auto *TI = dyn_cast<Instruction>(TrueVal);
1754 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001755 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001756 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001757 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001758
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001759 if (Instruction *I = foldSelectExtConst(SI))
1760 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001761
Chris Lattner8f771cb2010-01-05 06:03:12 +00001762 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001763 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001764 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001765 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001766
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001767 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001768 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001769 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1770 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001771
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001772 if (SelectPatternResult::isMinOrMax(SPF)) {
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001773 // Canonicalize so that
1774 // - type casts are outside select patterns.
1775 // - float clamp is transformed to min/max pattern
1776
1777 bool IsCastNeeded = LHS->getType() != SelType;
1778 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1779 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1780 if (IsCastNeeded ||
1781 (LHS->getType()->isFPOrFPVectorTy() &&
1782 ((CmpLHS != LHS && CmpLHS != RHS) ||
1783 (CmpRHS != LHS && CmpRHS != RHS)))) {
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001784 CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
James Molloy134bec22015-08-11 09:12:57 +00001785
1786 Value *Cmp;
1787 if (CmpInst::isIntPredicate(Pred)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001788 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001789 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00001790 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
James Molloy134bec22015-08-11 09:12:57 +00001791 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Craig Topperbb4069e2017-07-07 23:16:26 +00001792 Builder.setFastMathFlags(FMF);
1793 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001794 }
1795
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001796 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1797 if (!IsCastNeeded)
1798 return replaceInstUsesWith(SI, NewSI);
1799
1800 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1801 return replaceInstUsesWith(SI, NewCast);
James Molloy2b21a7c2015-05-20 18:41:25 +00001802 }
Sanjay Patel5b6aacf2018-01-05 19:01:17 +00001803
1804 // MAX(~a, ~b) -> ~MIN(a, b)
1805 // MIN(~a, ~b) -> ~MAX(a, b)
1806 Value *A, *B;
Sanjay Patel26a6fcd2018-01-06 17:34:22 +00001807 if (match(LHS, m_Not(m_Value(A))) && match(RHS, m_Not(m_Value(B))) &&
1808 (LHS->getNumUses() <= 2 || RHS->getNumUses() <= 2)) {
Sanjay Patel7ed0bc22018-03-06 16:57:55 +00001809 CmpInst::Predicate InvertedPred = getInverseMinMaxPred(SPF);
Sanjay Patel5b6aacf2018-01-05 19:01:17 +00001810 Value *InvertedCmp = Builder.CreateICmp(InvertedPred, A, B);
1811 Value *NewSel = Builder.CreateSelect(InvertedCmp, A, B);
1812 return BinaryOperator::CreateNot(NewSel);
1813 }
Sanjay Patel31b4b762018-01-08 15:05:34 +00001814
1815 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1816 return I;
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001817 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001818
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001819 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001820 // MAX(MAX(a, b), a) -> MAX(a, b)
1821 // MIN(MIN(a, b), a) -> MIN(a, b)
1822 // MAX(MIN(a, b), a) -> a
1823 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001824 // ABS(ABS(a)) -> ABS(a)
1825 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001826 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001827 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001828 SI, SPF, RHS))
1829 return R;
James Molloy134bec22015-08-11 09:12:57 +00001830 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001831 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001832 SI, SPF, LHS))
1833 return R;
1834 }
1835
1836 // TODO.
1837 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001838 }
1839
1840 // See if we can fold the select into a phi node if the condition is a select.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001841 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001842 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001843 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1844 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Craig Topperfb71b7d2017-04-14 19:20:12 +00001845 if (Instruction *NV = foldOpIntoPhi(SI, PN))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001846 return NV;
1847
Nick Lewyckyb074e322011-01-28 03:28:10 +00001848 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001849 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1850 // select(C, select(C, a, b), c) -> select(C, a, c)
1851 if (TrueSI->getCondition() == CondVal) {
1852 if (SI.getTrueValue() == TrueSI->getTrueValue())
1853 return nullptr;
1854 SI.setOperand(1, TrueSI->getTrueValue());
1855 return &SI;
1856 }
1857 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1858 // We choose this as normal form to enable folding on the And and shortening
1859 // paths for the values (this helps GetUnderlyingObjects() for example).
1860 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001861 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001862 SI.setOperand(0, And);
1863 SI.setOperand(1, TrueSI->getTrueValue());
1864 return &SI;
1865 }
Matthias Braun2e404592015-02-06 17:49:36 +00001866 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001867 }
1868 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001869 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1870 // select(C, a, select(C, b, c)) -> select(C, a, c)
1871 if (FalseSI->getCondition() == CondVal) {
1872 if (SI.getFalseValue() == FalseSI->getFalseValue())
1873 return nullptr;
1874 SI.setOperand(2, FalseSI->getFalseValue());
1875 return &SI;
1876 }
1877 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1878 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001879 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001880 SI.setOperand(0, Or);
1881 SI.setOperand(2, FalseSI->getFalseValue());
1882 return &SI;
1883 }
Matthias Braun2e404592015-02-06 17:49:36 +00001884 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001885 }
1886
Craig Topper1c19cc12018-02-14 18:08:33 +00001887 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1888 // The select might be preventing a division by 0.
1889 switch (BO->getOpcode()) {
1890 default:
1891 return true;
1892 case Instruction::SRem:
1893 case Instruction::URem:
1894 case Instruction::SDiv:
1895 case Instruction::UDiv:
1896 return false;
1897 }
1898 };
1899
Craig Topperf7b86722017-11-15 05:23:02 +00001900 // Try to simplify a binop sandwiched between 2 selects with the same
1901 // condition.
1902 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1903 BinaryOperator *TrueBO;
Craig Topper1c19cc12018-02-14 18:08:33 +00001904 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1905 canMergeSelectThroughBinop(TrueBO)) {
Craig Topperf7b86722017-11-15 05:23:02 +00001906 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1907 if (TrueBOSI->getCondition() == CondVal) {
1908 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1909 Worklist.Add(TrueBO);
1910 return &SI;
1911 }
1912 }
1913 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1914 if (TrueBOSI->getCondition() == CondVal) {
1915 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1916 Worklist.Add(TrueBO);
1917 return &SI;
1918 }
1919 }
1920 }
1921
1922 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1923 BinaryOperator *FalseBO;
Craig Topper1c19cc12018-02-14 18:08:33 +00001924 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1925 canMergeSelectThroughBinop(FalseBO)) {
Craig Topperf7b86722017-11-15 05:23:02 +00001926 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1927 if (FalseBOSI->getCondition() == CondVal) {
1928 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1929 Worklist.Add(FalseBO);
1930 return &SI;
1931 }
1932 }
1933 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1934 if (FalseBOSI->getCondition() == CondVal) {
1935 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1936 Worklist.Add(FalseBO);
1937 return &SI;
1938 }
1939 }
1940 }
1941
Chris Lattner8f771cb2010-01-05 06:03:12 +00001942 if (BinaryOperator::isNot(CondVal)) {
1943 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1944 SI.setOperand(1, FalseVal);
1945 SI.setOperand(2, TrueVal);
1946 return &SI;
1947 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001948
Sanjay Patel4e463b42016-09-06 18:16:31 +00001949 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001950 unsigned VWidth = VecTy->getNumElements();
1951 APInt UndefElts(VWidth, 0);
1952 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1953 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1954 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001955 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001956 return &SI;
1957 }
1958 }
1959
Chad Rosiercd62bf52016-04-29 21:12:31 +00001960 // See if we can determine the result of this select based on a dominating
1961 // condition.
1962 BasicBlock *Parent = SI.getParent();
1963 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1964 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1965 if (PBI && PBI->isConditional() &&
1966 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1967 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
Chad Rosierdfd1de62017-08-01 20:18:54 +00001968 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
Chad Rosiercd62bf52016-04-29 21:12:31 +00001969 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00001970 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
Chad Rosiercd62bf52016-04-29 21:12:31 +00001971 if (Implication) {
1972 Value *V = *Implication ? TrueVal : FalseVal;
1973 return replaceInstUsesWith(SI, V);
1974 }
1975 }
1976 }
1977
Sanjay Patel51783632017-01-13 17:02:42 +00001978 // If we can compute the condition, there's no need for a select.
1979 // Like the above fold, we are attempting to reduce compile-time cost by
1980 // putting this fold here with limitations rather than in InstSimplify.
1981 // The motivation for this call into value tracking is to take advantage of
1982 // the assumption cache, so make sure that is populated.
1983 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001984 KnownBits Known(1);
1985 computeKnownBits(CondVal, Known, 0, &SI);
Craig Topper73ba1c82017-06-07 07:40:37 +00001986 if (Known.One.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001987 return replaceInstUsesWith(SI, TrueVal);
Craig Topper73ba1c82017-06-07 07:40:37 +00001988 if (Known.Zero.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001989 return replaceInstUsesWith(SI, FalseVal);
1990 }
1991
Craig Topperbb4069e2017-07-07 23:16:26 +00001992 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
Sanjay Patel978f8272016-10-29 15:22:04 +00001993 return BitCastSel;
1994
Matthew Simpsonb6915fb2017-10-31 12:34:02 +00001995 // Simplify selects that test the returned flag of cmpxchg instructions.
1996 if (Instruction *Select = foldSelectCmpXchg(SI))
1997 return Select;
1998
David Bolvansky6737b3a2018-07-30 20:38:53 +00001999 if (Instruction *Select = foldSelectBinOpIdentity(SI))
2000 return Select;
2001
Craig Topperf40110f2014-04-25 05:29:35 +00002002 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00002003}