blob: 018cdcc24d5c825bcdf956cf1b3848d633c1948b [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"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000016#include "llvm/Analysis/InstructionSimplify.h"
James Molloy71b91c22015-05-11 14:42:20 +000017#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Sanjoy Das08e95b42015-04-30 04:56:04 +000024static SelectPatternFlavor
25getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
26 switch (SPF) {
27 default:
28 llvm_unreachable("unhandled!");
29
30 case SPF_SMIN:
31 return SPF_SMAX;
32 case SPF_UMIN:
33 return SPF_UMAX;
34 case SPF_SMAX:
35 return SPF_SMIN;
36 case SPF_UMAX:
37 return SPF_UMIN;
38 }
39}
40
James Molloy134bec22015-08-11 09:12:57 +000041static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
42 bool Ordered=false) {
Sanjoy Das08e95b42015-04-30 04:56:04 +000043 switch (SPF) {
44 default:
45 llvm_unreachable("unhandled!");
46
47 case SPF_SMIN:
48 return ICmpInst::ICMP_SLT;
49 case SPF_UMIN:
50 return ICmpInst::ICMP_ULT;
51 case SPF_SMAX:
52 return ICmpInst::ICMP_SGT;
53 case SPF_UMAX:
54 return ICmpInst::ICMP_UGT;
James Molloy134bec22015-08-11 09:12:57 +000055 case SPF_FMINNUM:
56 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
57 case SPF_FMAXNUM:
58 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
Sanjoy Das08e95b42015-04-30 04:56:04 +000059 }
60}
61
62static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
63 SelectPatternFlavor SPF, Value *A,
64 Value *B) {
James Molloy134bec22015-08-11 09:12:57 +000065 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
66 assert(CmpInst::isIntPredicate(Pred));
Sanjoy Das08e95b42015-04-30 04:56:04 +000067 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
68}
69
Sanjay Patel6eccf482015-09-09 15:24:36 +000070/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +000071/// %C = or %A, %B
72/// %D = select %cond, %C, %A
73/// into:
74/// %C = select %cond, %B, 0
75/// %D = or %A, %C
76///
77/// Assuming that the specified instruction is an operand to the select, return
78/// a bitmask indicating which operands of this instruction are foldable if they
79/// equal the other incoming value of the select.
80///
81static unsigned GetSelectFoldableOperands(Instruction *I) {
82 switch (I->getOpcode()) {
83 case Instruction::Add:
84 case Instruction::Mul:
85 case Instruction::And:
86 case Instruction::Or:
87 case Instruction::Xor:
88 return 3; // Can fold through either operand.
89 case Instruction::Sub: // Can only fold on the amount subtracted.
90 case Instruction::Shl: // Can only fold on the shift amount.
91 case Instruction::LShr:
92 case Instruction::AShr:
93 return 1;
94 default:
95 return 0; // Cannot fold
96 }
97}
98
Sanjay Patel6eccf482015-09-09 15:24:36 +000099/// For the same transformation as the previous function, return the identity
100/// constant that goes into the select.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000101static Constant *GetSelectFoldableConstant(Instruction *I) {
102 switch (I->getOpcode()) {
103 default: llvm_unreachable("This cannot happen!");
104 case Instruction::Add:
105 case Instruction::Sub:
106 case Instruction::Or:
107 case Instruction::Xor:
108 case Instruction::Shl:
109 case Instruction::LShr:
110 case Instruction::AShr:
111 return Constant::getNullValue(I->getType());
112 case Instruction::And:
113 return Constant::getAllOnesValue(I->getType());
114 case Instruction::Mul:
115 return ConstantInt::get(I->getType(), 1);
116 }
117}
118
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000119/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000120Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
121 Instruction *FI) {
Sanjay Patel384d0f22016-06-08 20:31:52 +0000122 // If this is a cast from the same type, merge.
123 if (TI->getNumOperands() == 1 && TI->isCast()) {
124 Type *FIOpndTy = FI->getOperand(0)->getType();
125 if (TI->getOperand(0)->getType() != FIOpndTy)
126 return nullptr;
127
128 // The select condition may be a vector. We may only change the operand
129 // type if the vector width remains the same (and matches the condition).
130 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000131 if (CondTy->isVectorTy()) {
132 if (!FIOpndTy->isVectorTy())
133 return nullptr;
134 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
135 return nullptr;
136
137 // TODO: If the backend knew how to deal with casts better, we could
138 // remove this limitation. For now, there's too much potential to create
139 // worse codegen by promoting the select ahead of size-altering casts
140 // (PR28160).
141 //
142 // Note that ValueTracking's matchSelectPattern() looks through casts
143 // without checking 'hasOneUse' when it matches min/max patterns, so this
144 // transform may end up happening anyway.
145 if (TI->getOpcode() != Instruction::BitCast &&
146 (!TI->hasOneUse() || !FI->hasOneUse()))
147 return nullptr;
148
149 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
150 // TODO: The one-use restrictions for a scalar select could be eased if
151 // the fold of a select in visitLoadInst() was enhanced to match a pattern
152 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000153 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000154 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000155
156 // Fold this by inserting a select from the input values.
Eli Friedman2fd66442011-05-18 18:10:28 +0000157 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
158 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000159 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000160 TI->getType());
161 }
162
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000163 // TODO: This function ends awkwardly in unreachable - fix to be more normal.
164
165 // Only handle binary operators with one-use here. As with the cast case
166 // above, it may be possible to relax the one-use constraint, but that needs
167 // be examined carefully since it may not reduce the total number of
168 // instructions.
169 if (!isa<BinaryOperator>(TI) || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000170 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000171
172 // Figure out if the operations have any operands in common.
173 Value *MatchOp, *OtherOpT, *OtherOpF;
174 bool MatchIsOpZero;
175 if (TI->getOperand(0) == FI->getOperand(0)) {
176 MatchOp = TI->getOperand(0);
177 OtherOpT = TI->getOperand(1);
178 OtherOpF = FI->getOperand(1);
179 MatchIsOpZero = true;
180 } else if (TI->getOperand(1) == FI->getOperand(1)) {
181 MatchOp = TI->getOperand(1);
182 OtherOpT = TI->getOperand(0);
183 OtherOpF = FI->getOperand(0);
184 MatchIsOpZero = false;
185 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000186 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000187 } else if (TI->getOperand(0) == FI->getOperand(1)) {
188 MatchOp = TI->getOperand(0);
189 OtherOpT = TI->getOperand(1);
190 OtherOpF = FI->getOperand(0);
191 MatchIsOpZero = true;
192 } else if (TI->getOperand(1) == FI->getOperand(0)) {
193 MatchOp = TI->getOperand(1);
194 OtherOpT = TI->getOperand(0);
195 OtherOpF = FI->getOperand(1);
196 MatchIsOpZero = true;
197 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000199 }
200
201 // If we reach here, they do have operations in common.
Eli Friedman2fd66442011-05-18 18:10:28 +0000202 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
203 OtherOpF, SI.getName()+".v");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000204
205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
206 if (MatchIsOpZero)
207 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
208 else
209 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
210 }
211 llvm_unreachable("Shouldn't get here");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000212}
213
214static bool isSelect01(Constant *C1, Constant *C2) {
215 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
216 if (!C1I)
217 return false;
218 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
219 if (!C2I)
220 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000221 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
222 return false;
223 return C1I->isOne() || C1I->isAllOnesValue() ||
224 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000225}
226
Sanjay Patel6eccf482015-09-09 15:24:36 +0000227/// Try to fold the select into one of the operands to allow further
228/// optimization.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000229Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
230 Value *FalseVal) {
231 // See the comment above GetSelectFoldableOperands for a description of the
232 // transformation we are doing here.
233 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
234 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
235 !isa<Constant>(FalseVal)) {
236 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
237 unsigned OpToFold = 0;
238 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
239 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000240 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000241 OpToFold = 2;
242 }
243
244 if (OpToFold) {
245 Constant *C = GetSelectFoldableConstant(TVI);
246 Value *OOp = TVI->getOperand(2-OpToFold);
247 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000248 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000249 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000250 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000251 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000252 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000253 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
254 FalseVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000255 BO->copyIRFlags(TVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000256 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000257 }
258 }
259 }
260 }
261 }
262
263 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
264 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
265 !isa<Constant>(TrueVal)) {
266 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
267 unsigned OpToFold = 0;
268 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
269 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000270 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000271 OpToFold = 2;
272 }
273
274 if (OpToFold) {
275 Constant *C = GetSelectFoldableConstant(FVI);
276 Value *OOp = FVI->getOperand(2-OpToFold);
277 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000278 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000279 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000280 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000281 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000282 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
283 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
284 TrueVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000285 BO->copyIRFlags(FVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000286 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000287 }
288 }
289 }
290 }
291 }
292
Craig Topperf40110f2014-04-25 05:29:35 +0000293 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000294}
295
Sanjay Patel6eccf482015-09-09 15:24:36 +0000296/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000297/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
298/// into:
299/// (or (shl (and X, C1), C3), y)
300/// iff:
301/// C1 and C2 are both powers of 2
302/// where:
303/// C3 = Log(C2) - Log(C1)
304///
305/// This transform handles cases where:
306/// 1. The icmp predicate is inverted
307/// 2. The select operands are reversed
308/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000309static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000310 Value *FalseVal,
311 InstCombiner::BuilderTy *Builder) {
312 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000313 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000314 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000315
316 Value *CmpLHS = IC->getOperand(0);
317 Value *CmpRHS = IC->getOperand(1);
318
319 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000320 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000321
322 Value *X;
323 const APInt *C1;
324 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000325 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000326
327 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000328 bool OrOnTrueVal = false;
329 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
330 if (!OrOnFalseVal)
331 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000332
333 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000334 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000335
336 Value *V = CmpLHS;
337 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
338
339 unsigned C1Log = C1->logBase2();
340 unsigned C2Log = C2->logBase2();
341 if (C2Log > C1Log) {
342 V = Builder->CreateZExtOrTrunc(V, Y->getType());
343 V = Builder->CreateShl(V, C2Log - C1Log);
344 } else if (C1Log > C2Log) {
345 V = Builder->CreateLShr(V, C1Log - C2Log);
346 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000347 } else
348 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000349
350 ICmpInst::Predicate Pred = IC->getPredicate();
351 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
352 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
353 V = Builder->CreateXor(V, *C2);
354
355 return Builder->CreateOr(V, Y);
356}
357
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000358/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
359/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
360///
361/// For example, we can fold the following code sequence:
362/// \code
363/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
364/// %1 = icmp ne i32 %x, 0
365/// %2 = select i1 %1, i32 %0, i32 32
366/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000367///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000368/// into:
369/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
370static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
371 InstCombiner::BuilderTy *Builder) {
372 ICmpInst::Predicate Pred = ICI->getPredicate();
373 Value *CmpLHS = ICI->getOperand(0);
374 Value *CmpRHS = ICI->getOperand(1);
375
376 // Check if the condition value compares a value for equality against zero.
377 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
378 return nullptr;
379
380 Value *Count = FalseVal;
381 Value *ValueOnZero = TrueVal;
382 if (Pred == ICmpInst::ICMP_NE)
383 std::swap(Count, ValueOnZero);
384
385 // Skip zero extend/truncate.
386 Value *V = nullptr;
387 if (match(Count, m_ZExt(m_Value(V))) ||
388 match(Count, m_Trunc(m_Value(V))))
389 Count = V;
390
391 // Check if the value propagated on zero is a constant number equal to the
392 // sizeof in bits of 'Count'.
393 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
394 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
395 return nullptr;
396
397 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
398 // input to the cttz/ctlz is used as LHS for the compare instruction.
399 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
400 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
401 IntrinsicInst *II = cast<IntrinsicInst>(Count);
402 IRBuilder<> Builder(II);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000403 // Explicitly clear the 'undef_on_zero' flag.
404 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
405 Type *Ty = NewI->getArgOperand(1)->getType();
406 NewI->setArgOperand(1, Constant::getNullValue(Ty));
407 Builder.Insert(NewI);
408 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000409 }
410
411 return nullptr;
412}
413
Sanjay Patel6eccf482015-09-09 15:24:36 +0000414/// Visit a SelectInst that has an ICmpInst as its first operand.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000415Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
416 ICmpInst *ICI) {
417 bool Changed = false;
418 ICmpInst::Predicate Pred = ICI->getPredicate();
419 Value *CmpLHS = ICI->getOperand(0);
420 Value *CmpRHS = ICI->getOperand(1);
421 Value *TrueVal = SI.getTrueValue();
422 Value *FalseVal = SI.getFalseValue();
423
424 // Check cases where the comparison is with a constant that
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000425 // can be adjusted to fit the min/max idiom. We may move or edit ICI
426 // here, so make sure the select is the only user.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000427 if (ICI->hasOneUse())
428 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
429 switch (Pred) {
430 default: break;
431 case ICmpInst::ICMP_ULT:
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000432 case ICmpInst::ICMP_SLT:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000433 case ICmpInst::ICMP_UGT:
434 case ICmpInst::ICMP_SGT: {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000435 // These transformations only work for selects over integers.
Chris Lattner229907c2011-07-18 04:54:35 +0000436 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000437 if (!SelectTy)
438 break;
439
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000440 Constant *AdjustedRHS;
441 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
442 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
443 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
444 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
445
Chris Lattner8f771cb2010-01-05 06:03:12 +0000446 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000447 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattner8f771cb2010-01-05 06:03:12 +0000448 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000449 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
450 ; // Nothing to do here. Values match without any sign/zero extension.
451
452 // Types do not match. Instead of calculating this with mixed types
453 // promote all to the larger type. This enables scalar evolution to
454 // analyze this expression.
455 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000456 < SelectTy->getBitWidth()) {
457 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000458
459 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
460 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
461 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
462 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
463 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
464 sextRHS == FalseVal) {
465 CmpLHS = TrueVal;
466 AdjustedRHS = sextRHS;
467 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
468 sextRHS == TrueVal) {
469 CmpLHS = FalseVal;
470 AdjustedRHS = sextRHS;
471 } else if (ICI->isUnsigned()) {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000472 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000473 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
474 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
475 // zext + signed compare cannot be changed:
476 // 0xff <s 0x00, but 0x00ff >s 0x0000
477 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
478 zextRHS == FalseVal) {
479 CmpLHS = TrueVal;
480 AdjustedRHS = zextRHS;
481 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
482 zextRHS == TrueVal) {
483 CmpLHS = FalseVal;
484 AdjustedRHS = zextRHS;
485 } else
486 break;
487 } else
488 break;
489 } else
490 break;
491
492 Pred = ICmpInst::getSwappedPredicate(Pred);
493 CmpRHS = AdjustedRHS;
494 std::swap(FalseVal, TrueVal);
495 ICI->setPredicate(Pred);
496 ICI->setOperand(0, CmpLHS);
497 ICI->setOperand(1, CmpRHS);
498 SI.setOperand(1, TrueVal);
499 SI.setOperand(2, FalseVal);
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000500
501 // Move ICI instruction right before the select instruction. Otherwise
502 // the sext/zext value may be defined after the ICI instruction uses it.
503 ICI->moveBefore(&SI);
504
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000505 Changed = true;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000506 break;
507 }
508 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000509 }
510
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000511 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
512 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
513 // FIXME: Type and constness constraints could be lifted, but we have to
514 // watch code size carefully. We should consider xor instead of
515 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000516 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000517 if (TrueVal->getType() == Ty) {
518 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000519 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000520 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
521 C1 = dyn_cast<ConstantInt>(TrueVal);
522 C2 = dyn_cast<ConstantInt>(FalseVal);
523 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
524 C1 = dyn_cast<ConstantInt>(FalseVal);
525 C2 = dyn_cast<ConstantInt>(TrueVal);
526 }
527 if (C1 && C2) {
528 // This shift results in either -1 or 0.
529 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
530
531 // Check if we can express the operation with a single or.
532 if (C2->isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000533 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000534
535 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000536 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000537 }
538 }
539 }
540 }
541
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000542 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
543
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000544 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000545 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
546 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
547 SI.setOperand(1, CmpRHS);
548 Changed = true;
549 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
550 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
551 SI.setOperand(2, CmpRHS);
552 Changed = true;
553 }
554 }
555
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000556 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
557 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000558 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000559 unsigned BitWidth =
560 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
David Majnemerb0362e42014-12-20 04:45:35 +0000561 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000562 Value *X;
563 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000564 bool TrueWhenUnset;
565 bool IsBitTest = false;
566 if (ICmpInst::isEquality(Pred) &&
567 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000568 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000569 IsBitTest = true;
570 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
571 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
572 X = CmpLHS;
573 Y = &MinSignedValue;
574 IsBitTest = true;
575 TrueWhenUnset = false;
576 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
577 X = CmpLHS;
578 Y = &MinSignedValue;
579 IsBitTest = true;
580 TrueWhenUnset = true;
581 }
582 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000583 Value *V = nullptr;
584 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000585 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000586 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
587 V = Builder->CreateAnd(X, ~(*Y));
588 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000589 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000590 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
591 V = Builder->CreateAnd(X, ~(*Y));
592 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000593 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000594 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
595 V = Builder->CreateOr(X, *Y);
596 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000597 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000598 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
599 V = Builder->CreateOr(X, *Y);
600
601 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000602 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000603 }
604 }
605
David Majnemer8d048d02013-04-30 08:57:58 +0000606 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000607 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000608
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000609 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000610 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000611
Craig Topperf40110f2014-04-25 05:29:35 +0000612 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000613}
614
615
Sanjay Patel6eccf482015-09-09 15:24:36 +0000616/// SI is a select whose condition is a PHI node (but the two may be in
617/// different blocks). See if the true/false values (V) are live in all of the
618/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000619///
620/// X = phi [ C1, BB1], [C2, BB2]
621/// Y = add
622/// Z = select X, Y, 0
623///
624/// because Y is not live in BB1/BB2.
625///
626static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
627 const SelectInst &SI) {
628 // If the value is a non-instruction value like a constant or argument, it
629 // can always be mapped.
630 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000631 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000632
Chris Lattner8f771cb2010-01-05 06:03:12 +0000633 // If V is a PHI node defined in the same block as the condition PHI, we can
634 // map the arguments.
635 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000636
Chris Lattner8f771cb2010-01-05 06:03:12 +0000637 if (const PHINode *VP = dyn_cast<PHINode>(I))
638 if (VP->getParent() == CondPHI->getParent())
639 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000640
Chris Lattner8f771cb2010-01-05 06:03:12 +0000641 // Otherwise, if the PHI and select are defined in the same block and if V is
642 // defined in a different block, then we can transform it.
643 if (SI.getParent() == CondPHI->getParent() &&
644 I->getParent() != CondPHI->getParent())
645 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000646
Chris Lattner8f771cb2010-01-05 06:03:12 +0000647 // Otherwise we have a 'hard' case and we can't tell without doing more
648 // detailed dominator based analysis, punt.
649 return false;
650}
651
Sanjay Patel6eccf482015-09-09 15:24:36 +0000652/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000653/// SPF2(SPF1(A, B), C)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000654Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
655 SelectPatternFlavor SPF1,
656 Value *A, Value *B,
657 Instruction &Outer,
658 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000659 if (Outer.getType() != Inner->getType())
660 return nullptr;
661
Chris Lattner8f771cb2010-01-05 06:03:12 +0000662 if (C == A || C == B) {
663 // MAX(MAX(A, B), B) -> MAX(A, B)
664 // MIN(MIN(a, b), a) -> MIN(a, b)
665 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000666 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000667
Chris Lattner8f771cb2010-01-05 06:03:12 +0000668 // MAX(MIN(a, b), a) -> a
669 // MIN(MAX(a, b), a) -> a
670 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
671 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
672 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
673 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000674 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000675 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000676
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000677 if (SPF1 == SPF2) {
678 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
679 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000680 const APInt &ACB = CB->getValue();
681 const APInt &ACC = CC->getValue();
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000682
683 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
684 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000685 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
686 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
687 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
688 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000689 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000690
691 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
692 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
693 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
694 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
695 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
696 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
697 Outer.replaceUsesOfWith(Inner, A);
698 return &Outer;
699 }
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000700 }
701 }
702 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000703
704 // ABS(ABS(X)) -> ABS(X)
705 // NABS(NABS(X)) -> NABS(X)
706 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000707 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000708 }
709
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000710 // ABS(NABS(X)) -> ABS(X)
711 // NABS(ABS(X)) -> NABS(X)
712 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
713 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
714 SelectInst *SI = cast<SelectInst>(Inner);
715 Value *NewSI = Builder->CreateSelect(
716 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000717 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000718 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000719
720 auto IsFreeOrProfitableToInvert =
721 [&](Value *V, Value *&NotV, bool &ElidesXor) {
722 if (match(V, m_Not(m_Value(NotV)))) {
723 // If V has at most 2 uses then we can get rid of the xor operation
724 // entirely.
725 ElidesXor |= !V->hasNUsesOrMore(3);
726 return true;
727 }
728
729 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
730 NotV = nullptr;
731 return true;
732 }
733
734 return false;
735 };
736
737 Value *NotA, *NotB, *NotC;
738 bool ElidesXor = false;
739
740 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
741 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
742 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
743 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
744 //
745 // This transform is performance neutral if we can elide at least one xor from
746 // the set of three operands, since we'll be tacking on an xor at the very
747 // end.
748 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
749 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
750 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
751 if (!NotA)
752 NotA = Builder->CreateNot(A);
753 if (!NotB)
754 NotB = Builder->CreateNot(B);
755 if (!NotC)
756 NotC = Builder->CreateNot(C);
757
758 Value *NewInner = generateMinMaxSelectPattern(
759 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
760 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
761 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000762 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000763 }
764
Craig Topperf40110f2014-04-25 05:29:35 +0000765 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000766}
767
Sanjay Patel6eccf482015-09-09 15:24:36 +0000768/// If one of the constants is zero (we know they can't both be) and we have an
769/// icmp instruction with zero, and we have an 'and' with the non-constant value
770/// and a power of two we can turn the select into a shift on the result of the
771/// 'and'.
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000772static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
773 ConstantInt *FalseVal,
774 InstCombiner::BuilderTy *Builder) {
775 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000776 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000777 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000778
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000779 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000780 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000781
782 ConstantInt *AndRHS;
783 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000784 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000786
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000787 // If both select arms are non-zero see if we have a select of the form
788 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
789 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000790 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000791 if (!TrueVal->isZero() && !FalseVal->isZero()) {
792 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
793 Offset = FalseVal;
794 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
795 Offset = TrueVal;
796 else
Craig Topperf40110f2014-04-25 05:29:35 +0000797 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000798
799 // Adjust TrueVal and FalseVal to the offset.
800 TrueVal = ConstantInt::get(Builder->getContext(),
801 TrueVal->getValue() - Offset->getValue());
802 FalseVal = ConstantInt::get(Builder->getContext(),
803 FalseVal->getValue() - Offset->getValue());
804 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000805
806 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
807 if (!AndRHS->getValue().isPowerOf2() ||
808 (!TrueVal->getValue().isPowerOf2() &&
809 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000810 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000811
812 // Determine which shift is needed to transform result of the 'and' into the
813 // desired result.
814 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
815 unsigned ValZeros = ValC->getValue().logBase2();
816 unsigned AndZeros = AndRHS->getValue().logBase2();
817
Benjamin Kramer4093f292013-06-29 21:17:04 +0000818 // If types don't match we can still convert the select by introducing a zext
819 // or a trunc of the 'and'. The trunc case requires that all of the truncated
820 // bits are zero, we can figure that out by looking at the 'and' mask.
821 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000822 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000823
824 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000825 if (ValZeros > AndZeros)
826 V = Builder->CreateShl(V, ValZeros - AndZeros);
827 else if (ValZeros < AndZeros)
828 V = Builder->CreateLShr(V, AndZeros - ValZeros);
829
830 // Okay, now we know that everything is set up, we just don't know whether we
831 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
832 bool ShouldNotVal = !TrueVal->isZero();
833 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
834 if (ShouldNotVal)
835 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000836
837 // Apply an offset if needed.
838 if (Offset)
839 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000840 return V;
841}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000842
Sanjay Patel39293132016-06-08 21:10:01 +0000843/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
844/// This is even legal for FP.
845static Instruction *foldAddSubSelect(SelectInst &SI,
846 InstCombiner::BuilderTy &Builder) {
847 Value *CondVal = SI.getCondition();
848 Value *TrueVal = SI.getTrueValue();
849 Value *FalseVal = SI.getFalseValue();
850 auto *TI = dyn_cast<Instruction>(TrueVal);
851 auto *FI = dyn_cast<Instruction>(FalseVal);
852 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
853 return nullptr;
854
855 Instruction *AddOp = nullptr, *SubOp = nullptr;
856 if ((TI->getOpcode() == Instruction::Sub &&
857 FI->getOpcode() == Instruction::Add) ||
858 (TI->getOpcode() == Instruction::FSub &&
859 FI->getOpcode() == Instruction::FAdd)) {
860 AddOp = FI;
861 SubOp = TI;
862 } else if ((FI->getOpcode() == Instruction::Sub &&
863 TI->getOpcode() == Instruction::Add) ||
864 (FI->getOpcode() == Instruction::FSub &&
865 TI->getOpcode() == Instruction::FAdd)) {
866 AddOp = TI;
867 SubOp = FI;
868 }
869
870 if (AddOp) {
871 Value *OtherAddOp = nullptr;
872 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
873 OtherAddOp = AddOp->getOperand(1);
874 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
875 OtherAddOp = AddOp->getOperand(0);
876 }
877
878 if (OtherAddOp) {
879 // So at this point we know we have (Y -> OtherAddOp):
880 // select C, (add X, Y), (sub X, Z)
881 Value *NegVal; // Compute -Z
882 if (SI.getType()->isFPOrFPVectorTy()) {
883 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
884 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
885 FastMathFlags Flags = AddOp->getFastMathFlags();
886 Flags &= SubOp->getFastMathFlags();
887 NegInst->setFastMathFlags(Flags);
888 }
889 } else {
890 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
891 }
892
893 Value *NewTrueOp = OtherAddOp;
894 Value *NewFalseOp = NegVal;
895 if (AddOp != TI)
896 std::swap(NewTrueOp, NewFalseOp);
897 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
898 SI.getName() + ".p");
899
900 if (SI.getType()->isFPOrFPVectorTy()) {
901 Instruction *RI =
902 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
903
904 FastMathFlags Flags = AddOp->getFastMathFlags();
905 Flags &= SubOp->getFastMathFlags();
906 RI->setFastMathFlags(Flags);
907 return RI;
908 } else
909 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
910 }
911 }
912 return nullptr;
913}
914
Chris Lattner8f771cb2010-01-05 06:03:12 +0000915Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
916 Value *CondVal = SI.getCondition();
917 Value *TrueVal = SI.getTrueValue();
918 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +0000919 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000920
Chandler Carruth66b31302015-01-04 12:03:27 +0000921 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +0000922 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000923 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000924
Sanjay Patel25600f32016-07-07 15:28:17 +0000925 if (SelType->getScalarType()->isIntegerTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +0000926 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +0000927 if (match(TrueVal, m_One())) {
928 // Change: A = select B, true, C --> A = or B, C
929 return BinaryOperator::CreateOr(CondVal, FalseVal);
930 }
931 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +0000932 // Change: A = select B, false, C --> A = and !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +0000933 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000934 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000935 }
Sanjay Patelea234362016-07-06 21:01:26 +0000936 if (match(FalseVal, m_Zero())) {
937 // Change: A = select B, C, false --> A = and B, C
938 return BinaryOperator::CreateAnd(CondVal, TrueVal);
939 }
940 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +0000941 // Change: A = select B, C, true --> A = or !B, C
Sanjay Patela1a4e102016-07-03 14:08:19 +0000942 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000943 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000944 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000945
Sanjay Patela1a4e102016-07-03 14:08:19 +0000946 // select a, a, b -> a | b
947 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +0000948 if (CondVal == TrueVal)
949 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000950 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000951 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +0000952
Sanjay Patela1a4e102016-07-03 14:08:19 +0000953 // select a, ~a, b -> (~a) & b
954 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +0000955 if (match(TrueVal, m_Not(m_Specific(CondVal))))
956 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000957 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +0000958 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000959 }
960
Sanjay Patel65a51c22016-07-06 22:23:01 +0000961 // Selecting between two integer or vector splat integer constants?
962 //
963 // Note that we don't handle a scalar select of vectors:
964 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
965 // because that may need 3 instructions to splat the condition value:
966 // extend, insertelement, shufflevector.
Sanjay Patel25600f32016-07-07 15:28:17 +0000967 if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +0000968 // select C, 1, 0 -> zext C to int
969 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +0000970 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +0000971
972 // select C, -1, 0 -> sext C to int
973 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +0000974 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +0000975
976 // select C, 0, 1 -> zext !C to int
977 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
978 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +0000979 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +0000980 }
981
982 // select C, 0, -1 -> sext !C to int
983 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
984 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +0000985 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +0000986 }
987 }
988
Chris Lattner8f771cb2010-01-05 06:03:12 +0000989 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
Sanjay Patel65a51c22016-07-06 22:23:01 +0000990 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000991 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000992 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000993
994 // See if we are selecting two values based on a comparison of the two values.
995 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
996 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
997 // Transform (X == Y) ? X : Y -> Y
998 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000999 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001000 // consider X== -0, Y== +0.
1001 // It becomes safe if either operand is a nonzero constant.
1002 ConstantFP *CFPt, *CFPf;
1003 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1004 !CFPt->getValueAPF().isZero()) ||
1005 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1006 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001007 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001008 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001009 // Transform (X une Y) ? X : Y -> X
1010 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001011 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001012 // consider X== -0, Y== +0.
1013 // It becomes safe if either operand is a nonzero constant.
1014 ConstantFP *CFPt, *CFPf;
1015 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1016 !CFPt->getValueAPF().isZero()) ||
1017 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1018 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001019 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001020 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001021
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001022 // Canonicalize to use ordered comparisons by swapping the select
1023 // operands.
1024 //
1025 // e.g.
1026 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1027 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1028 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001029 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001030 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001031 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1032 FCI->getName() + ".inv");
1033
1034 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1035 SI.getName() + ".p");
1036 }
1037
1038 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001039 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1040 // Transform (X == Y) ? Y : X -> X
1041 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001042 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001043 // consider X== -0, Y== +0.
1044 // It becomes safe if either operand is a nonzero constant.
1045 ConstantFP *CFPt, *CFPf;
1046 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1047 !CFPt->getValueAPF().isZero()) ||
1048 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1049 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001050 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001051 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001052 // Transform (X une Y) ? Y : X -> Y
1053 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001054 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001055 // consider X== -0, Y== +0.
1056 // It becomes safe if either operand is a nonzero constant.
1057 ConstantFP *CFPt, *CFPf;
1058 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1059 !CFPt->getValueAPF().isZero()) ||
1060 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1061 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001062 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001063 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001064
1065 // Canonicalize to use ordered comparisons by swapping the select
1066 // operands.
1067 //
1068 // e.g.
1069 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1070 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1071 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +00001072 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +00001073 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001074 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1075 FCI->getName() + ".inv");
1076
1077 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1078 SI.getName() + ".p");
1079 }
1080
Chris Lattner8f771cb2010-01-05 06:03:12 +00001081 // NOTE: if we wanted to, this is where to detect MIN/MAX
1082 }
1083 // NOTE: if we wanted to, this is where to detect ABS
1084 }
1085
1086 // See if we are selecting two values based on a comparison of the two values.
1087 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1088 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1089 return Result;
1090
Sanjay Patel39293132016-06-08 21:10:01 +00001091 if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1092 return Add;
1093
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001094 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001095 auto *TI = dyn_cast<Instruction>(TrueVal);
1096 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001097 if (TI && FI && TI->getOpcode() == FI->getOpcode())
1098 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1099 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001100
Chris Lattner8f771cb2010-01-05 06:03:12 +00001101 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001102 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Chris Lattner8f771cb2010-01-05 06:03:12 +00001103 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1104 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001105
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001106 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001107 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001108 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1109 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001110
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001111 if (SelectPatternResult::isMinOrMax(SPF)) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001112 // Canonicalize so that type casts are outside select patterns.
1113 if (LHS->getType()->getPrimitiveSizeInBits() !=
Sanjay Patel25600f32016-07-07 15:28:17 +00001114 SelType->getPrimitiveSizeInBits()) {
James Molloy134bec22015-08-11 09:12:57 +00001115 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1116
1117 Value *Cmp;
1118 if (CmpInst::isIntPredicate(Pred)) {
1119 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1120 } else {
1121 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1122 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Sanjay Patela2528152016-01-12 18:03:37 +00001123 Builder->setFastMathFlags(FMF);
James Molloy134bec22015-08-11 09:12:57 +00001124 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1125 }
1126
James Molloy2b21a7c2015-05-20 18:41:25 +00001127 Value *NewSI = Builder->CreateCast(CastOp,
1128 Builder->CreateSelect(Cmp, LHS, RHS),
Sanjay Patel25600f32016-07-07 15:28:17 +00001129 SelType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001130 return replaceInstUsesWith(SI, NewSI);
James Molloy2b21a7c2015-05-20 18:41:25 +00001131 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001132 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001133
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001134 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001135 // MAX(MAX(a, b), a) -> MAX(a, b)
1136 // MIN(MIN(a, b), a) -> MIN(a, b)
1137 // MAX(MIN(a, b), a) -> a
1138 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001139 // ABS(ABS(a)) -> ABS(a)
1140 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001141 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001142 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001143 SI, SPF, RHS))
1144 return R;
James Molloy134bec22015-08-11 09:12:57 +00001145 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001146 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1147 SI, SPF, LHS))
1148 return R;
1149 }
1150
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001151 // MAX(~a, ~b) -> ~MIN(a, b)
1152 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1153 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1154 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1155
1156 // This transform adds a xor operation and that extra cost needs to be
1157 // justified. We look for simplifications that will result from
1158 // applying this rule:
1159
1160 bool Profitable =
1161 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1162 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1163 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1164
1165 if (Profitable) {
1166 Value *NewLHS = Builder->CreateNot(LHS);
1167 Value *NewRHS = Builder->CreateNot(RHS);
1168 Value *NewCmp = SPF == SPF_SMAX
1169 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1170 : Builder->CreateICmpULT(NewLHS, NewRHS);
1171 Value *NewSI =
1172 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel4b198802016-02-01 22:23:39 +00001173 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001174 }
1175 }
1176 }
1177
Chris Lattner8f771cb2010-01-05 06:03:12 +00001178 // TODO.
1179 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001180 }
1181
1182 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001183 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001184 // The true/false values have to be live in the PHI predecessor's blocks.
1185 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1186 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1187 if (Instruction *NV = FoldOpIntoPhi(SI))
1188 return NV;
1189
Nick Lewyckyb074e322011-01-28 03:28:10 +00001190 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001191 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1192 // select(C, select(C, a, b), c) -> select(C, a, c)
1193 if (TrueSI->getCondition() == CondVal) {
1194 if (SI.getTrueValue() == TrueSI->getTrueValue())
1195 return nullptr;
1196 SI.setOperand(1, TrueSI->getTrueValue());
1197 return &SI;
1198 }
1199 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1200 // We choose this as normal form to enable folding on the And and shortening
1201 // paths for the values (this helps GetUnderlyingObjects() for example).
1202 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1203 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1204 SI.setOperand(0, And);
1205 SI.setOperand(1, TrueSI->getTrueValue());
1206 return &SI;
1207 }
Matthias Braun2e404592015-02-06 17:49:36 +00001208 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001209 }
1210 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001211 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1212 // select(C, a, select(C, b, c)) -> select(C, a, c)
1213 if (FalseSI->getCondition() == CondVal) {
1214 if (SI.getFalseValue() == FalseSI->getFalseValue())
1215 return nullptr;
1216 SI.setOperand(2, FalseSI->getFalseValue());
1217 return &SI;
1218 }
1219 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1220 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1221 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1222 SI.setOperand(0, Or);
1223 SI.setOperand(2, FalseSI->getFalseValue());
1224 return &SI;
1225 }
Matthias Braun2e404592015-02-06 17:49:36 +00001226 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001227 }
1228
Chris Lattner8f771cb2010-01-05 06:03:12 +00001229 if (BinaryOperator::isNot(CondVal)) {
1230 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1231 SI.setOperand(1, FalseVal);
1232 SI.setOperand(2, TrueVal);
1233 return &SI;
1234 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001235
Sanjay Patel25600f32016-07-07 15:28:17 +00001236 if (VectorType* VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001237 unsigned VWidth = VecTy->getNumElements();
1238 APInt UndefElts(VWidth, 0);
1239 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1240 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1241 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001242 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001243 return &SI;
1244 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001245
Nick Lewycky156999f2012-09-28 09:33:53 +00001246 if (isa<ConstantAggregateZero>(CondVal)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001247 return replaceInstUsesWith(SI, FalseVal);
Nick Lewycky156999f2012-09-28 09:33:53 +00001248 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001249 }
1250
Chad Rosiercd62bf52016-04-29 21:12:31 +00001251 // See if we can determine the result of this select based on a dominating
1252 // condition.
1253 BasicBlock *Parent = SI.getParent();
1254 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1255 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1256 if (PBI && PBI->isConditional() &&
1257 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1258 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1259 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1260 Optional<bool> Implication = isImpliedCondition(
1261 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1262 if (Implication) {
1263 Value *V = *Implication ? TrueVal : FalseVal;
1264 return replaceInstUsesWith(SI, V);
1265 }
1266 }
1267 }
1268
Craig Topperf40110f2014-04-25 05:29:35 +00001269 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001270}