blob: 876b8ce6ae4a7e50d31b1fdb46f9281168afb448 [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
Sanjoy Das08e95b42015-04-30 04:56:04 +000050static SelectPatternFlavor
51getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
52 switch (SPF) {
53 default:
54 llvm_unreachable("unhandled!");
55
56 case SPF_SMIN:
57 return SPF_SMAX;
58 case SPF_UMIN:
59 return SPF_UMAX;
60 case SPF_SMAX:
61 return SPF_SMIN;
62 case SPF_UMAX:
63 return SPF_UMIN;
64 }
65}
66
James Molloy134bec22015-08-11 09:12:57 +000067static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
68 bool Ordered=false) {
Sanjoy Das08e95b42015-04-30 04:56:04 +000069 switch (SPF) {
70 default:
71 llvm_unreachable("unhandled!");
72
73 case SPF_SMIN:
74 return ICmpInst::ICMP_SLT;
75 case SPF_UMIN:
76 return ICmpInst::ICMP_ULT;
77 case SPF_SMAX:
78 return ICmpInst::ICMP_SGT;
79 case SPF_UMAX:
80 return ICmpInst::ICMP_UGT;
James Molloy134bec22015-08-11 09:12:57 +000081 case SPF_FMINNUM:
82 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
83 case SPF_FMAXNUM:
84 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
Sanjoy Das08e95b42015-04-30 04:56:04 +000085 }
86}
87
Craig Topperbb4069e2017-07-07 23:16:26 +000088static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
Sanjoy Das08e95b42015-04-30 04:56:04 +000089 SelectPatternFlavor SPF, Value *A,
90 Value *B) {
James Molloy134bec22015-08-11 09:12:57 +000091 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
92 assert(CmpInst::isIntPredicate(Pred));
Craig Topperbb4069e2017-07-07 23:16:26 +000093 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
Sanjoy Das08e95b42015-04-30 04:56:04 +000094}
95
Craig Topper28d6d962017-09-05 05:26:37 +000096/// If one of the constants is zero (we know they can't both be) and we have an
97/// icmp instruction with zero, and we have an 'and' with the non-constant value
98/// and a power of two we can turn the select into a shift on the result of the
99/// 'and'.
100/// This folds:
101/// select (icmp eq (and X, C1)), C2, C3
102/// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
103/// To something like:
104/// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
105/// Or:
106/// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
107/// With some variations depending if C3 is larger than C2, or the shift
108/// isn't needed, or the bit widths don't match.
109static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
110 APInt TrueVal, APInt FalseVal,
111 InstCombiner::BuilderTy &Builder) {
112 assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
113
114 // If this is a vector select, we need a vector compare.
115 if (SelType->isVectorTy() != IC->getType()->isVectorTy())
116 return nullptr;
117
118 Value *V;
119 APInt AndMask;
120 bool CreateAnd = false;
121 ICmpInst::Predicate Pred = IC->getPredicate();
122 if (ICmpInst::isEquality(Pred)) {
123 if (!match(IC->getOperand(1), m_Zero()))
124 return nullptr;
125
126 V = IC->getOperand(0);
127
128 const APInt *AndRHS;
129 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
130 return nullptr;
131
132 AndMask = *AndRHS;
133 } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
134 Pred, V, AndMask)) {
135 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
136
137 if (!AndMask.isPowerOf2())
138 return nullptr;
139
140 CreateAnd = true;
141 } else {
142 return nullptr;
143 }
144
145 // If both select arms are non-zero see if we have a select of the form
146 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
147 // for 'x ? 2^n : 0' and fix the thing up at the end.
148 APInt Offset(TrueVal.getBitWidth(), 0);
149 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
150 if ((TrueVal - FalseVal).isPowerOf2())
151 Offset = FalseVal;
152 else if ((FalseVal - TrueVal).isPowerOf2())
153 Offset = TrueVal;
154 else
155 return nullptr;
156
157 // Adjust TrueVal and FalseVal to the offset.
158 TrueVal -= Offset;
159 FalseVal -= Offset;
160 }
161
162 // Make sure one of the select arms is a power of 2.
163 if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
164 return nullptr;
165
166 // Determine which shift is needed to transform result of the 'and' into the
167 // desired result.
168 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
169 unsigned ValZeros = ValC.logBase2();
170 unsigned AndZeros = AndMask.logBase2();
171
172 if (CreateAnd) {
173 // Insert the AND instruction on the input to the truncate.
174 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
175 }
176
177 // If types don't match we can still convert the select by introducing a zext
178 // or a trunc of the 'and'.
179 if (ValZeros > AndZeros) {
180 V = Builder.CreateZExtOrTrunc(V, SelType);
181 V = Builder.CreateShl(V, ValZeros - AndZeros);
182 } else if (ValZeros < AndZeros) {
183 V = Builder.CreateLShr(V, AndZeros - ValZeros);
184 V = Builder.CreateZExtOrTrunc(V, SelType);
185 } else
186 V = Builder.CreateZExtOrTrunc(V, SelType);
187
188 // Okay, now we know that everything is set up, we just don't know whether we
189 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
190 bool ShouldNotVal = !TrueVal.isNullValue();
191 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
192 if (ShouldNotVal)
193 V = Builder.CreateXor(V, ValC);
194
195 // Apply an offset if needed.
196 if (!Offset.isNullValue())
197 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
198 return V;
199}
200
Sanjay Patel6eccf482015-09-09 15:24:36 +0000201/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000202/// %C = or %A, %B
203/// %D = select %cond, %C, %A
204/// into:
205/// %C = select %cond, %B, 0
206/// %D = or %A, %C
207///
208/// Assuming that the specified instruction is an operand to the select, return
209/// a bitmask indicating which operands of this instruction are foldable if they
210/// equal the other incoming value of the select.
Craig Topper8e351e92017-08-08 06:19:24 +0000211static unsigned getSelectFoldableOperands(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000212 switch (I->getOpcode()) {
213 case Instruction::Add:
214 case Instruction::Mul:
215 case Instruction::And:
216 case Instruction::Or:
217 case Instruction::Xor:
218 return 3; // Can fold through either operand.
219 case Instruction::Sub: // Can only fold on the amount subtracted.
220 case Instruction::Shl: // Can only fold on the shift amount.
221 case Instruction::LShr:
222 case Instruction::AShr:
223 return 1;
224 default:
225 return 0; // Cannot fold
226 }
227}
228
Sanjay Patel6eccf482015-09-09 15:24:36 +0000229/// For the same transformation as the previous function, return the identity
230/// constant that goes into the select.
Craig Topper4c766a02017-09-05 05:26:36 +0000231static APInt getSelectFoldableConstant(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000232 switch (I->getOpcode()) {
233 default: llvm_unreachable("This cannot happen!");
234 case Instruction::Add:
235 case Instruction::Sub:
236 case Instruction::Or:
237 case Instruction::Xor:
238 case Instruction::Shl:
239 case Instruction::LShr:
240 case Instruction::AShr:
Craig Topper4c766a02017-09-05 05:26:36 +0000241 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000242 case Instruction::And:
Craig Topper4c766a02017-09-05 05:26:36 +0000243 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000244 case Instruction::Mul:
Craig Topper4c766a02017-09-05 05:26:36 +0000245 return APInt(I->getType()->getScalarSizeInBits(), 1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000246 }
247}
248
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000249/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000250Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000251 Instruction *FI) {
Sanjay Patel6105bb52017-03-16 20:42:45 +0000252 // Don't break up min/max patterns. The hasOneUse checks below prevent that
253 // for most cases, but vector min/max with bitcasts can be transformed. If the
254 // one-use restrictions are eased for other patterns, we still don't want to
255 // obfuscate min/max.
256 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
257 match(&SI, m_SMax(m_Value(), m_Value())) ||
258 match(&SI, m_UMin(m_Value(), m_Value())) ||
259 match(&SI, m_UMax(m_Value(), m_Value()))))
260 return nullptr;
261
Sanjay Patel384d0f22016-06-08 20:31:52 +0000262 // If this is a cast from the same type, merge.
263 if (TI->getNumOperands() == 1 && TI->isCast()) {
264 Type *FIOpndTy = FI->getOperand(0)->getType();
265 if (TI->getOperand(0)->getType() != FIOpndTy)
266 return nullptr;
267
268 // The select condition may be a vector. We may only change the operand
269 // type if the vector width remains the same (and matches the condition).
270 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000271 if (CondTy->isVectorTy()) {
272 if (!FIOpndTy->isVectorTy())
273 return nullptr;
274 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
275 return nullptr;
276
277 // TODO: If the backend knew how to deal with casts better, we could
278 // remove this limitation. For now, there's too much potential to create
279 // worse codegen by promoting the select ahead of size-altering casts
280 // (PR28160).
281 //
282 // Note that ValueTracking's matchSelectPattern() looks through casts
283 // without checking 'hasOneUse' when it matches min/max patterns, so this
284 // transform may end up happening anyway.
285 if (TI->getOpcode() != Instruction::BitCast &&
286 (!TI->hasOneUse() || !FI->hasOneUse()))
287 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000288 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
289 // TODO: The one-use restrictions for a scalar select could be eased if
290 // the fold of a select in visitLoadInst() was enhanced to match a pattern
291 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000292 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000293 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000294
295 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000296 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000297 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
298 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000299 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000300 TI->getType());
301 }
302
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000303 // Only handle binary operators with one-use here. As with the cast case
304 // above, it may be possible to relax the one-use constraint, but that needs
305 // be examined carefully since it may not reduce the total number of
306 // instructions.
Sanjay Patel84ae9432016-11-11 23:20:01 +0000307 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
308 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000309 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000310
311 // Figure out if the operations have any operands in common.
312 Value *MatchOp, *OtherOpT, *OtherOpF;
313 bool MatchIsOpZero;
314 if (TI->getOperand(0) == FI->getOperand(0)) {
315 MatchOp = TI->getOperand(0);
316 OtherOpT = TI->getOperand(1);
317 OtherOpF = FI->getOperand(1);
318 MatchIsOpZero = true;
319 } else if (TI->getOperand(1) == FI->getOperand(1)) {
320 MatchOp = TI->getOperand(1);
321 OtherOpT = TI->getOperand(0);
322 OtherOpF = FI->getOperand(0);
323 MatchIsOpZero = false;
324 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000325 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000326 } else if (TI->getOperand(0) == FI->getOperand(1)) {
327 MatchOp = TI->getOperand(0);
328 OtherOpT = TI->getOperand(1);
329 OtherOpF = FI->getOperand(0);
330 MatchIsOpZero = true;
331 } else if (TI->getOperand(1) == FI->getOperand(0)) {
332 MatchOp = TI->getOperand(1);
333 OtherOpT = TI->getOperand(0);
334 OtherOpF = FI->getOperand(1);
335 MatchIsOpZero = true;
336 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000337 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000338 }
339
340 // If we reach here, they do have operations in common.
Craig Topperbb4069e2017-07-07 23:16:26 +0000341 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
342 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000343 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
344 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
345 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000346}
347
Craig Topper4c766a02017-09-05 05:26:36 +0000348static bool isSelect01(const APInt &C1I, const APInt &C2I) {
349 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000350 return false;
Craig Topper4c766a02017-09-05 05:26:36 +0000351 return C1I.isOneValue() || C1I.isAllOnesValue() ||
352 C2I.isOneValue() || C2I.isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000353}
354
Sanjay Patel6eccf482015-09-09 15:24:36 +0000355/// Try to fold the select into one of the operands to allow further
356/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000357Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000358 Value *FalseVal) {
359 // See the comment above GetSelectFoldableOperands for a description of the
360 // transformation we are doing here.
Craig Topper8e351e92017-08-08 06:19:24 +0000361 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
362 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000363 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000364 unsigned OpToFold = 0;
365 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
366 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000367 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000368 OpToFold = 2;
369 }
370
371 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000372 APInt CI = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000373 Value *OOp = TVI->getOperand(2-OpToFold);
374 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000375 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000376 const APInt *OOpC;
377 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
378 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
379 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000380 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000381 NewSel->takeName(TVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000382 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000383 FalseVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000384 BO->copyIRFlags(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000385 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000386 }
387 }
388 }
389 }
390 }
391
Craig Topper8e351e92017-08-08 06:19:24 +0000392 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
393 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000394 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000395 unsigned OpToFold = 0;
396 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
397 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000398 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000399 OpToFold = 2;
400 }
401
402 if (OpToFold) {
Craig Topper4c766a02017-09-05 05:26:36 +0000403 APInt CI = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000404 Value *OOp = FVI->getOperand(2-OpToFold);
405 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000406 // between 0, 1 and -1.
Craig Topper4c766a02017-09-05 05:26:36 +0000407 const APInt *OOpC;
408 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
409 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
410 Value *C = ConstantInt::get(OOp->getType(), CI);
Craig Topperbb4069e2017-07-07 23:16:26 +0000411 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000412 NewSel->takeName(FVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000413 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000414 TrueVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000415 BO->copyIRFlags(FVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000416 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000417 }
418 }
419 }
420 }
421 }
422
Craig Topperf40110f2014-04-25 05:29:35 +0000423 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000424}
425
Sanjay Patel6eccf482015-09-09 15:24:36 +0000426/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000427/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
428/// into:
Craig Topperae86cc72017-06-21 16:07:13 +0000429/// (or (shl (and X, C1), C3), Y)
David Majnemer8d048d02013-04-30 08:57:58 +0000430/// iff:
431/// C1 and C2 are both powers of 2
432/// where:
433/// C3 = Log(C2) - Log(C1)
434///
435/// This transform handles cases where:
436/// 1. The icmp predicate is inverted
437/// 2. The select operands are reversed
438/// 3. The magnitude of C2 and C1 are flipped
Craig Topper5d6ddda2017-08-29 00:13:49 +0000439static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000440 Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000441 InstCombiner::BuilderTy &Builder) {
Craig Topper5d6ddda2017-08-29 00:13:49 +0000442 // Only handle integer compares. Also, if this is a vector select, we need a
443 // vector compare.
444 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
445 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000446 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000447
448 Value *CmpLHS = IC->getOperand(0);
449 Value *CmpRHS = IC->getOperand(1);
450
Craig Topperdffbbcb2017-06-22 16:23:30 +0000451 Value *V;
452 unsigned C1Log;
453 bool IsEqualZero;
454 bool NeedAnd = false;
455 if (IC->isEquality()) {
456 if (!match(CmpRHS, m_Zero()))
457 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000458
Craig Topperdffbbcb2017-06-22 16:23:30 +0000459 const APInt *C1;
460 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
461 return nullptr;
462
463 V = CmpLHS;
464 C1Log = C1->logBase2();
465 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
466 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
467 IC->getPredicate() == ICmpInst::ICMP_SGT) {
468 // We also need to recognize (icmp slt (trunc (X)), 0) and
469 // (icmp sgt (trunc (X)), -1).
470 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
471 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
472 (!IsEqualZero && !match(CmpRHS, m_Zero())))
473 return nullptr;
474
475 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
476 return nullptr;
477
478 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
479 NeedAnd = true;
480 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000481 return nullptr;
Craig Topperdffbbcb2017-06-22 16:23:30 +0000482 }
David Majnemer8d048d02013-04-30 08:57:58 +0000483
484 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000485 bool OrOnTrueVal = false;
486 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
487 if (!OrOnFalseVal)
488 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000489
490 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000491 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000492
David Majnemer8d048d02013-04-30 08:57:58 +0000493 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
494
David Majnemer8d048d02013-04-30 08:57:58 +0000495 unsigned C2Log = C2->logBase2();
Craig Topperae86cc72017-06-21 16:07:13 +0000496
Craig Topperdffbbcb2017-06-22 16:23:30 +0000497 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
Craig Topperae86cc72017-06-21 16:07:13 +0000498 bool NeedShift = C1Log != C2Log;
Craig Topper5d6ddda2017-08-29 00:13:49 +0000499 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
500 V->getType()->getScalarSizeInBits();
Craig Topperae86cc72017-06-21 16:07:13 +0000501
502 // Make sure we don't create more instructions than we save.
503 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
504 if ((NeedShift + NeedXor + NeedZExtTrunc) >
505 (IC->hasOneUse() + Or->hasOneUse()))
506 return nullptr;
507
Craig Topperdffbbcb2017-06-22 16:23:30 +0000508 if (NeedAnd) {
509 // Insert the AND instruction on the input to the truncate.
510 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
Craig Topperbb4069e2017-07-07 23:16:26 +0000511 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
Craig Topperdffbbcb2017-06-22 16:23:30 +0000512 }
513
David Majnemer8d048d02013-04-30 08:57:58 +0000514 if (C2Log > C1Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000515 V = Builder.CreateZExtOrTrunc(V, Y->getType());
516 V = Builder.CreateShl(V, C2Log - C1Log);
David Majnemer8d048d02013-04-30 08:57:58 +0000517 } else if (C1Log > C2Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000518 V = Builder.CreateLShr(V, C1Log - C2Log);
519 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000520 } else
Craig Topperbb4069e2017-07-07 23:16:26 +0000521 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000522
Craig Topperae86cc72017-06-21 16:07:13 +0000523 if (NeedXor)
Craig Topperbb4069e2017-07-07 23:16:26 +0000524 V = Builder.CreateXor(V, *C2);
David Majnemer8d048d02013-04-30 08:57:58 +0000525
Craig Topperbb4069e2017-07-07 23:16:26 +0000526 return Builder.CreateOr(V, Y);
David Majnemer8d048d02013-04-30 08:57:58 +0000527}
528
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000529/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
530/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
531///
532/// For example, we can fold the following code sequence:
533/// \code
534/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
535/// %1 = icmp ne i32 %x, 0
536/// %2 = select i1 %1, i32 %0, i32 32
537/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000538///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000539/// into:
540/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
541static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000542 InstCombiner::BuilderTy &Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000543 ICmpInst::Predicate Pred = ICI->getPredicate();
544 Value *CmpLHS = ICI->getOperand(0);
545 Value *CmpRHS = ICI->getOperand(1);
546
547 // Check if the condition value compares a value for equality against zero.
548 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
549 return nullptr;
550
551 Value *Count = FalseVal;
552 Value *ValueOnZero = TrueVal;
553 if (Pred == ICmpInst::ICMP_NE)
554 std::swap(Count, ValueOnZero);
555
556 // Skip zero extend/truncate.
557 Value *V = nullptr;
558 if (match(Count, m_ZExt(m_Value(V))) ||
559 match(Count, m_Trunc(m_Value(V))))
560 Count = V;
561
562 // Check if the value propagated on zero is a constant number equal to the
563 // sizeof in bits of 'Count'.
564 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
565 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
566 return nullptr;
567
568 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
569 // input to the cttz/ctlz is used as LHS for the compare instruction.
570 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
571 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
572 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000573 // Explicitly clear the 'undef_on_zero' flag.
574 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Craig Topper3b74a682017-08-04 16:07:18 +0000575 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
Craig Topperbb4069e2017-07-07 23:16:26 +0000576 Builder.Insert(NewI);
577 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000578 }
579
580 return nullptr;
581}
582
Sanjay Patel7ce65832016-11-01 17:46:08 +0000583/// Return true if we find and adjust an icmp+select pattern where the compare
584/// is with a constant that can be incremented or decremented to match the
585/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000586static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
587 ICmpInst::Predicate Pred = Cmp.getPredicate();
588 Value *CmpLHS = Cmp.getOperand(0);
589 Value *CmpRHS = Cmp.getOperand(1);
590 Value *TrueVal = Sel.getTrueValue();
591 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000592
Sanjay Patel644d7c32016-11-01 18:15:03 +0000593 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000594 const APInt *CmpC;
595 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000596 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000597
Sanjay Patel86408a82016-11-07 15:52:45 +0000598 // These transforms only work for selects of integers or vector selects of
599 // integer vectors.
600 Type *SelTy = Sel.getType();
601 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
602 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000603 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000604
Sanjay Patel644d7c32016-11-01 18:15:03 +0000605 Constant *AdjustedRHS;
606 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000607 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000608 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000609 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000610 else
611 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000612
Sanjay Patel644d7c32016-11-01 18:15:03 +0000613 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
614 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
615 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
616 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
617 ; // Nothing to do here. Values match without any sign/zero extension.
618 }
619 // Types do not match. Instead of calculating this with mixed types, promote
620 // all to the larger type. This enables scalar evolution to analyze this
621 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000622 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
623 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000624
Sanjay Patel644d7c32016-11-01 18:15:03 +0000625 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
626 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
627 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
628 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
629 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
630 CmpLHS = TrueVal;
631 AdjustedRHS = SextRHS;
632 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
633 SextRHS == TrueVal) {
634 CmpLHS = FalseVal;
635 AdjustedRHS = SextRHS;
636 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000637 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000638 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
639 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
640 // zext + signed compare cannot be changed:
641 // 0xff <s 0x00, but 0x00ff >s 0x0000
642 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
643 CmpLHS = TrueVal;
644 AdjustedRHS = ZextRHS;
645 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
646 ZextRHS == TrueVal) {
647 CmpLHS = FalseVal;
648 AdjustedRHS = ZextRHS;
649 } else {
650 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000651 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000652 } else {
653 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000654 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000655 } else {
656 return false;
657 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000658
Sanjay Patel644d7c32016-11-01 18:15:03 +0000659 Pred = ICmpInst::getSwappedPredicate(Pred);
660 CmpRHS = AdjustedRHS;
661 std::swap(FalseVal, TrueVal);
662 Cmp.setPredicate(Pred);
663 Cmp.setOperand(0, CmpLHS);
664 Cmp.setOperand(1, CmpRHS);
665 Sel.setOperand(1, TrueVal);
666 Sel.setOperand(2, FalseVal);
667 Sel.swapProfMetadata();
668
669 // Move the compare instruction right before the select instruction. Otherwise
670 // the sext/zext value may be defined after the compare instruction uses it.
671 Cmp.moveBefore(&Sel);
672
673 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000674}
675
Sanjay Patelcb731f12017-02-21 19:33:53 +0000676/// If this is an integer min/max (icmp + select) with a constant operand,
677/// create the canonical icmp for the min/max operation and canonicalize the
678/// constant to the 'false' operand of the select:
679/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
680/// Note: if C1 != C2, this will change the icmp constant to the existing
681/// constant operand of the select.
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000682static Instruction *
683canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
684 InstCombiner::BuilderTy &Builder) {
Sanjay Patelcb731f12017-02-21 19:33:53 +0000685 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000686 return nullptr;
687
688 // Canonicalize the compare predicate based on whether we have min or max.
689 Value *LHS, *RHS;
690 ICmpInst::Predicate NewPred;
691 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
692 switch (SPR.Flavor) {
693 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
694 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
695 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
696 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
697 default: return nullptr;
698 }
699
Sanjay Patelcb731f12017-02-21 19:33:53 +0000700 // Is this already canonical?
701 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
702 Cmp.getPredicate() == NewPred)
703 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000704
Sanjay Patelcb731f12017-02-21 19:33:53 +0000705 // Create the canonical compare and plug it into the select.
706 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000707
Sanjay Patelcb731f12017-02-21 19:33:53 +0000708 // If the select operands did not change, we're done.
709 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
710 return &Sel;
711
712 // If we are swapping the select operands, swap the metadata too.
713 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
714 "Unexpected results from matchSelectPattern");
715 Sel.setTrueValue(LHS);
716 Sel.setFalseValue(RHS);
717 Sel.swapProfMetadata();
718 return &Sel;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000719}
720
Sanjay Patel7ce65832016-11-01 17:46:08 +0000721/// Visit a SelectInst that has an ICmpInst as its first operand.
722Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
723 ICmpInst *ICI) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000724 Value *TrueVal = SI.getTrueValue();
725 Value *FalseVal = SI.getFalseValue();
726
Craig Topperbb4069e2017-07-07 23:16:26 +0000727 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000728 return NewSel;
729
Sanjay Patel644d7c32016-11-01 18:15:03 +0000730 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000731
732 ICmpInst::Predicate Pred = ICI->getPredicate();
733 Value *CmpLHS = ICI->getOperand(0);
734 Value *CmpRHS = ICI->getOperand(1);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000735
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000736 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
737 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
738 // FIXME: Type and constness constraints could be lifted, but we have to
739 // watch code size carefully. We should consider xor instead of
740 // sub/add when we decide to do that.
Craig Topper74177e12017-08-21 19:02:06 +0000741 // TODO: Merge this with foldSelectICmpAnd somehow.
Craig Topper882f2962017-08-16 21:52:07 +0000742 if (CmpLHS->getType()->isIntOrIntVectorTy() &&
743 CmpLHS->getType() == TrueVal->getType()) {
744 const APInt *C1, *C2;
745 if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
746 ICmpInst::Predicate Pred = ICI->getPredicate();
747 Value *X;
748 APInt Mask;
Craig Topper924f2022017-09-01 21:27:34 +0000749 if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
Craig Topper882f2962017-08-16 21:52:07 +0000750 if (Mask.isSignMask()) {
751 assert(X == CmpLHS && "Expected to use the compare input directly");
752 assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
753
754 if (Pred == ICmpInst::ICMP_NE)
755 std::swap(C1, C2);
756
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000757 // This shift results in either -1 or 0.
Craig Topper882f2962017-08-16 21:52:07 +0000758 Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000759
760 // Check if we can express the operation with a single or.
Craig Topper882f2962017-08-16 21:52:07 +0000761 if (C2->isAllOnesValue())
762 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000763
Craig Topper882f2962017-08-16 21:52:07 +0000764 Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
765 return replaceInstUsesWith(SI, Builder.CreateAdd(And,
766 ConstantInt::get(And->getType(), *C1)));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000767 }
768 }
769 }
770 }
771
Craig Topper74177e12017-08-21 19:02:06 +0000772 {
773 const APInt *TrueValC, *FalseValC;
774 if (match(TrueVal, m_APInt(TrueValC)) &&
775 match(FalseVal, m_APInt(FalseValC)))
776 if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
777 *FalseValC, Builder))
778 return replaceInstUsesWith(SI, V);
779 }
780
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000781 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
782
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000783 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000784 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
785 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
786 SI.setOperand(1, CmpRHS);
787 Changed = true;
788 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
789 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
790 SI.setOperand(2, CmpRHS);
791 Changed = true;
792 }
793 }
794
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000795 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
796 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000797 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000798 unsigned BitWidth =
799 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
Craig Topperbcfd2d12017-04-20 16:56:25 +0000800 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000801 Value *X;
802 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000803 bool TrueWhenUnset;
804 bool IsBitTest = false;
805 if (ICmpInst::isEquality(Pred) &&
806 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000807 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000808 IsBitTest = true;
809 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
810 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
811 X = CmpLHS;
812 Y = &MinSignedValue;
813 IsBitTest = true;
814 TrueWhenUnset = false;
815 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
816 X = CmpLHS;
817 Y = &MinSignedValue;
818 IsBitTest = true;
819 TrueWhenUnset = true;
820 }
821 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000822 Value *V = nullptr;
823 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000824 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000825 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000826 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000827 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000828 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000829 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000830 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000831 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000832 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000833 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000834 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000835 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000836 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000837 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000838 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000839
840 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000841 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000842 }
843 }
844
Craig Topper5d6ddda2017-08-29 00:13:49 +0000845 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000846 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000847
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000848 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000849 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000850
Craig Topperf40110f2014-04-25 05:29:35 +0000851 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000852}
853
854
Sanjay Patel6eccf482015-09-09 15:24:36 +0000855/// SI is a select whose condition is a PHI node (but the two may be in
856/// different blocks). See if the true/false values (V) are live in all of the
857/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000858///
859/// X = phi [ C1, BB1], [C2, BB2]
860/// Y = add
861/// Z = select X, Y, 0
862///
863/// because Y is not live in BB1/BB2.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000864static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000865 const SelectInst &SI) {
866 // If the value is a non-instruction value like a constant or argument, it
867 // can always be mapped.
868 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000869 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000870
Chris Lattner8f771cb2010-01-05 06:03:12 +0000871 // If V is a PHI node defined in the same block as the condition PHI, we can
872 // map the arguments.
873 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000874
Chris Lattner8f771cb2010-01-05 06:03:12 +0000875 if (const PHINode *VP = dyn_cast<PHINode>(I))
876 if (VP->getParent() == CondPHI->getParent())
877 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000878
Chris Lattner8f771cb2010-01-05 06:03:12 +0000879 // Otherwise, if the PHI and select are defined in the same block and if V is
880 // defined in a different block, then we can transform it.
881 if (SI.getParent() == CondPHI->getParent() &&
882 I->getParent() != CondPHI->getParent())
883 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000884
Chris Lattner8f771cb2010-01-05 06:03:12 +0000885 // Otherwise we have a 'hard' case and we can't tell without doing more
886 // detailed dominator based analysis, punt.
887 return false;
888}
889
Sanjay Patel6eccf482015-09-09 15:24:36 +0000890/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000891/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000892Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000893 SelectPatternFlavor SPF1,
894 Value *A, Value *B,
895 Instruction &Outer,
896 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000897 if (Outer.getType() != Inner->getType())
898 return nullptr;
899
Chris Lattner8f771cb2010-01-05 06:03:12 +0000900 if (C == A || C == B) {
901 // MAX(MAX(A, B), B) -> MAX(A, B)
902 // MIN(MIN(a, b), a) -> MIN(a, b)
903 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000904 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000905
Chris Lattner8f771cb2010-01-05 06:03:12 +0000906 // MAX(MIN(a, b), a) -> a
907 // MIN(MAX(a, b), a) -> a
908 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
909 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
910 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
911 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000912 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000913 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000914
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000915 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000916 const APInt *CB, *CC;
917 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
918 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
919 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
920 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
921 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
922 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
923 (SPF1 == SPF_SMAX && CB->sge(*CC)))
924 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000925
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000926 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
927 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
928 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
929 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
930 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
931 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
932 Outer.replaceUsesOfWith(Inner, A);
933 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000934 }
935 }
936 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000937
938 // ABS(ABS(X)) -> ABS(X)
939 // NABS(NABS(X)) -> NABS(X)
940 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000941 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000942 }
943
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000944 // ABS(NABS(X)) -> ABS(X)
945 // NABS(ABS(X)) -> NABS(X)
946 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
947 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
948 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000949 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000950 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
951 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000952 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000953 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000954
955 auto IsFreeOrProfitableToInvert =
956 [&](Value *V, Value *&NotV, bool &ElidesXor) {
957 if (match(V, m_Not(m_Value(NotV)))) {
958 // If V has at most 2 uses then we can get rid of the xor operation
959 // entirely.
960 ElidesXor |= !V->hasNUsesOrMore(3);
961 return true;
962 }
963
964 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
965 NotV = nullptr;
966 return true;
967 }
968
969 return false;
970 };
971
972 Value *NotA, *NotB, *NotC;
973 bool ElidesXor = false;
974
975 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
976 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
977 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
978 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
979 //
980 // This transform is performance neutral if we can elide at least one xor from
981 // the set of three operands, since we'll be tacking on an xor at the very
982 // end.
Anna Thomasec36f3b2017-02-21 14:40:28 +0000983 if (SelectPatternResult::isMinOrMax(SPF1) &&
984 SelectPatternResult::isMinOrMax(SPF2) &&
985 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
Sanjoy Das08e95b42015-04-30 04:56:04 +0000986 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
987 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
988 if (!NotA)
Craig Topperbb4069e2017-07-07 23:16:26 +0000989 NotA = Builder.CreateNot(A);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000990 if (!NotB)
Craig Topperbb4069e2017-07-07 23:16:26 +0000991 NotB = Builder.CreateNot(B);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000992 if (!NotC)
Craig Topperbb4069e2017-07-07 23:16:26 +0000993 NotC = Builder.CreateNot(C);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000994
995 Value *NewInner = generateMinMaxSelectPattern(
996 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
Craig Topperbb4069e2017-07-07 23:16:26 +0000997 Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
Sanjoy Das08e95b42015-04-30 04:56:04 +0000998 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000999 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +00001000 }
1001
Craig Topperf40110f2014-04-25 05:29:35 +00001002 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001003}
1004
Sanjay Patel39293132016-06-08 21:10:01 +00001005/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1006/// This is even legal for FP.
1007static Instruction *foldAddSubSelect(SelectInst &SI,
1008 InstCombiner::BuilderTy &Builder) {
1009 Value *CondVal = SI.getCondition();
1010 Value *TrueVal = SI.getTrueValue();
1011 Value *FalseVal = SI.getFalseValue();
1012 auto *TI = dyn_cast<Instruction>(TrueVal);
1013 auto *FI = dyn_cast<Instruction>(FalseVal);
1014 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1015 return nullptr;
1016
1017 Instruction *AddOp = nullptr, *SubOp = nullptr;
1018 if ((TI->getOpcode() == Instruction::Sub &&
1019 FI->getOpcode() == Instruction::Add) ||
1020 (TI->getOpcode() == Instruction::FSub &&
1021 FI->getOpcode() == Instruction::FAdd)) {
1022 AddOp = FI;
1023 SubOp = TI;
1024 } else if ((FI->getOpcode() == Instruction::Sub &&
1025 TI->getOpcode() == Instruction::Add) ||
1026 (FI->getOpcode() == Instruction::FSub &&
1027 TI->getOpcode() == Instruction::FAdd)) {
1028 AddOp = TI;
1029 SubOp = FI;
1030 }
1031
1032 if (AddOp) {
1033 Value *OtherAddOp = nullptr;
1034 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1035 OtherAddOp = AddOp->getOperand(1);
1036 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1037 OtherAddOp = AddOp->getOperand(0);
1038 }
1039
1040 if (OtherAddOp) {
1041 // So at this point we know we have (Y -> OtherAddOp):
1042 // select C, (add X, Y), (sub X, Z)
1043 Value *NegVal; // Compute -Z
1044 if (SI.getType()->isFPOrFPVectorTy()) {
1045 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1046 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1047 FastMathFlags Flags = AddOp->getFastMathFlags();
1048 Flags &= SubOp->getFastMathFlags();
1049 NegInst->setFastMathFlags(Flags);
1050 }
1051 } else {
1052 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1053 }
1054
1055 Value *NewTrueOp = OtherAddOp;
1056 Value *NewFalseOp = NegVal;
1057 if (AddOp != TI)
1058 std::swap(NewTrueOp, NewFalseOp);
1059 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +00001060 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +00001061
1062 if (SI.getType()->isFPOrFPVectorTy()) {
1063 Instruction *RI =
1064 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1065
1066 FastMathFlags Flags = AddOp->getFastMathFlags();
1067 Flags &= SubOp->getFastMathFlags();
1068 RI->setFastMathFlags(Flags);
1069 return RI;
1070 } else
1071 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1072 }
1073 }
1074 return nullptr;
1075}
1076
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001077Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1078 Instruction *ExtInst;
1079 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1080 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1081 return nullptr;
1082
1083 auto ExtOpcode = ExtInst->getOpcode();
1084 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1085 return nullptr;
1086
Sanjay Patel453ceff2016-09-29 22:18:30 +00001087 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001088 Value *X = ExtInst->getOperand(0);
1089 Type *SmallType = X->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001090 if (!SmallType->isIntOrIntVectorTy(1))
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001091 return nullptr;
1092
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001093 Constant *C;
1094 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1095 !match(Sel.getFalseValue(), m_Constant(C)))
1096 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001097
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001098 // If the constant is the same after truncation to the smaller type and
1099 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001100 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001101 Type *SelType = Sel.getType();
1102 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1103 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1104 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001105 Value *TruncCVal = cast<Value>(TruncC);
1106 if (ExtInst == Sel.getFalseValue())
1107 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001108
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001109 // select Cond, (ext X), C --> ext(select Cond, X, C')
1110 // select Cond, C, (ext X) --> ext(select Cond, C', X)
Craig Topperbb4069e2017-07-07 23:16:26 +00001111 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001112 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +00001113 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001114
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001115 // If one arm of the select is the extend of the condition, replace that arm
1116 // with the extension of the appropriate known bool value.
1117 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001118 if (ExtInst == Sel.getTrueValue()) {
1119 // select X, (sext X), C --> select X, -1, C
1120 // select X, (zext X), C --> select X, 1, C
1121 Constant *One = ConstantInt::getTrue(SmallType);
1122 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001123 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001124 } else {
1125 // select X, C, (sext X) --> select X, C, 0
1126 // select X, C, (zext X) --> select X, C, 0
1127 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001128 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001129 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001130 }
1131
Sanjay Patel453ceff2016-09-29 22:18:30 +00001132 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001133}
1134
Sanjay Patelf26710d2016-09-16 22:16:18 +00001135/// Try to transform a vector select with a constant condition vector into a
1136/// shuffle for easier combining with other shuffles and insert/extract.
1137static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1138 Value *CondVal = SI.getCondition();
1139 Constant *CondC;
1140 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1141 return nullptr;
1142
1143 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1144 SmallVector<Constant *, 16> Mask;
1145 Mask.reserve(NumElts);
1146 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1147 for (unsigned i = 0; i != NumElts; ++i) {
1148 Constant *Elt = CondC->getAggregateElement(i);
1149 if (!Elt)
1150 return nullptr;
1151
1152 if (Elt->isOneValue()) {
1153 // If the select condition element is true, choose from the 1st vector.
1154 Mask.push_back(ConstantInt::get(Int32Ty, i));
1155 } else if (Elt->isNullValue()) {
1156 // If the select condition element is false, choose from the 2nd vector.
1157 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1158 } else if (isa<UndefValue>(Elt)) {
Sanjay Patel6e410182017-04-12 18:39:53 +00001159 // Undef in a select condition (choose one of the operands) does not mean
1160 // the same thing as undef in a shuffle mask (any value is acceptable), so
1161 // give up.
1162 return nullptr;
Sanjay Patelf26710d2016-09-16 22:16:18 +00001163 } else {
1164 // Bail out on a constant expression.
1165 return nullptr;
1166 }
1167 }
1168
1169 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1170 ConstantVector::get(Mask));
1171}
1172
Sanjay Patel978f8272016-10-29 15:22:04 +00001173/// Reuse bitcasted operands between a compare and select:
1174/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1175/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1176static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1177 InstCombiner::BuilderTy &Builder) {
1178 Value *Cond = Sel.getCondition();
1179 Value *TVal = Sel.getTrueValue();
1180 Value *FVal = Sel.getFalseValue();
1181
1182 CmpInst::Predicate Pred;
1183 Value *A, *B;
1184 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1185 return nullptr;
1186
1187 // The select condition is a compare instruction. If the select's true/false
1188 // values are already the same as the compare operands, there's nothing to do.
1189 if (TVal == A || TVal == B || FVal == A || FVal == B)
1190 return nullptr;
1191
1192 Value *C, *D;
1193 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1194 return nullptr;
1195
1196 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1197 Value *TSrc, *FSrc;
1198 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1199 !match(FVal, m_BitCast(m_Value(FSrc))))
1200 return nullptr;
1201
1202 // If the select true/false values are *different bitcasts* of the same source
1203 // operands, make the select operands the same as the compare operands and
1204 // cast the result. This is the canonical select form for min/max.
1205 Value *NewSel;
1206 if (TSrc == C && FSrc == D) {
1207 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1208 // bitcast (select (cmp A, B), A, B)
1209 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1210 } else if (TSrc == D && FSrc == C) {
1211 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1212 // bitcast (select (cmp A, B), B, A)
1213 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1214 } else {
1215 return nullptr;
1216 }
1217 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1218}
1219
Chris Lattner8f771cb2010-01-05 06:03:12 +00001220Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1221 Value *CondVal = SI.getCondition();
1222 Value *TrueVal = SI.getTrueValue();
1223 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001224 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001225
Wei Mifc0e2452017-07-25 23:37:17 +00001226 // FIXME: Remove this workaround when freeze related patches are done.
1227 // For select with undef operand which feeds into an equality comparison,
1228 // don't simplify it so loop unswitch can know the equality comparison
1229 // may have an undef operand. This is a workaround for PR31652 caused by
1230 // descrepancy about branch on undef between LoopUnswitch and GVN.
1231 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001232 if (llvm::any_of(SI.users(), [&](User *U) {
Wei Mifc0e2452017-07-25 23:37:17 +00001233 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1234 if (CI && CI->isEquality())
1235 return true;
1236 return false;
1237 })) {
1238 return nullptr;
1239 }
1240 }
1241
Craig Toppera4205622017-06-09 03:21:29 +00001242 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1243 SQ.getWithInstruction(&SI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001244 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001245
Sanjay Patelf26710d2016-09-16 22:16:18 +00001246 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1247 return I;
1248
Sanjay Patel72272762017-06-27 17:53:22 +00001249 // Canonicalize a one-use integer compare with a non-canonical predicate by
1250 // inverting the predicate and swapping the select operands. This matches a
1251 // compare canonicalization for conditional branches.
1252 // TODO: Should we do the same for FP compares?
1253 CmpInst::Predicate Pred;
1254 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1255 !isCanonicalPredicate(Pred)) {
1256 // Swap true/false values and condition.
1257 CmpInst *Cond = cast<CmpInst>(CondVal);
1258 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1259 SI.setOperand(1, FalseVal);
1260 SI.setOperand(2, TrueVal);
1261 SI.swapProfMetadata();
1262 Worklist.Add(Cond);
1263 return &SI;
1264 }
1265
Craig Topperfde47232017-07-09 07:04:03 +00001266 if (SelType->isIntOrIntVectorTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001267 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001268 if (match(TrueVal, m_One())) {
1269 // Change: A = select B, true, C --> A = or B, C
1270 return BinaryOperator::CreateOr(CondVal, FalseVal);
1271 }
1272 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001273 // Change: A = select B, false, C --> A = and !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001274 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001275 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001276 }
Sanjay Patelea234362016-07-06 21:01:26 +00001277 if (match(FalseVal, m_Zero())) {
1278 // Change: A = select B, C, false --> A = and B, C
1279 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1280 }
1281 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001282 // Change: A = select B, C, true --> A = or !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001283 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001284 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001285 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001286
Sanjay Patela1a4e102016-07-03 14:08:19 +00001287 // select a, a, b -> a | b
1288 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001289 if (CondVal == TrueVal)
1290 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001291 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001292 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001293
Sanjay Patela1a4e102016-07-03 14:08:19 +00001294 // select a, ~a, b -> (~a) & b
1295 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001296 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1297 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001298 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001299 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001300 }
1301
Sanjay Patel65a51c22016-07-06 22:23:01 +00001302 // Selecting between two integer or vector splat integer constants?
1303 //
1304 // Note that we don't handle a scalar select of vectors:
1305 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1306 // because that may need 3 instructions to splat the condition value:
1307 // extend, insertelement, shufflevector.
Craig Toppere79b3e72017-07-09 03:25:17 +00001308 if (SelType->isIntOrIntVectorTy() &&
1309 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001310 // select C, 1, 0 -> zext C to int
1311 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001312 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001313
1314 // select C, -1, 0 -> sext C to int
1315 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001316 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001317
1318 // select C, 0, 1 -> zext !C to int
1319 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001320 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001321 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001322 }
1323
1324 // select C, 0, -1 -> sext !C to int
1325 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001326 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001327 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001328 }
1329 }
1330
Chris Lattner8f771cb2010-01-05 06:03:12 +00001331 // See if we are selecting two values based on a comparison of the two values.
1332 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1333 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1334 // Transform (X == Y) ? X : Y -> Y
1335 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001336 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001337 // consider X== -0, Y== +0.
1338 // It becomes safe if either operand is a nonzero constant.
1339 ConstantFP *CFPt, *CFPf;
1340 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1341 !CFPt->getValueAPF().isZero()) ||
1342 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1343 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001344 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001345 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001346 // Transform (X une Y) ? X : Y -> X
1347 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001348 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001349 // consider X== -0, Y== +0.
1350 // It becomes safe if either operand is a nonzero constant.
1351 ConstantFP *CFPt, *CFPf;
1352 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1353 !CFPt->getValueAPF().isZero()) ||
1354 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1355 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001356 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001357 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001358
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001359 // Canonicalize to use ordered comparisons by swapping the select
1360 // operands.
1361 //
1362 // e.g.
1363 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1364 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1365 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001366 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1367 Builder.setFastMathFlags(FCI->getFastMathFlags());
1368 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1369 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001370
1371 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1372 SI.getName() + ".p");
1373 }
1374
1375 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001376 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1377 // Transform (X == Y) ? Y : X -> X
1378 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001379 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001380 // consider X== -0, Y== +0.
1381 // It becomes safe if either operand is a nonzero constant.
1382 ConstantFP *CFPt, *CFPf;
1383 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1384 !CFPt->getValueAPF().isZero()) ||
1385 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1386 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001387 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001388 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001389 // Transform (X une Y) ? Y : X -> Y
1390 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001391 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001392 // consider X== -0, Y== +0.
1393 // It becomes safe if either operand is a nonzero constant.
1394 ConstantFP *CFPt, *CFPf;
1395 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1396 !CFPt->getValueAPF().isZero()) ||
1397 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1398 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001399 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001400 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001401
1402 // Canonicalize to use ordered comparisons by swapping the select
1403 // operands.
1404 //
1405 // e.g.
1406 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1407 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1408 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001409 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1410 Builder.setFastMathFlags(FCI->getFastMathFlags());
1411 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1412 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001413
1414 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1415 SI.getName() + ".p");
1416 }
1417
Chris Lattner8f771cb2010-01-05 06:03:12 +00001418 // NOTE: if we wanted to, this is where to detect MIN/MAX
1419 }
1420 // NOTE: if we wanted to, this is where to detect ABS
1421 }
1422
1423 // See if we are selecting two values based on a comparison of the two values.
1424 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001425 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001426 return Result;
1427
Craig Topperbb4069e2017-07-07 23:16:26 +00001428 if (Instruction *Add = foldAddSubSelect(SI, Builder))
Sanjay Patel39293132016-06-08 21:10:01 +00001429 return Add;
1430
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001431 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001432 auto *TI = dyn_cast<Instruction>(TrueVal);
1433 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001434 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001435 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001436 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001437
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001438 if (Instruction *I = foldSelectExtConst(SI))
1439 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001440
Chris Lattner8f771cb2010-01-05 06:03:12 +00001441 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001442 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001443 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001444 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001445
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001446 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001447 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001448 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1449 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001450
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001451 if (SelectPatternResult::isMinOrMax(SPF)) {
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001452 // Canonicalize so that
1453 // - type casts are outside select patterns.
1454 // - float clamp is transformed to min/max pattern
1455
1456 bool IsCastNeeded = LHS->getType() != SelType;
1457 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1458 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1459 if (IsCastNeeded ||
1460 (LHS->getType()->isFPOrFPVectorTy() &&
1461 ((CmpLHS != LHS && CmpLHS != RHS) ||
1462 (CmpRHS != LHS && CmpRHS != RHS)))) {
James Molloy134bec22015-08-11 09:12:57 +00001463 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1464
1465 Value *Cmp;
1466 if (CmpInst::isIntPredicate(Pred)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001467 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001468 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00001469 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
James Molloy134bec22015-08-11 09:12:57 +00001470 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Craig Topperbb4069e2017-07-07 23:16:26 +00001471 Builder.setFastMathFlags(FMF);
1472 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001473 }
1474
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001475 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1476 if (!IsCastNeeded)
1477 return replaceInstUsesWith(SI, NewSI);
1478
1479 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1480 return replaceInstUsesWith(SI, NewCast);
James Molloy2b21a7c2015-05-20 18:41:25 +00001481 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001482 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001483
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001484 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001485 // MAX(MAX(a, b), a) -> MAX(a, b)
1486 // MIN(MIN(a, b), a) -> MIN(a, b)
1487 // MAX(MIN(a, b), a) -> a
1488 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001489 // ABS(ABS(a)) -> ABS(a)
1490 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001491 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001492 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001493 SI, SPF, RHS))
1494 return R;
James Molloy134bec22015-08-11 09:12:57 +00001495 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001496 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001497 SI, SPF, LHS))
1498 return R;
1499 }
1500
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001501 // MAX(~a, ~b) -> ~MIN(a, b)
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001502 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1503 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1504 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001505 // For this transform to be profitable, we need to eliminate at least two
1506 // 'not' instructions if we're going to add one 'not' instruction.
1507 int NumberOfNots =
1508 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1509 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001510 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001511
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001512 if (NumberOfNots >= 2) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001513 Value *NewLHS = Builder.CreateNot(LHS);
1514 Value *NewRHS = Builder.CreateNot(RHS);
1515 Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1516 : Builder.CreateICmpULT(NewLHS, NewRHS);
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001517 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +00001518 Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001519 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001520 }
1521 }
1522
Chris Lattner8f771cb2010-01-05 06:03:12 +00001523 // TODO.
1524 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001525 }
1526
1527 // See if we can fold the select into a phi node if the condition is a select.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001528 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001529 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001530 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1531 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Craig Topperfb71b7d2017-04-14 19:20:12 +00001532 if (Instruction *NV = foldOpIntoPhi(SI, PN))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001533 return NV;
1534
Nick Lewyckyb074e322011-01-28 03:28:10 +00001535 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001536 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1537 // select(C, select(C, a, b), c) -> select(C, a, c)
1538 if (TrueSI->getCondition() == CondVal) {
1539 if (SI.getTrueValue() == TrueSI->getTrueValue())
1540 return nullptr;
1541 SI.setOperand(1, TrueSI->getTrueValue());
1542 return &SI;
1543 }
1544 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1545 // We choose this as normal form to enable folding on the And and shortening
1546 // paths for the values (this helps GetUnderlyingObjects() for example).
1547 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001548 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001549 SI.setOperand(0, And);
1550 SI.setOperand(1, TrueSI->getTrueValue());
1551 return &SI;
1552 }
Matthias Braun2e404592015-02-06 17:49:36 +00001553 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001554 }
1555 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001556 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1557 // select(C, a, select(C, b, c)) -> select(C, a, c)
1558 if (FalseSI->getCondition() == CondVal) {
1559 if (SI.getFalseValue() == FalseSI->getFalseValue())
1560 return nullptr;
1561 SI.setOperand(2, FalseSI->getFalseValue());
1562 return &SI;
1563 }
1564 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1565 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001566 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001567 SI.setOperand(0, Or);
1568 SI.setOperand(2, FalseSI->getFalseValue());
1569 return &SI;
1570 }
Matthias Braun2e404592015-02-06 17:49:36 +00001571 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001572 }
1573
Chris Lattner8f771cb2010-01-05 06:03:12 +00001574 if (BinaryOperator::isNot(CondVal)) {
1575 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1576 SI.setOperand(1, FalseVal);
1577 SI.setOperand(2, TrueVal);
1578 return &SI;
1579 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001580
Sanjay Patel4e463b42016-09-06 18:16:31 +00001581 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001582 unsigned VWidth = VecTy->getNumElements();
1583 APInt UndefElts(VWidth, 0);
1584 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1585 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1586 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001587 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001588 return &SI;
1589 }
1590 }
1591
Chad Rosiercd62bf52016-04-29 21:12:31 +00001592 // See if we can determine the result of this select based on a dominating
1593 // condition.
1594 BasicBlock *Parent = SI.getParent();
1595 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1596 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1597 if (PBI && PBI->isConditional() &&
1598 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1599 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
Chad Rosierdfd1de62017-08-01 20:18:54 +00001600 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
Chad Rosiercd62bf52016-04-29 21:12:31 +00001601 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00001602 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
Chad Rosiercd62bf52016-04-29 21:12:31 +00001603 if (Implication) {
1604 Value *V = *Implication ? TrueVal : FalseVal;
1605 return replaceInstUsesWith(SI, V);
1606 }
1607 }
1608 }
1609
Sanjay Patel51783632017-01-13 17:02:42 +00001610 // If we can compute the condition, there's no need for a select.
1611 // Like the above fold, we are attempting to reduce compile-time cost by
1612 // putting this fold here with limitations rather than in InstSimplify.
1613 // The motivation for this call into value tracking is to take advantage of
1614 // the assumption cache, so make sure that is populated.
1615 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001616 KnownBits Known(1);
1617 computeKnownBits(CondVal, Known, 0, &SI);
Craig Topper73ba1c82017-06-07 07:40:37 +00001618 if (Known.One.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001619 return replaceInstUsesWith(SI, TrueVal);
Craig Topper73ba1c82017-06-07 07:40:37 +00001620 if (Known.Zero.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001621 return replaceInstUsesWith(SI, FalseVal);
1622 }
1623
Craig Topperbb4069e2017-07-07 23:16:26 +00001624 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
Sanjay Patel978f8272016-10-29 15:22:04 +00001625 return BitCastSel;
1626
Craig Topperf40110f2014-04-25 05:29:35 +00001627 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001628}