blob: 4d23ce9ac021e60f010c8c421a29028c5eeed941 [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 Patel6eccf482015-09-09 15:24:36 +0000119/// Here we have (select c, TI, FI), and we know that TI and FI
Chris Lattner8f771cb2010-01-05 06:03:12 +0000120/// have the same opcode and only one use each. Try to simplify this.
121Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
122 Instruction *FI) {
123 if (TI->getNumOperands() == 1) {
124 // If this is a non-volatile load or a cast from the same type,
125 // merge.
126 if (TI->isCast()) {
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000127 Type *FIOpndTy = FI->getOperand(0)->getType();
128 if (TI->getOperand(0)->getType() != FIOpndTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000129 return nullptr;
Nadav Rotem4e50efe2012-06-07 20:28:57 +0000130 // The select condition may be a vector. We may only change the operand
131 // type if the vector width remains the same (and matches the condition).
132 Type *CondTy = SI.getCondition()->getType();
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000133 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
134 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000136 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000137 return nullptr; // unknown unary op.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000138 }
139
140 // Fold this by inserting a select from the input values.
Eli Friedman2fd66442011-05-18 18:10:28 +0000141 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
142 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000143 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000144 TI->getType());
145 }
146
147 // Only handle binary operators here.
148 if (!isa<BinaryOperator>(TI))
Craig Topperf40110f2014-04-25 05:29:35 +0000149 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000150
151 // Figure out if the operations have any operands in common.
152 Value *MatchOp, *OtherOpT, *OtherOpF;
153 bool MatchIsOpZero;
154 if (TI->getOperand(0) == FI->getOperand(0)) {
155 MatchOp = TI->getOperand(0);
156 OtherOpT = TI->getOperand(1);
157 OtherOpF = FI->getOperand(1);
158 MatchIsOpZero = true;
159 } else if (TI->getOperand(1) == FI->getOperand(1)) {
160 MatchOp = TI->getOperand(1);
161 OtherOpT = TI->getOperand(0);
162 OtherOpF = FI->getOperand(0);
163 MatchIsOpZero = false;
164 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000165 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000166 } else if (TI->getOperand(0) == FI->getOperand(1)) {
167 MatchOp = TI->getOperand(0);
168 OtherOpT = TI->getOperand(1);
169 OtherOpF = FI->getOperand(0);
170 MatchIsOpZero = true;
171 } else if (TI->getOperand(1) == FI->getOperand(0)) {
172 MatchOp = TI->getOperand(1);
173 OtherOpT = TI->getOperand(0);
174 OtherOpF = FI->getOperand(1);
175 MatchIsOpZero = true;
176 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000177 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000178 }
179
180 // If we reach here, they do have operations in common.
Eli Friedman2fd66442011-05-18 18:10:28 +0000181 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
182 OtherOpF, SI.getName()+".v");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000183
184 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
185 if (MatchIsOpZero)
186 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
187 else
188 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
189 }
190 llvm_unreachable("Shouldn't get here");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000191}
192
193static bool isSelect01(Constant *C1, Constant *C2) {
194 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
195 if (!C1I)
196 return false;
197 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
198 if (!C2I)
199 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000200 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
201 return false;
202 return C1I->isOne() || C1I->isAllOnesValue() ||
203 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000204}
205
Sanjay Patel6eccf482015-09-09 15:24:36 +0000206/// Try to fold the select into one of the operands to allow further
207/// optimization.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000208Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
209 Value *FalseVal) {
210 // See the comment above GetSelectFoldableOperands for a description of the
211 // transformation we are doing here.
212 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
213 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
214 !isa<Constant>(FalseVal)) {
215 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
216 unsigned OpToFold = 0;
217 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
218 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000219 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000220 OpToFold = 2;
221 }
222
223 if (OpToFold) {
224 Constant *C = GetSelectFoldableConstant(TVI);
225 Value *OOp = TVI->getOperand(2-OpToFold);
226 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000227 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000228 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000229 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000230 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000231 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000232 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
233 FalseVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000234 BO->copyIRFlags(TVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000235 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000236 }
237 }
238 }
239 }
240 }
241
242 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
243 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
244 !isa<Constant>(TrueVal)) {
245 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
246 unsigned OpToFold = 0;
247 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
248 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000249 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000250 OpToFold = 2;
251 }
252
253 if (OpToFold) {
254 Constant *C = GetSelectFoldableConstant(FVI);
255 Value *OOp = FVI->getOperand(2-OpToFold);
256 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000257 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000258 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000259 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000260 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000261 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
262 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
263 TrueVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000264 BO->copyIRFlags(FVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000265 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000266 }
267 }
268 }
269 }
270 }
271
Craig Topperf40110f2014-04-25 05:29:35 +0000272 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000273}
274
Sanjay Patel6eccf482015-09-09 15:24:36 +0000275/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000276/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
277/// into:
278/// (or (shl (and X, C1), C3), y)
279/// iff:
280/// C1 and C2 are both powers of 2
281/// where:
282/// C3 = Log(C2) - Log(C1)
283///
284/// This transform handles cases where:
285/// 1. The icmp predicate is inverted
286/// 2. The select operands are reversed
287/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000288static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000289 Value *FalseVal,
290 InstCombiner::BuilderTy *Builder) {
291 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000292 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000293 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000294
295 Value *CmpLHS = IC->getOperand(0);
296 Value *CmpRHS = IC->getOperand(1);
297
298 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000299 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000300
301 Value *X;
302 const APInt *C1;
303 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000304 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000305
306 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000307 bool OrOnTrueVal = false;
308 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
309 if (!OrOnFalseVal)
310 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000311
312 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000313 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000314
315 Value *V = CmpLHS;
316 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
317
318 unsigned C1Log = C1->logBase2();
319 unsigned C2Log = C2->logBase2();
320 if (C2Log > C1Log) {
321 V = Builder->CreateZExtOrTrunc(V, Y->getType());
322 V = Builder->CreateShl(V, C2Log - C1Log);
323 } else if (C1Log > C2Log) {
324 V = Builder->CreateLShr(V, C1Log - C2Log);
325 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000326 } else
327 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000328
329 ICmpInst::Predicate Pred = IC->getPredicate();
330 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
331 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
332 V = Builder->CreateXor(V, *C2);
333
334 return Builder->CreateOr(V, Y);
335}
336
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000337/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
338/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
339///
340/// For example, we can fold the following code sequence:
341/// \code
342/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
343/// %1 = icmp ne i32 %x, 0
344/// %2 = select i1 %1, i32 %0, i32 32
345/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000346///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000347/// into:
348/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
349static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
350 InstCombiner::BuilderTy *Builder) {
351 ICmpInst::Predicate Pred = ICI->getPredicate();
352 Value *CmpLHS = ICI->getOperand(0);
353 Value *CmpRHS = ICI->getOperand(1);
354
355 // Check if the condition value compares a value for equality against zero.
356 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
357 return nullptr;
358
359 Value *Count = FalseVal;
360 Value *ValueOnZero = TrueVal;
361 if (Pred == ICmpInst::ICMP_NE)
362 std::swap(Count, ValueOnZero);
363
364 // Skip zero extend/truncate.
365 Value *V = nullptr;
366 if (match(Count, m_ZExt(m_Value(V))) ||
367 match(Count, m_Trunc(m_Value(V))))
368 Count = V;
369
370 // Check if the value propagated on zero is a constant number equal to the
371 // sizeof in bits of 'Count'.
372 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
373 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
374 return nullptr;
375
376 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
377 // input to the cttz/ctlz is used as LHS for the compare instruction.
378 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
379 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
380 IntrinsicInst *II = cast<IntrinsicInst>(Count);
381 IRBuilder<> Builder(II);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000382 // Explicitly clear the 'undef_on_zero' flag.
383 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
384 Type *Ty = NewI->getArgOperand(1)->getType();
385 NewI->setArgOperand(1, Constant::getNullValue(Ty));
386 Builder.Insert(NewI);
387 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000388 }
389
390 return nullptr;
391}
392
Sanjay Patel6eccf482015-09-09 15:24:36 +0000393/// Visit a SelectInst that has an ICmpInst as its first operand.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000394Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
395 ICmpInst *ICI) {
396 bool Changed = false;
397 ICmpInst::Predicate Pred = ICI->getPredicate();
398 Value *CmpLHS = ICI->getOperand(0);
399 Value *CmpRHS = ICI->getOperand(1);
400 Value *TrueVal = SI.getTrueValue();
401 Value *FalseVal = SI.getFalseValue();
402
403 // Check cases where the comparison is with a constant that
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000404 // can be adjusted to fit the min/max idiom. We may move or edit ICI
405 // here, so make sure the select is the only user.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000406 if (ICI->hasOneUse())
407 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
408 switch (Pred) {
409 default: break;
410 case ICmpInst::ICMP_ULT:
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000411 case ICmpInst::ICMP_SLT:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000412 case ICmpInst::ICMP_UGT:
413 case ICmpInst::ICMP_SGT: {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000414 // These transformations only work for selects over integers.
Chris Lattner229907c2011-07-18 04:54:35 +0000415 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000416 if (!SelectTy)
417 break;
418
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000419 Constant *AdjustedRHS;
420 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
421 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
422 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
423 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
424
Chris Lattner8f771cb2010-01-05 06:03:12 +0000425 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000426 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattner8f771cb2010-01-05 06:03:12 +0000427 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000428 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
429 ; // Nothing to do here. Values match without any sign/zero extension.
430
431 // Types do not match. Instead of calculating this with mixed types
432 // promote all to the larger type. This enables scalar evolution to
433 // analyze this expression.
434 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000435 < SelectTy->getBitWidth()) {
436 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000437
438 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
439 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
440 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
441 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
442 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
443 sextRHS == FalseVal) {
444 CmpLHS = TrueVal;
445 AdjustedRHS = sextRHS;
446 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
447 sextRHS == TrueVal) {
448 CmpLHS = FalseVal;
449 AdjustedRHS = sextRHS;
450 } else if (ICI->isUnsigned()) {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000451 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000452 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
453 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
454 // zext + signed compare cannot be changed:
455 // 0xff <s 0x00, but 0x00ff >s 0x0000
456 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
457 zextRHS == FalseVal) {
458 CmpLHS = TrueVal;
459 AdjustedRHS = zextRHS;
460 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
461 zextRHS == TrueVal) {
462 CmpLHS = FalseVal;
463 AdjustedRHS = zextRHS;
464 } else
465 break;
466 } else
467 break;
468 } else
469 break;
470
471 Pred = ICmpInst::getSwappedPredicate(Pred);
472 CmpRHS = AdjustedRHS;
473 std::swap(FalseVal, TrueVal);
474 ICI->setPredicate(Pred);
475 ICI->setOperand(0, CmpLHS);
476 ICI->setOperand(1, CmpRHS);
477 SI.setOperand(1, TrueVal);
478 SI.setOperand(2, FalseVal);
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000479
480 // Move ICI instruction right before the select instruction. Otherwise
481 // the sext/zext value may be defined after the ICI instruction uses it.
482 ICI->moveBefore(&SI);
483
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000484 Changed = true;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000485 break;
486 }
487 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000488 }
489
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000490 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
491 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
492 // FIXME: Type and constness constraints could be lifted, but we have to
493 // watch code size carefully. We should consider xor instead of
494 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000495 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000496 if (TrueVal->getType() == Ty) {
497 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000498 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000499 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
500 C1 = dyn_cast<ConstantInt>(TrueVal);
501 C2 = dyn_cast<ConstantInt>(FalseVal);
502 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
503 C1 = dyn_cast<ConstantInt>(FalseVal);
504 C2 = dyn_cast<ConstantInt>(TrueVal);
505 }
506 if (C1 && C2) {
507 // This shift results in either -1 or 0.
508 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
509
510 // Check if we can express the operation with a single or.
511 if (C2->isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000512 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000513
514 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000515 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000516 }
517 }
518 }
519 }
520
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000521 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
522
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000523 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000524 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
525 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
526 SI.setOperand(1, CmpRHS);
527 Changed = true;
528 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
529 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
530 SI.setOperand(2, CmpRHS);
531 Changed = true;
532 }
533 }
534
David Majnemer3f0fb982015-06-06 22:40:21 +0000535 {
536 unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType());
David Majnemerb0362e42014-12-20 04:45:35 +0000537 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000538 Value *X;
539 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000540 bool TrueWhenUnset;
541 bool IsBitTest = false;
542 if (ICmpInst::isEquality(Pred) &&
543 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000544 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000545 IsBitTest = true;
546 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
547 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
548 X = CmpLHS;
549 Y = &MinSignedValue;
550 IsBitTest = true;
551 TrueWhenUnset = false;
552 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
553 X = CmpLHS;
554 Y = &MinSignedValue;
555 IsBitTest = true;
556 TrueWhenUnset = true;
557 }
558 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000559 Value *V = nullptr;
560 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000561 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000562 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
563 V = Builder->CreateAnd(X, ~(*Y));
564 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000565 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000566 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
567 V = Builder->CreateAnd(X, ~(*Y));
568 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000569 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000570 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
571 V = Builder->CreateOr(X, *Y);
572 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000573 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000574 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
575 V = Builder->CreateOr(X, *Y);
576
577 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000578 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000579 }
580 }
581
David Majnemer8d048d02013-04-30 08:57:58 +0000582 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000583 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000584
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000585 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000586 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000587
Craig Topperf40110f2014-04-25 05:29:35 +0000588 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000589}
590
591
Sanjay Patel6eccf482015-09-09 15:24:36 +0000592/// SI is a select whose condition is a PHI node (but the two may be in
593/// different blocks). See if the true/false values (V) are live in all of the
594/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000595///
596/// X = phi [ C1, BB1], [C2, BB2]
597/// Y = add
598/// Z = select X, Y, 0
599///
600/// because Y is not live in BB1/BB2.
601///
602static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
603 const SelectInst &SI) {
604 // If the value is a non-instruction value like a constant or argument, it
605 // can always be mapped.
606 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000607 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000608
Chris Lattner8f771cb2010-01-05 06:03:12 +0000609 // If V is a PHI node defined in the same block as the condition PHI, we can
610 // map the arguments.
611 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000612
Chris Lattner8f771cb2010-01-05 06:03:12 +0000613 if (const PHINode *VP = dyn_cast<PHINode>(I))
614 if (VP->getParent() == CondPHI->getParent())
615 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000616
Chris Lattner8f771cb2010-01-05 06:03:12 +0000617 // Otherwise, if the PHI and select are defined in the same block and if V is
618 // defined in a different block, then we can transform it.
619 if (SI.getParent() == CondPHI->getParent() &&
620 I->getParent() != CondPHI->getParent())
621 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000622
Chris Lattner8f771cb2010-01-05 06:03:12 +0000623 // Otherwise we have a 'hard' case and we can't tell without doing more
624 // detailed dominator based analysis, punt.
625 return false;
626}
627
Sanjay Patel6eccf482015-09-09 15:24:36 +0000628/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000629/// SPF2(SPF1(A, B), C)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000630Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
631 SelectPatternFlavor SPF1,
632 Value *A, Value *B,
633 Instruction &Outer,
634 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000635 if (Outer.getType() != Inner->getType())
636 return nullptr;
637
Chris Lattner8f771cb2010-01-05 06:03:12 +0000638 if (C == A || C == B) {
639 // MAX(MAX(A, B), B) -> MAX(A, B)
640 // MIN(MIN(a, b), a) -> MIN(a, b)
641 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000642 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000643
Chris Lattner8f771cb2010-01-05 06:03:12 +0000644 // MAX(MIN(a, b), a) -> a
645 // MIN(MAX(a, b), a) -> a
646 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
647 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
648 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
649 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000650 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000651 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000652
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000653 if (SPF1 == SPF2) {
654 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
655 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000656 const APInt &ACB = CB->getValue();
657 const APInt &ACC = CC->getValue();
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000658
659 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
660 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000661 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
662 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
663 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
664 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000665 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000666
667 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
668 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
669 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
670 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
671 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
672 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
673 Outer.replaceUsesOfWith(Inner, A);
674 return &Outer;
675 }
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000676 }
677 }
678 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000679
680 // ABS(ABS(X)) -> ABS(X)
681 // NABS(NABS(X)) -> NABS(X)
682 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000683 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000684 }
685
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000686 // ABS(NABS(X)) -> ABS(X)
687 // NABS(ABS(X)) -> NABS(X)
688 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
689 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
690 SelectInst *SI = cast<SelectInst>(Inner);
691 Value *NewSI = Builder->CreateSelect(
692 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
Sanjay Patel4b198802016-02-01 22:23:39 +0000693 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000694 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000695
696 auto IsFreeOrProfitableToInvert =
697 [&](Value *V, Value *&NotV, bool &ElidesXor) {
698 if (match(V, m_Not(m_Value(NotV)))) {
699 // If V has at most 2 uses then we can get rid of the xor operation
700 // entirely.
701 ElidesXor |= !V->hasNUsesOrMore(3);
702 return true;
703 }
704
705 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
706 NotV = nullptr;
707 return true;
708 }
709
710 return false;
711 };
712
713 Value *NotA, *NotB, *NotC;
714 bool ElidesXor = false;
715
716 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
717 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
718 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
719 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
720 //
721 // This transform is performance neutral if we can elide at least one xor from
722 // the set of three operands, since we'll be tacking on an xor at the very
723 // end.
724 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
725 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
726 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
727 if (!NotA)
728 NotA = Builder->CreateNot(A);
729 if (!NotB)
730 NotB = Builder->CreateNot(B);
731 if (!NotC)
732 NotC = Builder->CreateNot(C);
733
734 Value *NewInner = generateMinMaxSelectPattern(
735 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
736 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
737 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000738 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000739 }
740
Craig Topperf40110f2014-04-25 05:29:35 +0000741 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000742}
743
Sanjay Patel6eccf482015-09-09 15:24:36 +0000744/// If one of the constants is zero (we know they can't both be) and we have an
745/// icmp instruction with zero, and we have an 'and' with the non-constant value
746/// and a power of two we can turn the select into a shift on the result of the
747/// 'and'.
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000748static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
749 ConstantInt *FalseVal,
750 InstCombiner::BuilderTy *Builder) {
751 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000752 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000753 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000754
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000755 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000756 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000757
758 ConstantInt *AndRHS;
759 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000760 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000761 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000762
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000763 // If both select arms are non-zero see if we have a select of the form
764 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
765 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000766 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000767 if (!TrueVal->isZero() && !FalseVal->isZero()) {
768 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
769 Offset = FalseVal;
770 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
771 Offset = TrueVal;
772 else
Craig Topperf40110f2014-04-25 05:29:35 +0000773 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000774
775 // Adjust TrueVal and FalseVal to the offset.
776 TrueVal = ConstantInt::get(Builder->getContext(),
777 TrueVal->getValue() - Offset->getValue());
778 FalseVal = ConstantInt::get(Builder->getContext(),
779 FalseVal->getValue() - Offset->getValue());
780 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000781
782 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
783 if (!AndRHS->getValue().isPowerOf2() ||
784 (!TrueVal->getValue().isPowerOf2() &&
785 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000786 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000787
788 // Determine which shift is needed to transform result of the 'and' into the
789 // desired result.
790 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
791 unsigned ValZeros = ValC->getValue().logBase2();
792 unsigned AndZeros = AndRHS->getValue().logBase2();
793
Benjamin Kramer4093f292013-06-29 21:17:04 +0000794 // If types don't match we can still convert the select by introducing a zext
795 // or a trunc of the 'and'. The trunc case requires that all of the truncated
796 // bits are zero, we can figure that out by looking at the 'and' mask.
797 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000798 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000799
800 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000801 if (ValZeros > AndZeros)
802 V = Builder->CreateShl(V, ValZeros - AndZeros);
803 else if (ValZeros < AndZeros)
804 V = Builder->CreateLShr(V, AndZeros - ValZeros);
805
806 // Okay, now we know that everything is set up, we just don't know whether we
807 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
808 bool ShouldNotVal = !TrueVal->isZero();
809 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
810 if (ShouldNotVal)
811 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000812
813 // Apply an offset if needed.
814 if (Offset)
815 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000816 return V;
817}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000818
819Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
820 Value *CondVal = SI.getCondition();
821 Value *TrueVal = SI.getTrueValue();
822 Value *FalseVal = SI.getFalseValue();
823
Chandler Carruth66b31302015-01-04 12:03:27 +0000824 if (Value *V =
825 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000826 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000827
Duncan Sands9dff9be2010-02-15 16:12:20 +0000828 if (SI.getType()->isIntegerTy(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000829 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
830 if (C->getZExtValue()) {
831 // Change: A = select B, true, C --> A = or B, C
832 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000833 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000834 // Change: A = select B, false, C --> A = and !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000835 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000836 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000837 }
838 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
David Blaikiedc3f01e2015-03-09 01:57:13 +0000839 if (!C->getZExtValue()) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000840 // Change: A = select B, C, false --> A = and B, C
841 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000842 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000843 // Change: A = select B, C, true --> A = or !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000844 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000845 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000846 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000847
Chris Lattner8f771cb2010-01-05 06:03:12 +0000848 // select a, b, a -> a&b
849 // select a, a, b -> a|b
850 if (CondVal == TrueVal)
851 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000852 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000853 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +0000854
855 // select a, ~a, b -> (~a)&b
856 // select a, b, ~a -> (~a)|b
857 if (match(TrueVal, m_Not(m_Specific(CondVal))))
858 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000859 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +0000860 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000861 }
862
863 // Selecting between two integer constants?
864 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
865 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
866 // select C, 1, 0 -> zext C to int
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000867 if (FalseValC->isZero() && TrueValC->getValue() == 1)
868 return new ZExtInst(CondVal, SI.getType());
869
870 // select C, -1, 0 -> sext C to int
871 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
872 return new SExtInst(CondVal, SI.getType());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000873
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000874 // select C, 0, 1 -> zext !C to int
875 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
876 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
877 return new ZExtInst(NotCond, SI.getType());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000878 }
879
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000880 // select C, 0, -1 -> sext !C to int
881 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
882 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
883 return new SExtInst(NotCond, SI.getType());
884 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000885
886 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000887 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000888 }
889
890 // See if we are selecting two values based on a comparison of the two values.
891 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
892 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
893 // Transform (X == Y) ? X : Y -> Y
894 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000895 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000896 // consider X== -0, Y== +0.
897 // It becomes safe if either operand is a nonzero constant.
898 ConstantFP *CFPt, *CFPf;
899 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
900 !CFPt->getValueAPF().isZero()) ||
901 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
902 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000903 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000904 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000905 // Transform (X une Y) ? X : Y -> X
906 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000907 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000908 // consider X== -0, Y== +0.
909 // It becomes safe if either operand is a nonzero constant.
910 ConstantFP *CFPt, *CFPf;
911 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
912 !CFPt->getValueAPF().isZero()) ||
913 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
914 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000915 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000916 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000917
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000918 // Canonicalize to use ordered comparisons by swapping the select
919 // operands.
920 //
921 // e.g.
922 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
923 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
924 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +0000925 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000926 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000927 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
928 FCI->getName() + ".inv");
929
930 return SelectInst::Create(NewCond, FalseVal, TrueVal,
931 SI.getName() + ".p");
932 }
933
934 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +0000935 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
936 // Transform (X == Y) ? Y : X -> X
937 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000938 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000939 // consider X== -0, Y== +0.
940 // It becomes safe if either operand is a nonzero constant.
941 ConstantFP *CFPt, *CFPf;
942 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
943 !CFPt->getValueAPF().isZero()) ||
944 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
945 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000946 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000947 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000948 // Transform (X une Y) ? Y : X -> Y
949 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000950 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000951 // consider X== -0, Y== +0.
952 // It becomes safe if either operand is a nonzero constant.
953 ConstantFP *CFPt, *CFPf;
954 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
955 !CFPt->getValueAPF().isZero()) ||
956 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
957 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000958 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000959 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000960
961 // Canonicalize to use ordered comparisons by swapping the select
962 // operands.
963 //
964 // e.g.
965 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
966 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
967 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
James Molloy134bec22015-08-11 09:12:57 +0000968 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000969 Builder->setFastMathFlags(FCI->getFastMathFlags());
Matt Arsenault238ff1a2014-11-24 23:15:18 +0000970 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
971 FCI->getName() + ".inv");
972
973 return SelectInst::Create(NewCond, FalseVal, TrueVal,
974 SI.getName() + ".p");
975 }
976
Chris Lattner8f771cb2010-01-05 06:03:12 +0000977 // NOTE: if we wanted to, this is where to detect MIN/MAX
978 }
979 // NOTE: if we wanted to, this is where to detect ABS
980 }
981
982 // See if we are selecting two values based on a comparison of the two values.
983 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
984 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
985 return Result;
986
987 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
988 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
989 if (TI->hasOneUse() && FI->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000990 Instruction *AddOp = nullptr, *SubOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000991
992 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
993 if (TI->getOpcode() == FI->getOpcode())
994 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
995 return IV;
996
997 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
998 // even legal for FP.
999 if ((TI->getOpcode() == Instruction::Sub &&
1000 FI->getOpcode() == Instruction::Add) ||
1001 (TI->getOpcode() == Instruction::FSub &&
1002 FI->getOpcode() == Instruction::FAdd)) {
1003 AddOp = FI; SubOp = TI;
1004 } else if ((FI->getOpcode() == Instruction::Sub &&
1005 TI->getOpcode() == Instruction::Add) ||
1006 (FI->getOpcode() == Instruction::FSub &&
1007 TI->getOpcode() == Instruction::FAdd)) {
1008 AddOp = TI; SubOp = FI;
1009 }
1010
1011 if (AddOp) {
Craig Topperf40110f2014-04-25 05:29:35 +00001012 Value *OtherAddOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001013 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1014 OtherAddOp = AddOp->getOperand(1);
1015 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1016 OtherAddOp = AddOp->getOperand(0);
1017 }
1018
1019 if (OtherAddOp) {
1020 // So at this point we know we have (Y -> OtherAddOp):
1021 // select C, (add X, Y), (sub X, Z)
1022 Value *NegVal; // Compute -Z
Eli Friedman2c980fa2011-06-23 20:40:23 +00001023 if (SI.getType()->isFPOrFPVectorTy()) {
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001024 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
Owen Anderson48b842e2014-01-18 00:48:14 +00001025 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1026 FastMathFlags Flags = AddOp->getFastMathFlags();
1027 Flags &= SubOp->getFastMathFlags();
1028 NegInst->setFastMathFlags(Flags);
1029 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001030 } else {
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001031 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
Chris Lattner8f771cb2010-01-05 06:03:12 +00001032 }
1033
1034 Value *NewTrueOp = OtherAddOp;
1035 Value *NewFalseOp = NegVal;
1036 if (AddOp != TI)
1037 std::swap(NewTrueOp, NewFalseOp);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001038 Value *NewSel =
Eli Friedman0b43b9e2011-05-18 17:58:37 +00001039 Builder->CreateSelect(CondVal, NewTrueOp,
1040 NewFalseOp, SI.getName() + ".p");
Chris Lattner8f771cb2010-01-05 06:03:12 +00001041
Owen Anderson48b842e2014-01-18 00:48:14 +00001042 if (SI.getType()->isFPOrFPVectorTy()) {
1043 Instruction *RI =
1044 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1045
1046 FastMathFlags Flags = AddOp->getFastMathFlags();
1047 Flags &= SubOp->getFastMathFlags();
1048 RI->setFastMathFlags(Flags);
1049 return RI;
1050 } else
Dale Johannesen16bb87a2010-10-27 23:45:18 +00001051 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001052 }
1053 }
1054 }
1055
1056 // See if we can fold the select into one of our operands.
James Molloy134bec22015-08-11 09:12:57 +00001057 if (SI.getType()->isIntOrIntVectorTy() || SI.getType()->isFPOrFPVectorTy()) {
Chris Lattner8f771cb2010-01-05 06:03:12 +00001058 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1059 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001060
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001061 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001062 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001063 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1064 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001065
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001066 if (SelectPatternResult::isMinOrMax(SPF)) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001067 // Canonicalize so that type casts are outside select patterns.
1068 if (LHS->getType()->getPrimitiveSizeInBits() !=
1069 SI.getType()->getPrimitiveSizeInBits()) {
James Molloy134bec22015-08-11 09:12:57 +00001070 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1071
1072 Value *Cmp;
1073 if (CmpInst::isIntPredicate(Pred)) {
1074 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1075 } else {
1076 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1077 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Sanjay Patela2528152016-01-12 18:03:37 +00001078 Builder->setFastMathFlags(FMF);
James Molloy134bec22015-08-11 09:12:57 +00001079 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1080 }
1081
James Molloy2b21a7c2015-05-20 18:41:25 +00001082 Value *NewSI = Builder->CreateCast(CastOp,
1083 Builder->CreateSelect(Cmp, LHS, RHS),
1084 SI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001085 return replaceInstUsesWith(SI, NewSI);
James Molloy2b21a7c2015-05-20 18:41:25 +00001086 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001087 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001088
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001089 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001090 // MAX(MAX(a, b), a) -> MAX(a, b)
1091 // MIN(MIN(a, b), a) -> MIN(a, b)
1092 // MAX(MIN(a, b), a) -> a
1093 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001094 // ABS(ABS(a)) -> ABS(a)
1095 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001096 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001097 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001098 SI, SPF, RHS))
1099 return R;
James Molloy134bec22015-08-11 09:12:57 +00001100 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001101 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1102 SI, SPF, LHS))
1103 return R;
1104 }
1105
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001106 // MAX(~a, ~b) -> ~MIN(a, b)
1107 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1108 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1109 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1110
1111 // This transform adds a xor operation and that extra cost needs to be
1112 // justified. We look for simplifications that will result from
1113 // applying this rule:
1114
1115 bool Profitable =
1116 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1117 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1118 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1119
1120 if (Profitable) {
1121 Value *NewLHS = Builder->CreateNot(LHS);
1122 Value *NewRHS = Builder->CreateNot(RHS);
1123 Value *NewCmp = SPF == SPF_SMAX
1124 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1125 : Builder->CreateICmpULT(NewLHS, NewRHS);
1126 Value *NewSI =
1127 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel4b198802016-02-01 22:23:39 +00001128 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001129 }
1130 }
1131 }
1132
Chris Lattner8f771cb2010-01-05 06:03:12 +00001133 // TODO.
1134 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001135 }
1136
1137 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001138 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001139 // The true/false values have to be live in the PHI predecessor's blocks.
1140 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1141 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1142 if (Instruction *NV = FoldOpIntoPhi(SI))
1143 return NV;
1144
Nick Lewyckyb074e322011-01-28 03:28:10 +00001145 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001146 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1147 // select(C, select(C, a, b), c) -> select(C, a, c)
1148 if (TrueSI->getCondition() == CondVal) {
1149 if (SI.getTrueValue() == TrueSI->getTrueValue())
1150 return nullptr;
1151 SI.setOperand(1, TrueSI->getTrueValue());
1152 return &SI;
1153 }
1154 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1155 // We choose this as normal form to enable folding on the And and shortening
1156 // paths for the values (this helps GetUnderlyingObjects() for example).
1157 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1158 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1159 SI.setOperand(0, And);
1160 SI.setOperand(1, TrueSI->getTrueValue());
1161 return &SI;
1162 }
Matthias Braun2e404592015-02-06 17:49:36 +00001163 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001164 }
1165 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001166 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1167 // select(C, a, select(C, b, c)) -> select(C, a, c)
1168 if (FalseSI->getCondition() == CondVal) {
1169 if (SI.getFalseValue() == FalseSI->getFalseValue())
1170 return nullptr;
1171 SI.setOperand(2, FalseSI->getFalseValue());
1172 return &SI;
1173 }
1174 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1175 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1176 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1177 SI.setOperand(0, Or);
1178 SI.setOperand(2, FalseSI->getFalseValue());
1179 return &SI;
1180 }
Matthias Braun2e404592015-02-06 17:49:36 +00001181 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001182 }
1183
Chris Lattner8f771cb2010-01-05 06:03:12 +00001184 if (BinaryOperator::isNot(CondVal)) {
1185 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1186 SI.setOperand(1, FalseVal);
1187 SI.setOperand(2, TrueVal);
1188 return &SI;
1189 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001190
Nadav Rotemc70ef4e2013-05-06 02:39:09 +00001191 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001192 unsigned VWidth = VecTy->getNumElements();
1193 APInt UndefElts(VWidth, 0);
1194 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1195 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1196 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001197 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001198 return &SI;
1199 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001200
Nick Lewycky156999f2012-09-28 09:33:53 +00001201 if (isa<ConstantAggregateZero>(CondVal)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001202 return replaceInstUsesWith(SI, FalseVal);
Nick Lewycky156999f2012-09-28 09:33:53 +00001203 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001204 }
1205
Chad Rosiercd62bf52016-04-29 21:12:31 +00001206 // See if we can determine the result of this select based on a dominating
1207 // condition.
1208 BasicBlock *Parent = SI.getParent();
1209 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1210 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1211 if (PBI && PBI->isConditional() &&
1212 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1213 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1214 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1215 Optional<bool> Implication = isImpliedCondition(
1216 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1217 if (Implication) {
1218 Value *V = *Implication ? TrueVal : FalseVal;
1219 return replaceInstUsesWith(SI, V);
1220 }
1221 }
1222 }
1223
Craig Topperf40110f2014-04-25 05:29:35 +00001224 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001225}