blob: b5b8aa3326764ec3a9e294944e01c85440f798e1 [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"
Xinliang David Licad3a992016-08-25 00:26:32 +000018#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000020#include "llvm/Support/KnownBits.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Sanjoy Das08e95b42015-04-30 04:56:04 +000026static SelectPatternFlavor
27getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
28 switch (SPF) {
29 default:
30 llvm_unreachable("unhandled!");
31
32 case SPF_SMIN:
33 return SPF_SMAX;
34 case SPF_UMIN:
35 return SPF_UMAX;
36 case SPF_SMAX:
37 return SPF_SMIN;
38 case SPF_UMAX:
39 return SPF_UMIN;
40 }
41}
42
James Molloy134bec22015-08-11 09:12:57 +000043static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
44 bool Ordered=false) {
Sanjoy Das08e95b42015-04-30 04:56:04 +000045 switch (SPF) {
46 default:
47 llvm_unreachable("unhandled!");
48
49 case SPF_SMIN:
50 return ICmpInst::ICMP_SLT;
51 case SPF_UMIN:
52 return ICmpInst::ICMP_ULT;
53 case SPF_SMAX:
54 return ICmpInst::ICMP_SGT;
55 case SPF_UMAX:
56 return ICmpInst::ICMP_UGT;
James Molloy134bec22015-08-11 09:12:57 +000057 case SPF_FMINNUM:
58 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
59 case SPF_FMAXNUM:
60 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
Sanjoy Das08e95b42015-04-30 04:56:04 +000061 }
62}
63
Craig Topperbb4069e2017-07-07 23:16:26 +000064static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
Sanjoy Das08e95b42015-04-30 04:56:04 +000065 SelectPatternFlavor SPF, Value *A,
66 Value *B) {
James Molloy134bec22015-08-11 09:12:57 +000067 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
68 assert(CmpInst::isIntPredicate(Pred));
Craig Topperbb4069e2017-07-07 23:16:26 +000069 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
Sanjoy Das08e95b42015-04-30 04:56:04 +000070}
71
Sanjay Patel6eccf482015-09-09 15:24:36 +000072/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +000073/// %C = or %A, %B
74/// %D = select %cond, %C, %A
75/// into:
76/// %C = select %cond, %B, 0
77/// %D = or %A, %C
78///
79/// Assuming that the specified instruction is an operand to the select, return
80/// a bitmask indicating which operands of this instruction are foldable if they
81/// equal the other incoming value of the select.
82///
Sanjay Patel453ceff2016-09-29 22:18:30 +000083static unsigned getSelectFoldableOperands(Instruction *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +000084 switch (I->getOpcode()) {
85 case Instruction::Add:
86 case Instruction::Mul:
87 case Instruction::And:
88 case Instruction::Or:
89 case Instruction::Xor:
90 return 3; // Can fold through either operand.
91 case Instruction::Sub: // Can only fold on the amount subtracted.
92 case Instruction::Shl: // Can only fold on the shift amount.
93 case Instruction::LShr:
94 case Instruction::AShr:
95 return 1;
96 default:
97 return 0; // Cannot fold
98 }
99}
100
Sanjay Patel6eccf482015-09-09 15:24:36 +0000101/// For the same transformation as the previous function, return the identity
102/// constant that goes into the select.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000103static Constant *getSelectFoldableConstant(Instruction *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000104 switch (I->getOpcode()) {
105 default: llvm_unreachable("This cannot happen!");
106 case Instruction::Add:
107 case Instruction::Sub:
108 case Instruction::Or:
109 case Instruction::Xor:
110 case Instruction::Shl:
111 case Instruction::LShr:
112 case Instruction::AShr:
113 return Constant::getNullValue(I->getType());
114 case Instruction::And:
115 return Constant::getAllOnesValue(I->getType());
116 case Instruction::Mul:
117 return ConstantInt::get(I->getType(), 1);
118 }
119}
120
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000121/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000122Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000123 Instruction *FI) {
Sanjay Patel6105bb52017-03-16 20:42:45 +0000124 // Don't break up min/max patterns. The hasOneUse checks below prevent that
125 // for most cases, but vector min/max with bitcasts can be transformed. If the
126 // one-use restrictions are eased for other patterns, we still don't want to
127 // obfuscate min/max.
128 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
129 match(&SI, m_SMax(m_Value(), m_Value())) ||
130 match(&SI, m_UMin(m_Value(), m_Value())) ||
131 match(&SI, m_UMax(m_Value(), m_Value()))))
132 return nullptr;
133
Sanjay Patel384d0f22016-06-08 20:31:52 +0000134 // If this is a cast from the same type, merge.
135 if (TI->getNumOperands() == 1 && TI->isCast()) {
136 Type *FIOpndTy = FI->getOperand(0)->getType();
137 if (TI->getOperand(0)->getType() != FIOpndTy)
138 return nullptr;
139
140 // The select condition may be a vector. We may only change the operand
141 // type if the vector width remains the same (and matches the condition).
142 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000143 if (CondTy->isVectorTy()) {
144 if (!FIOpndTy->isVectorTy())
145 return nullptr;
146 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
147 return nullptr;
148
149 // TODO: If the backend knew how to deal with casts better, we could
150 // remove this limitation. For now, there's too much potential to create
151 // worse codegen by promoting the select ahead of size-altering casts
152 // (PR28160).
153 //
154 // Note that ValueTracking's matchSelectPattern() looks through casts
155 // without checking 'hasOneUse' when it matches min/max patterns, so this
156 // transform may end up happening anyway.
157 if (TI->getOpcode() != Instruction::BitCast &&
158 (!TI->hasOneUse() || !FI->hasOneUse()))
159 return nullptr;
160
161 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
162 // TODO: The one-use restrictions for a scalar select could be eased if
163 // the fold of a select in visitLoadInst() was enhanced to match a pattern
164 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000165 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000166 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000167
168 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000169 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000170 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
171 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000172 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000173 TI->getType());
174 }
175
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000176 // Only handle binary operators with one-use here. As with the cast case
177 // above, it may be possible to relax the one-use constraint, but that needs
178 // be examined carefully since it may not reduce the total number of
179 // instructions.
Sanjay Patel84ae9432016-11-11 23:20:01 +0000180 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
181 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000182 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000183
184 // Figure out if the operations have any operands in common.
185 Value *MatchOp, *OtherOpT, *OtherOpF;
186 bool MatchIsOpZero;
187 if (TI->getOperand(0) == FI->getOperand(0)) {
188 MatchOp = TI->getOperand(0);
189 OtherOpT = TI->getOperand(1);
190 OtherOpF = FI->getOperand(1);
191 MatchIsOpZero = true;
192 } else if (TI->getOperand(1) == FI->getOperand(1)) {
193 MatchOp = TI->getOperand(1);
194 OtherOpT = TI->getOperand(0);
195 OtherOpF = FI->getOperand(0);
196 MatchIsOpZero = false;
197 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000199 } else if (TI->getOperand(0) == FI->getOperand(1)) {
200 MatchOp = TI->getOperand(0);
201 OtherOpT = TI->getOperand(1);
202 OtherOpF = FI->getOperand(0);
203 MatchIsOpZero = true;
204 } else if (TI->getOperand(1) == FI->getOperand(0)) {
205 MatchOp = TI->getOperand(1);
206 OtherOpT = TI->getOperand(0);
207 OtherOpF = FI->getOperand(1);
208 MatchIsOpZero = true;
209 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000210 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000211 }
212
213 // If we reach here, they do have operations in common.
Craig Topperbb4069e2017-07-07 23:16:26 +0000214 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
215 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000216 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
217 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
218 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000219}
220
221static bool isSelect01(Constant *C1, Constant *C2) {
222 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
223 if (!C1I)
224 return false;
225 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
226 if (!C2I)
227 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000228 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
229 return false;
Craig Topper79ab6432017-07-06 18:39:47 +0000230 return C1I->isOne() || C1I->isMinusOne() ||
231 C2I->isOne() || C2I->isMinusOne();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000232}
233
Sanjay Patel6eccf482015-09-09 15:24:36 +0000234/// Try to fold the select into one of the operands to allow further
235/// optimization.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000236Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000237 Value *FalseVal) {
238 // See the comment above GetSelectFoldableOperands for a description of the
239 // transformation we are doing here.
240 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
241 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
242 !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000243 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000244 unsigned OpToFold = 0;
245 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
246 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000247 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000248 OpToFold = 2;
249 }
250
251 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000252 Constant *C = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000253 Value *OOp = TVI->getOperand(2-OpToFold);
254 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000255 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000256 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000257 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000258 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000259 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000260 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
261 FalseVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000262 BO->copyIRFlags(TVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000263 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000264 }
265 }
266 }
267 }
268 }
269
270 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
271 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
272 !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000273 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000274 unsigned OpToFold = 0;
275 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
276 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000277 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000278 OpToFold = 2;
279 }
280
281 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000282 Constant *C = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000283 Value *OOp = FVI->getOperand(2-OpToFold);
284 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000285 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000286 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000287 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000288 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000289 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
290 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
291 TrueVal, NewSel);
Sanjay Patel916f8a02016-06-08 19:33:52 +0000292 BO->copyIRFlags(FVI_BO);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000293 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000294 }
295 }
296 }
297 }
298 }
299
Craig Topperf40110f2014-04-25 05:29:35 +0000300 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000301}
302
Sanjay Patel6eccf482015-09-09 15:24:36 +0000303/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000304/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
305/// into:
Craig Topperae86cc72017-06-21 16:07:13 +0000306/// (or (shl (and X, C1), C3), Y)
David Majnemer8d048d02013-04-30 08:57:58 +0000307/// iff:
308/// C1 and C2 are both powers of 2
309/// where:
310/// C3 = Log(C2) - Log(C1)
311///
312/// This transform handles cases where:
313/// 1. The icmp predicate is inverted
314/// 2. The select operands are reversed
315/// 3. The magnitude of C2 and C1 are flipped
David Majnemer5468e862014-11-26 23:00:38 +0000316static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000317 Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000318 InstCombiner::BuilderTy &Builder) {
David Majnemer8d048d02013-04-30 08:57:58 +0000319 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Craig Topperdffbbcb2017-06-22 16:23:30 +0000320 if (!IC || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000321 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000322
323 Value *CmpLHS = IC->getOperand(0);
324 Value *CmpRHS = IC->getOperand(1);
325
Craig Topperdffbbcb2017-06-22 16:23:30 +0000326 Value *V;
327 unsigned C1Log;
328 bool IsEqualZero;
329 bool NeedAnd = false;
330 if (IC->isEquality()) {
331 if (!match(CmpRHS, m_Zero()))
332 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000333
Craig Topperdffbbcb2017-06-22 16:23:30 +0000334 const APInt *C1;
335 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
336 return nullptr;
337
338 V = CmpLHS;
339 C1Log = C1->logBase2();
340 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
341 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
342 IC->getPredicate() == ICmpInst::ICMP_SGT) {
343 // We also need to recognize (icmp slt (trunc (X)), 0) and
344 // (icmp sgt (trunc (X)), -1).
345 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
346 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
347 (!IsEqualZero && !match(CmpRHS, m_Zero())))
348 return nullptr;
349
350 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
351 return nullptr;
352
353 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
354 NeedAnd = true;
355 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000356 return nullptr;
Craig Topperdffbbcb2017-06-22 16:23:30 +0000357 }
David Majnemer8d048d02013-04-30 08:57:58 +0000358
359 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000360 bool OrOnTrueVal = false;
361 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
362 if (!OrOnFalseVal)
363 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000364
365 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000366 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000367
David Majnemer8d048d02013-04-30 08:57:58 +0000368 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
369
David Majnemer8d048d02013-04-30 08:57:58 +0000370 unsigned C2Log = C2->logBase2();
Craig Topperae86cc72017-06-21 16:07:13 +0000371
Craig Topperdffbbcb2017-06-22 16:23:30 +0000372 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
Craig Topperae86cc72017-06-21 16:07:13 +0000373 bool NeedShift = C1Log != C2Log;
374 bool NeedZExtTrunc = Y->getType()->getIntegerBitWidth() !=
375 V->getType()->getIntegerBitWidth();
376
377 // Make sure we don't create more instructions than we save.
378 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
379 if ((NeedShift + NeedXor + NeedZExtTrunc) >
380 (IC->hasOneUse() + Or->hasOneUse()))
381 return nullptr;
382
Craig Topperdffbbcb2017-06-22 16:23:30 +0000383 if (NeedAnd) {
384 // Insert the AND instruction on the input to the truncate.
385 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
Craig Topperbb4069e2017-07-07 23:16:26 +0000386 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
Craig Topperdffbbcb2017-06-22 16:23:30 +0000387 }
388
David Majnemer8d048d02013-04-30 08:57:58 +0000389 if (C2Log > C1Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000390 V = Builder.CreateZExtOrTrunc(V, Y->getType());
391 V = Builder.CreateShl(V, C2Log - C1Log);
David Majnemer8d048d02013-04-30 08:57:58 +0000392 } else if (C1Log > C2Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000393 V = Builder.CreateLShr(V, C1Log - C2Log);
394 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000395 } else
Craig Topperbb4069e2017-07-07 23:16:26 +0000396 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000397
Craig Topperae86cc72017-06-21 16:07:13 +0000398 if (NeedXor)
Craig Topperbb4069e2017-07-07 23:16:26 +0000399 V = Builder.CreateXor(V, *C2);
David Majnemer8d048d02013-04-30 08:57:58 +0000400
Craig Topperbb4069e2017-07-07 23:16:26 +0000401 return Builder.CreateOr(V, Y);
David Majnemer8d048d02013-04-30 08:57:58 +0000402}
403
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000404/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
405/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
406///
407/// For example, we can fold the following code sequence:
408/// \code
409/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
410/// %1 = icmp ne i32 %x, 0
411/// %2 = select i1 %1, i32 %0, i32 32
412/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000413///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000414/// into:
415/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
416static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000417 InstCombiner::BuilderTy &Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000418 ICmpInst::Predicate Pred = ICI->getPredicate();
419 Value *CmpLHS = ICI->getOperand(0);
420 Value *CmpRHS = ICI->getOperand(1);
421
422 // Check if the condition value compares a value for equality against zero.
423 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
424 return nullptr;
425
426 Value *Count = FalseVal;
427 Value *ValueOnZero = TrueVal;
428 if (Pred == ICmpInst::ICMP_NE)
429 std::swap(Count, ValueOnZero);
430
431 // Skip zero extend/truncate.
432 Value *V = nullptr;
433 if (match(Count, m_ZExt(m_Value(V))) ||
434 match(Count, m_Trunc(m_Value(V))))
435 Count = V;
436
437 // Check if the value propagated on zero is a constant number equal to the
438 // sizeof in bits of 'Count'.
439 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
440 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
441 return nullptr;
442
443 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
444 // input to the cttz/ctlz is used as LHS for the compare instruction.
445 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
446 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
447 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000448 // Explicitly clear the 'undef_on_zero' flag.
449 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Craig Topper3b74a682017-08-04 16:07:18 +0000450 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
Craig Topperbb4069e2017-07-07 23:16:26 +0000451 Builder.Insert(NewI);
452 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000453 }
454
455 return nullptr;
456}
457
Sanjay Patel7ce65832016-11-01 17:46:08 +0000458/// Return true if we find and adjust an icmp+select pattern where the compare
459/// is with a constant that can be incremented or decremented to match the
460/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000461static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
462 ICmpInst::Predicate Pred = Cmp.getPredicate();
463 Value *CmpLHS = Cmp.getOperand(0);
464 Value *CmpRHS = Cmp.getOperand(1);
465 Value *TrueVal = Sel.getTrueValue();
466 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000467
Sanjay Patel644d7c32016-11-01 18:15:03 +0000468 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000469 const APInt *CmpC;
470 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000471 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000472
Sanjay Patel86408a82016-11-07 15:52:45 +0000473 // These transforms only work for selects of integers or vector selects of
474 // integer vectors.
475 Type *SelTy = Sel.getType();
476 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
477 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000478 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000479
Sanjay Patel644d7c32016-11-01 18:15:03 +0000480 Constant *AdjustedRHS;
481 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000482 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000483 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000484 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000485 else
486 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000487
Sanjay Patel644d7c32016-11-01 18:15:03 +0000488 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
489 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
490 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
491 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
492 ; // Nothing to do here. Values match without any sign/zero extension.
493 }
494 // Types do not match. Instead of calculating this with mixed types, promote
495 // all to the larger type. This enables scalar evolution to analyze this
496 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000497 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
498 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000499
Sanjay Patel644d7c32016-11-01 18:15:03 +0000500 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
501 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
502 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
503 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
504 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
505 CmpLHS = TrueVal;
506 AdjustedRHS = SextRHS;
507 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
508 SextRHS == TrueVal) {
509 CmpLHS = FalseVal;
510 AdjustedRHS = SextRHS;
511 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000512 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000513 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
514 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
515 // zext + signed compare cannot be changed:
516 // 0xff <s 0x00, but 0x00ff >s 0x0000
517 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
518 CmpLHS = TrueVal;
519 AdjustedRHS = ZextRHS;
520 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
521 ZextRHS == TrueVal) {
522 CmpLHS = FalseVal;
523 AdjustedRHS = ZextRHS;
524 } else {
525 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000526 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000527 } else {
528 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000529 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000530 } else {
531 return false;
532 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000533
Sanjay Patel644d7c32016-11-01 18:15:03 +0000534 Pred = ICmpInst::getSwappedPredicate(Pred);
535 CmpRHS = AdjustedRHS;
536 std::swap(FalseVal, TrueVal);
537 Cmp.setPredicate(Pred);
538 Cmp.setOperand(0, CmpLHS);
539 Cmp.setOperand(1, CmpRHS);
540 Sel.setOperand(1, TrueVal);
541 Sel.setOperand(2, FalseVal);
542 Sel.swapProfMetadata();
543
544 // Move the compare instruction right before the select instruction. Otherwise
545 // the sext/zext value may be defined after the compare instruction uses it.
546 Cmp.moveBefore(&Sel);
547
548 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000549}
550
Sanjay Patelcb731f12017-02-21 19:33:53 +0000551/// If this is an integer min/max (icmp + select) with a constant operand,
552/// create the canonical icmp for the min/max operation and canonicalize the
553/// constant to the 'false' operand of the select:
554/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
555/// Note: if C1 != C2, this will change the icmp constant to the existing
556/// constant operand of the select.
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000557static Instruction *
558canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
559 InstCombiner::BuilderTy &Builder) {
Sanjay Patelcb731f12017-02-21 19:33:53 +0000560 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000561 return nullptr;
562
563 // Canonicalize the compare predicate based on whether we have min or max.
564 Value *LHS, *RHS;
565 ICmpInst::Predicate NewPred;
566 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
567 switch (SPR.Flavor) {
568 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
569 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
570 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
571 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
572 default: return nullptr;
573 }
574
Sanjay Patelcb731f12017-02-21 19:33:53 +0000575 // Is this already canonical?
576 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
577 Cmp.getPredicate() == NewPred)
578 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000579
Sanjay Patelcb731f12017-02-21 19:33:53 +0000580 // Create the canonical compare and plug it into the select.
581 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000582
Sanjay Patelcb731f12017-02-21 19:33:53 +0000583 // If the select operands did not change, we're done.
584 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
585 return &Sel;
586
587 // If we are swapping the select operands, swap the metadata too.
588 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
589 "Unexpected results from matchSelectPattern");
590 Sel.setTrueValue(LHS);
591 Sel.setFalseValue(RHS);
592 Sel.swapProfMetadata();
593 return &Sel;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000594}
595
Craig Topperc2d3c632017-08-04 05:12:37 +0000596/// If one of the constants is zero (we know they can't both be) and we have an
597/// icmp instruction with zero, and we have an 'and' with the non-constant value
598/// and a power of two we can turn the select into a shift on the result of the
599/// 'and'.
600static Value *foldSelectICmpAnd(const SelectInst &SI, const ICmpInst *IC,
601 APInt TrueVal, APInt FalseVal,
602 InstCombiner::BuilderTy &Builder) {
603 if (!IC->isEquality() || !SI.getType()->isIntegerTy())
604 return nullptr;
605
606 if (!match(IC->getOperand(1), m_Zero()))
607 return nullptr;
608
609 ConstantInt *AndRHS;
610 Value *LHS = IC->getOperand(0);
611 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
612 return nullptr;
613
614 // If both select arms are non-zero see if we have a select of the form
615 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
616 // for 'x ? 2^n : 0' and fix the thing up at the end.
617 APInt Offset(TrueVal.getBitWidth(), 0);
618 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
619 if ((TrueVal - FalseVal).isPowerOf2())
620 Offset = FalseVal;
621 else if ((FalseVal - TrueVal).isPowerOf2())
622 Offset = TrueVal;
623 else
624 return nullptr;
625
626 // Adjust TrueVal and FalseVal to the offset.
627 TrueVal -= Offset;
628 FalseVal -= Offset;
629 }
630
631 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
632 if (!AndRHS->getValue().isPowerOf2() ||
633 (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2()))
634 return nullptr;
635
636 // Determine which shift is needed to transform result of the 'and' into the
637 // desired result.
638 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
639 unsigned ValZeros = ValC.logBase2();
640 unsigned AndZeros = AndRHS->getValue().logBase2();
641
642 // If types don't match we can still convert the select by introducing a zext
Craig Topperfc528302017-08-05 01:45:17 +0000643 // or a trunc of the 'and'.
644 Value *V = LHS;
645 if (ValZeros > AndZeros) {
646 V = Builder.CreateZExtOrTrunc(V, SI.getType());
Craig Topperc2d3c632017-08-04 05:12:37 +0000647 V = Builder.CreateShl(V, ValZeros - AndZeros);
Craig Topperfc528302017-08-05 01:45:17 +0000648 } else if (ValZeros < AndZeros) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000649 V = Builder.CreateLShr(V, AndZeros - ValZeros);
Craig Topperfc528302017-08-05 01:45:17 +0000650 V = Builder.CreateZExtOrTrunc(V, SI.getType());
651 } else
652 V = Builder.CreateZExtOrTrunc(V, SI.getType());
Craig Topperc2d3c632017-08-04 05:12:37 +0000653
654 // Okay, now we know that everything is set up, we just don't know whether we
655 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
656 bool ShouldNotVal = !TrueVal.isNullValue();
657 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
658 if (ShouldNotVal)
659 V = Builder.CreateXor(V, ValC);
660
661 // Apply an offset if needed.
662 if (!Offset.isNullValue())
663 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
664 return V;
665}
666
Sanjay Patel7ce65832016-11-01 17:46:08 +0000667/// Visit a SelectInst that has an ICmpInst as its first operand.
668Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
669 ICmpInst *ICI) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000670 Value *TrueVal = SI.getTrueValue();
671 Value *FalseVal = SI.getFalseValue();
672
673 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
674 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
675 if (Value *V = foldSelectICmpAnd(SI, ICI, TrueValC->getValue(),
676 FalseValC->getValue(), Builder))
677 return replaceInstUsesWith(SI, V);
678
Craig Topperbb4069e2017-07-07 23:16:26 +0000679 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000680 return NewSel;
681
Sanjay Patel644d7c32016-11-01 18:15:03 +0000682 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000683
684 ICmpInst::Predicate Pred = ICI->getPredicate();
685 Value *CmpLHS = ICI->getOperand(0);
686 Value *CmpRHS = ICI->getOperand(1);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000687
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000688 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
689 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
690 // FIXME: Type and constness constraints could be lifted, but we have to
691 // watch code size carefully. We should consider xor instead of
692 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000693 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000694 if (TrueVal->getType() == Ty) {
695 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000696 ConstantInt *C1 = nullptr, *C2 = nullptr;
Craig Topper79ab6432017-07-06 18:39:47 +0000697 if (Pred == ICmpInst::ICMP_SGT && Cmp->isMinusOne()) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000698 C1 = dyn_cast<ConstantInt>(TrueVal);
699 C2 = dyn_cast<ConstantInt>(FalseVal);
Craig Topper79ab6432017-07-06 18:39:47 +0000700 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isZero()) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000701 C1 = dyn_cast<ConstantInt>(FalseVal);
702 C2 = dyn_cast<ConstantInt>(TrueVal);
703 }
704 if (C1 && C2) {
705 // This shift results in either -1 or 0.
Craig Topperbb4069e2017-07-07 23:16:26 +0000706 Value *AShr = Builder.CreateAShr(CmpLHS, Ty->getBitWidth() - 1);
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000707
708 // Check if we can express the operation with a single or.
Craig Topper79ab6432017-07-06 18:39:47 +0000709 if (C2->isMinusOne())
Craig Topperbb4069e2017-07-07 23:16:26 +0000710 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000711
Craig Topperbb4069e2017-07-07 23:16:26 +0000712 Value *And = Builder.CreateAnd(AShr, C2->getValue() - C1->getValue());
713 return replaceInstUsesWith(SI, Builder.CreateAdd(And, C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000714 }
715 }
716 }
717 }
718
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000719 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
720
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000721 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000722 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
723 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
724 SI.setOperand(1, CmpRHS);
725 Changed = true;
726 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
727 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
728 SI.setOperand(2, CmpRHS);
729 Changed = true;
730 }
731 }
732
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000733 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
734 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000735 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000736 unsigned BitWidth =
737 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
Craig Topperbcfd2d12017-04-20 16:56:25 +0000738 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000739 Value *X;
740 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000741 bool TrueWhenUnset;
742 bool IsBitTest = false;
743 if (ICmpInst::isEquality(Pred) &&
744 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000745 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000746 IsBitTest = true;
747 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
748 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
749 X = CmpLHS;
750 Y = &MinSignedValue;
751 IsBitTest = true;
752 TrueWhenUnset = false;
753 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
754 X = CmpLHS;
755 Y = &MinSignedValue;
756 IsBitTest = true;
757 TrueWhenUnset = true;
758 }
759 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000760 Value *V = nullptr;
761 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000762 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000763 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000764 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000765 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000766 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000767 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000768 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000769 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000770 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000771 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000772 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000773 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000774 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000775 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000776 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000777
778 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000779 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000780 }
781 }
782
David Majnemer8d048d02013-04-30 08:57:58 +0000783 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000784 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000785
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000786 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000787 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000788
Craig Topperf40110f2014-04-25 05:29:35 +0000789 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000790}
791
792
Sanjay Patel6eccf482015-09-09 15:24:36 +0000793/// SI is a select whose condition is a PHI node (but the two may be in
794/// different blocks). See if the true/false values (V) are live in all of the
795/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000796///
797/// X = phi [ C1, BB1], [C2, BB2]
798/// Y = add
799/// Z = select X, Y, 0
800///
801/// because Y is not live in BB1/BB2.
802///
Sanjay Patel453ceff2016-09-29 22:18:30 +0000803static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000804 const SelectInst &SI) {
805 // If the value is a non-instruction value like a constant or argument, it
806 // can always be mapped.
807 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000808 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000809
Chris Lattner8f771cb2010-01-05 06:03:12 +0000810 // If V is a PHI node defined in the same block as the condition PHI, we can
811 // map the arguments.
812 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000813
Chris Lattner8f771cb2010-01-05 06:03:12 +0000814 if (const PHINode *VP = dyn_cast<PHINode>(I))
815 if (VP->getParent() == CondPHI->getParent())
816 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000817
Chris Lattner8f771cb2010-01-05 06:03:12 +0000818 // Otherwise, if the PHI and select are defined in the same block and if V is
819 // defined in a different block, then we can transform it.
820 if (SI.getParent() == CondPHI->getParent() &&
821 I->getParent() != CondPHI->getParent())
822 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000823
Chris Lattner8f771cb2010-01-05 06:03:12 +0000824 // Otherwise we have a 'hard' case and we can't tell without doing more
825 // detailed dominator based analysis, punt.
826 return false;
827}
828
Sanjay Patel6eccf482015-09-09 15:24:36 +0000829/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000830/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000831Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000832 SelectPatternFlavor SPF1,
833 Value *A, Value *B,
834 Instruction &Outer,
835 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000836 if (Outer.getType() != Inner->getType())
837 return nullptr;
838
Chris Lattner8f771cb2010-01-05 06:03:12 +0000839 if (C == A || C == B) {
840 // MAX(MAX(A, B), B) -> MAX(A, B)
841 // MIN(MIN(a, b), a) -> MIN(a, b)
842 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000843 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000844
Chris Lattner8f771cb2010-01-05 06:03:12 +0000845 // MAX(MIN(a, b), a) -> a
846 // MIN(MAX(a, b), a) -> a
847 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
848 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
849 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
850 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000851 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000852 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000853
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000854 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000855 const APInt *CB, *CC;
856 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
857 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
858 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
859 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
860 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
861 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
862 (SPF1 == SPF_SMAX && CB->sge(*CC)))
863 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000864
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000865 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
866 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
867 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
868 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
869 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
870 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
871 Outer.replaceUsesOfWith(Inner, A);
872 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000873 }
874 }
875 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000876
877 // ABS(ABS(X)) -> ABS(X)
878 // NABS(NABS(X)) -> NABS(X)
879 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000880 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000881 }
882
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000883 // ABS(NABS(X)) -> ABS(X)
884 // NABS(ABS(X)) -> NABS(X)
885 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
886 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
887 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000888 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000889 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
890 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000891 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000892 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000893
894 auto IsFreeOrProfitableToInvert =
895 [&](Value *V, Value *&NotV, bool &ElidesXor) {
896 if (match(V, m_Not(m_Value(NotV)))) {
897 // If V has at most 2 uses then we can get rid of the xor operation
898 // entirely.
899 ElidesXor |= !V->hasNUsesOrMore(3);
900 return true;
901 }
902
903 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
904 NotV = nullptr;
905 return true;
906 }
907
908 return false;
909 };
910
911 Value *NotA, *NotB, *NotC;
912 bool ElidesXor = false;
913
914 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
915 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
916 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
917 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
918 //
919 // This transform is performance neutral if we can elide at least one xor from
920 // the set of three operands, since we'll be tacking on an xor at the very
921 // end.
Anna Thomasec36f3b2017-02-21 14:40:28 +0000922 if (SelectPatternResult::isMinOrMax(SPF1) &&
923 SelectPatternResult::isMinOrMax(SPF2) &&
924 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
Sanjoy Das08e95b42015-04-30 04:56:04 +0000925 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
926 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
927 if (!NotA)
Craig Topperbb4069e2017-07-07 23:16:26 +0000928 NotA = Builder.CreateNot(A);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000929 if (!NotB)
Craig Topperbb4069e2017-07-07 23:16:26 +0000930 NotB = Builder.CreateNot(B);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000931 if (!NotC)
Craig Topperbb4069e2017-07-07 23:16:26 +0000932 NotC = Builder.CreateNot(C);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000933
934 Value *NewInner = generateMinMaxSelectPattern(
935 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
Craig Topperbb4069e2017-07-07 23:16:26 +0000936 Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
Sanjoy Das08e95b42015-04-30 04:56:04 +0000937 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000938 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000939 }
940
Craig Topperf40110f2014-04-25 05:29:35 +0000941 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000942}
943
Sanjay Patel39293132016-06-08 21:10:01 +0000944/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
945/// This is even legal for FP.
946static Instruction *foldAddSubSelect(SelectInst &SI,
947 InstCombiner::BuilderTy &Builder) {
948 Value *CondVal = SI.getCondition();
949 Value *TrueVal = SI.getTrueValue();
950 Value *FalseVal = SI.getFalseValue();
951 auto *TI = dyn_cast<Instruction>(TrueVal);
952 auto *FI = dyn_cast<Instruction>(FalseVal);
953 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
954 return nullptr;
955
956 Instruction *AddOp = nullptr, *SubOp = nullptr;
957 if ((TI->getOpcode() == Instruction::Sub &&
958 FI->getOpcode() == Instruction::Add) ||
959 (TI->getOpcode() == Instruction::FSub &&
960 FI->getOpcode() == Instruction::FAdd)) {
961 AddOp = FI;
962 SubOp = TI;
963 } else if ((FI->getOpcode() == Instruction::Sub &&
964 TI->getOpcode() == Instruction::Add) ||
965 (FI->getOpcode() == Instruction::FSub &&
966 TI->getOpcode() == Instruction::FAdd)) {
967 AddOp = TI;
968 SubOp = FI;
969 }
970
971 if (AddOp) {
972 Value *OtherAddOp = nullptr;
973 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
974 OtherAddOp = AddOp->getOperand(1);
975 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
976 OtherAddOp = AddOp->getOperand(0);
977 }
978
979 if (OtherAddOp) {
980 // So at this point we know we have (Y -> OtherAddOp):
981 // select C, (add X, Y), (sub X, Z)
982 Value *NegVal; // Compute -Z
983 if (SI.getType()->isFPOrFPVectorTy()) {
984 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
985 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
986 FastMathFlags Flags = AddOp->getFastMathFlags();
987 Flags &= SubOp->getFastMathFlags();
988 NegInst->setFastMathFlags(Flags);
989 }
990 } else {
991 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
992 }
993
994 Value *NewTrueOp = OtherAddOp;
995 Value *NewFalseOp = NegVal;
996 if (AddOp != TI)
997 std::swap(NewTrueOp, NewFalseOp);
998 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +0000999 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +00001000
1001 if (SI.getType()->isFPOrFPVectorTy()) {
1002 Instruction *RI =
1003 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1004
1005 FastMathFlags Flags = AddOp->getFastMathFlags();
1006 Flags &= SubOp->getFastMathFlags();
1007 RI->setFastMathFlags(Flags);
1008 return RI;
1009 } else
1010 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1011 }
1012 }
1013 return nullptr;
1014}
1015
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001016Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1017 Instruction *ExtInst;
1018 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1019 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1020 return nullptr;
1021
1022 auto ExtOpcode = ExtInst->getOpcode();
1023 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1024 return nullptr;
1025
Sanjay Patel453ceff2016-09-29 22:18:30 +00001026 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001027 Value *X = ExtInst->getOperand(0);
1028 Type *SmallType = X->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001029 if (!SmallType->isIntOrIntVectorTy(1))
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001030 return nullptr;
1031
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001032 Constant *C;
1033 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1034 !match(Sel.getFalseValue(), m_Constant(C)))
1035 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001036
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001037 // If the constant is the same after truncation to the smaller type and
1038 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001039 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001040 Type *SelType = Sel.getType();
1041 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1042 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1043 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001044 Value *TruncCVal = cast<Value>(TruncC);
1045 if (ExtInst == Sel.getFalseValue())
1046 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001047
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001048 // select Cond, (ext X), C --> ext(select Cond, X, C')
1049 // select Cond, C, (ext X) --> ext(select Cond, C', X)
Craig Topperbb4069e2017-07-07 23:16:26 +00001050 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001051 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +00001052 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001053
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001054 // If one arm of the select is the extend of the condition, replace that arm
1055 // with the extension of the appropriate known bool value.
1056 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001057 if (ExtInst == Sel.getTrueValue()) {
1058 // select X, (sext X), C --> select X, -1, C
1059 // select X, (zext X), C --> select X, 1, C
1060 Constant *One = ConstantInt::getTrue(SmallType);
1061 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001062 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001063 } else {
1064 // select X, C, (sext X) --> select X, C, 0
1065 // select X, C, (zext X) --> select X, C, 0
1066 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001067 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001068 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001069 }
1070
Sanjay Patel453ceff2016-09-29 22:18:30 +00001071 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001072}
1073
Sanjay Patelf26710d2016-09-16 22:16:18 +00001074/// Try to transform a vector select with a constant condition vector into a
1075/// shuffle for easier combining with other shuffles and insert/extract.
1076static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1077 Value *CondVal = SI.getCondition();
1078 Constant *CondC;
1079 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1080 return nullptr;
1081
1082 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1083 SmallVector<Constant *, 16> Mask;
1084 Mask.reserve(NumElts);
1085 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1086 for (unsigned i = 0; i != NumElts; ++i) {
1087 Constant *Elt = CondC->getAggregateElement(i);
1088 if (!Elt)
1089 return nullptr;
1090
1091 if (Elt->isOneValue()) {
1092 // If the select condition element is true, choose from the 1st vector.
1093 Mask.push_back(ConstantInt::get(Int32Ty, i));
1094 } else if (Elt->isNullValue()) {
1095 // If the select condition element is false, choose from the 2nd vector.
1096 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1097 } else if (isa<UndefValue>(Elt)) {
Sanjay Patel6e410182017-04-12 18:39:53 +00001098 // Undef in a select condition (choose one of the operands) does not mean
1099 // the same thing as undef in a shuffle mask (any value is acceptable), so
1100 // give up.
1101 return nullptr;
Sanjay Patelf26710d2016-09-16 22:16:18 +00001102 } else {
1103 // Bail out on a constant expression.
1104 return nullptr;
1105 }
1106 }
1107
1108 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1109 ConstantVector::get(Mask));
1110}
1111
Sanjay Patel978f8272016-10-29 15:22:04 +00001112/// Reuse bitcasted operands between a compare and select:
1113/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1114/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1115static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1116 InstCombiner::BuilderTy &Builder) {
1117 Value *Cond = Sel.getCondition();
1118 Value *TVal = Sel.getTrueValue();
1119 Value *FVal = Sel.getFalseValue();
1120
1121 CmpInst::Predicate Pred;
1122 Value *A, *B;
1123 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1124 return nullptr;
1125
1126 // The select condition is a compare instruction. If the select's true/false
1127 // values are already the same as the compare operands, there's nothing to do.
1128 if (TVal == A || TVal == B || FVal == A || FVal == B)
1129 return nullptr;
1130
1131 Value *C, *D;
1132 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1133 return nullptr;
1134
1135 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1136 Value *TSrc, *FSrc;
1137 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1138 !match(FVal, m_BitCast(m_Value(FSrc))))
1139 return nullptr;
1140
1141 // If the select true/false values are *different bitcasts* of the same source
1142 // operands, make the select operands the same as the compare operands and
1143 // cast the result. This is the canonical select form for min/max.
1144 Value *NewSel;
1145 if (TSrc == C && FSrc == D) {
1146 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1147 // bitcast (select (cmp A, B), A, B)
1148 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1149 } else if (TSrc == D && FSrc == C) {
1150 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1151 // bitcast (select (cmp A, B), B, A)
1152 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1153 } else {
1154 return nullptr;
1155 }
1156 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1157}
1158
Chris Lattner8f771cb2010-01-05 06:03:12 +00001159Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1160 Value *CondVal = SI.getCondition();
1161 Value *TrueVal = SI.getTrueValue();
1162 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001163 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001164
Wei Mifc0e2452017-07-25 23:37:17 +00001165 // FIXME: Remove this workaround when freeze related patches are done.
1166 // For select with undef operand which feeds into an equality comparison,
1167 // don't simplify it so loop unswitch can know the equality comparison
1168 // may have an undef operand. This is a workaround for PR31652 caused by
1169 // descrepancy about branch on undef between LoopUnswitch and GVN.
1170 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1171 if (any_of(SI.users(), [&](User *U) {
1172 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1173 if (CI && CI->isEquality())
1174 return true;
1175 return false;
1176 })) {
1177 return nullptr;
1178 }
1179 }
1180
Craig Toppera4205622017-06-09 03:21:29 +00001181 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1182 SQ.getWithInstruction(&SI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001183 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001184
Sanjay Patelf26710d2016-09-16 22:16:18 +00001185 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1186 return I;
1187
Sanjay Patel72272762017-06-27 17:53:22 +00001188 // Canonicalize a one-use integer compare with a non-canonical predicate by
1189 // inverting the predicate and swapping the select operands. This matches a
1190 // compare canonicalization for conditional branches.
1191 // TODO: Should we do the same for FP compares?
1192 CmpInst::Predicate Pred;
1193 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1194 !isCanonicalPredicate(Pred)) {
1195 // Swap true/false values and condition.
1196 CmpInst *Cond = cast<CmpInst>(CondVal);
1197 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1198 SI.setOperand(1, FalseVal);
1199 SI.setOperand(2, TrueVal);
1200 SI.swapProfMetadata();
1201 Worklist.Add(Cond);
1202 return &SI;
1203 }
1204
Craig Topperfde47232017-07-09 07:04:03 +00001205 if (SelType->isIntOrIntVectorTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001206 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001207 if (match(TrueVal, m_One())) {
1208 // Change: A = select B, true, C --> A = or B, C
1209 return BinaryOperator::CreateOr(CondVal, FalseVal);
1210 }
1211 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001212 // Change: A = select B, false, C --> A = and !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001213 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001214 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001215 }
Sanjay Patelea234362016-07-06 21:01:26 +00001216 if (match(FalseVal, m_Zero())) {
1217 // Change: A = select B, C, false --> A = and B, C
1218 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1219 }
1220 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001221 // Change: A = select B, C, true --> A = or !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001222 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001223 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001224 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001225
Sanjay Patela1a4e102016-07-03 14:08:19 +00001226 // select a, a, b -> a | b
1227 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001228 if (CondVal == TrueVal)
1229 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001230 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001231 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001232
Sanjay Patela1a4e102016-07-03 14:08:19 +00001233 // select a, ~a, b -> (~a) & b
1234 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001235 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1236 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001237 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001238 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001239 }
1240
Sanjay Patel65a51c22016-07-06 22:23:01 +00001241 // Selecting between two integer or vector splat integer constants?
1242 //
1243 // Note that we don't handle a scalar select of vectors:
1244 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1245 // because that may need 3 instructions to splat the condition value:
1246 // extend, insertelement, shufflevector.
Craig Toppere79b3e72017-07-09 03:25:17 +00001247 if (SelType->isIntOrIntVectorTy() &&
1248 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001249 // select C, 1, 0 -> zext C to int
1250 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001251 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001252
1253 // select C, -1, 0 -> sext C to int
1254 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001255 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001256
1257 // select C, 0, 1 -> zext !C to int
1258 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001259 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001260 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001261 }
1262
1263 // select C, 0, -1 -> sext !C to int
1264 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001265 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001266 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001267 }
1268 }
1269
Chris Lattner8f771cb2010-01-05 06:03:12 +00001270 // See if we are selecting two values based on a comparison of the two values.
1271 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1272 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1273 // Transform (X == Y) ? X : Y -> Y
1274 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001275 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001276 // consider X== -0, Y== +0.
1277 // It becomes safe if either operand is a nonzero constant.
1278 ConstantFP *CFPt, *CFPf;
1279 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1280 !CFPt->getValueAPF().isZero()) ||
1281 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1282 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001283 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001284 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001285 // Transform (X une Y) ? X : Y -> X
1286 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001287 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001288 // consider X== -0, Y== +0.
1289 // It becomes safe if either operand is a nonzero constant.
1290 ConstantFP *CFPt, *CFPf;
1291 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1292 !CFPt->getValueAPF().isZero()) ||
1293 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1294 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001295 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001296 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001297
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001298 // Canonicalize to use ordered comparisons by swapping the select
1299 // operands.
1300 //
1301 // e.g.
1302 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1303 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1304 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001305 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1306 Builder.setFastMathFlags(FCI->getFastMathFlags());
1307 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1308 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001309
1310 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1311 SI.getName() + ".p");
1312 }
1313
1314 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001315 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1316 // Transform (X == Y) ? Y : X -> X
1317 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001318 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001319 // consider X== -0, Y== +0.
1320 // It becomes safe if either operand is a nonzero constant.
1321 ConstantFP *CFPt, *CFPf;
1322 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1323 !CFPt->getValueAPF().isZero()) ||
1324 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1325 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001326 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001327 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001328 // Transform (X une Y) ? Y : X -> Y
1329 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001330 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001331 // consider X== -0, Y== +0.
1332 // It becomes safe if either operand is a nonzero constant.
1333 ConstantFP *CFPt, *CFPf;
1334 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1335 !CFPt->getValueAPF().isZero()) ||
1336 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1337 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001338 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001339 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001340
1341 // Canonicalize to use ordered comparisons by swapping the select
1342 // operands.
1343 //
1344 // e.g.
1345 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1346 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1347 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001348 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1349 Builder.setFastMathFlags(FCI->getFastMathFlags());
1350 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1351 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001352
1353 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1354 SI.getName() + ".p");
1355 }
1356
Chris Lattner8f771cb2010-01-05 06:03:12 +00001357 // NOTE: if we wanted to, this is where to detect MIN/MAX
1358 }
1359 // NOTE: if we wanted to, this is where to detect ABS
1360 }
1361
1362 // See if we are selecting two values based on a comparison of the two values.
1363 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001364 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001365 return Result;
1366
Craig Topperbb4069e2017-07-07 23:16:26 +00001367 if (Instruction *Add = foldAddSubSelect(SI, Builder))
Sanjay Patel39293132016-06-08 21:10:01 +00001368 return Add;
1369
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001370 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001371 auto *TI = dyn_cast<Instruction>(TrueVal);
1372 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001373 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001374 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001375 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001376
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001377 if (Instruction *I = foldSelectExtConst(SI))
1378 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001379
Chris Lattner8f771cb2010-01-05 06:03:12 +00001380 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001381 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001382 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001383 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001384
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001385 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001386 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001387 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1388 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001389
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001390 if (SelectPatternResult::isMinOrMax(SPF)) {
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001391 // Canonicalize so that
1392 // - type casts are outside select patterns.
1393 // - float clamp is transformed to min/max pattern
1394
1395 bool IsCastNeeded = LHS->getType() != SelType;
1396 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1397 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1398 if (IsCastNeeded ||
1399 (LHS->getType()->isFPOrFPVectorTy() &&
1400 ((CmpLHS != LHS && CmpLHS != RHS) ||
1401 (CmpRHS != LHS && CmpRHS != RHS)))) {
James Molloy134bec22015-08-11 09:12:57 +00001402 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1403
1404 Value *Cmp;
1405 if (CmpInst::isIntPredicate(Pred)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001406 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001407 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00001408 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
James Molloy134bec22015-08-11 09:12:57 +00001409 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Craig Topperbb4069e2017-07-07 23:16:26 +00001410 Builder.setFastMathFlags(FMF);
1411 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001412 }
1413
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001414 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1415 if (!IsCastNeeded)
1416 return replaceInstUsesWith(SI, NewSI);
1417
1418 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1419 return replaceInstUsesWith(SI, NewCast);
James Molloy2b21a7c2015-05-20 18:41:25 +00001420 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001421 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001422
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001423 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001424 // MAX(MAX(a, b), a) -> MAX(a, b)
1425 // MIN(MIN(a, b), a) -> MIN(a, b)
1426 // MAX(MIN(a, b), a) -> a
1427 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001428 // ABS(ABS(a)) -> ABS(a)
1429 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001430 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001431 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001432 SI, SPF, RHS))
1433 return R;
James Molloy134bec22015-08-11 09:12:57 +00001434 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001435 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001436 SI, SPF, LHS))
1437 return R;
1438 }
1439
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001440 // MAX(~a, ~b) -> ~MIN(a, b)
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001441 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1442 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1443 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001444 // For this transform to be profitable, we need to eliminate at least two
1445 // 'not' instructions if we're going to add one 'not' instruction.
1446 int NumberOfNots =
1447 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1448 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001449 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001450
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001451 if (NumberOfNots >= 2) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001452 Value *NewLHS = Builder.CreateNot(LHS);
1453 Value *NewRHS = Builder.CreateNot(RHS);
1454 Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1455 : Builder.CreateICmpULT(NewLHS, NewRHS);
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001456 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +00001457 Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001458 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001459 }
1460 }
1461
Chris Lattner8f771cb2010-01-05 06:03:12 +00001462 // TODO.
1463 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001464 }
1465
1466 // See if we can fold the select into a phi node if the condition is a select.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001467 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001468 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001469 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1470 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Craig Topperfb71b7d2017-04-14 19:20:12 +00001471 if (Instruction *NV = foldOpIntoPhi(SI, PN))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001472 return NV;
1473
Nick Lewyckyb074e322011-01-28 03:28:10 +00001474 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001475 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1476 // select(C, select(C, a, b), c) -> select(C, a, c)
1477 if (TrueSI->getCondition() == CondVal) {
1478 if (SI.getTrueValue() == TrueSI->getTrueValue())
1479 return nullptr;
1480 SI.setOperand(1, TrueSI->getTrueValue());
1481 return &SI;
1482 }
1483 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1484 // We choose this as normal form to enable folding on the And and shortening
1485 // paths for the values (this helps GetUnderlyingObjects() for example).
1486 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001487 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001488 SI.setOperand(0, And);
1489 SI.setOperand(1, TrueSI->getTrueValue());
1490 return &SI;
1491 }
Matthias Braun2e404592015-02-06 17:49:36 +00001492 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001493 }
1494 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001495 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1496 // select(C, a, select(C, b, c)) -> select(C, a, c)
1497 if (FalseSI->getCondition() == CondVal) {
1498 if (SI.getFalseValue() == FalseSI->getFalseValue())
1499 return nullptr;
1500 SI.setOperand(2, FalseSI->getFalseValue());
1501 return &SI;
1502 }
1503 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1504 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001505 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001506 SI.setOperand(0, Or);
1507 SI.setOperand(2, FalseSI->getFalseValue());
1508 return &SI;
1509 }
Matthias Braun2e404592015-02-06 17:49:36 +00001510 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001511 }
1512
Chris Lattner8f771cb2010-01-05 06:03:12 +00001513 if (BinaryOperator::isNot(CondVal)) {
1514 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1515 SI.setOperand(1, FalseVal);
1516 SI.setOperand(2, TrueVal);
1517 return &SI;
1518 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001519
Sanjay Patel4e463b42016-09-06 18:16:31 +00001520 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001521 unsigned VWidth = VecTy->getNumElements();
1522 APInt UndefElts(VWidth, 0);
1523 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1524 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1525 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001526 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001527 return &SI;
1528 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001529
Nick Lewycky156999f2012-09-28 09:33:53 +00001530 if (isa<ConstantAggregateZero>(CondVal)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001531 return replaceInstUsesWith(SI, FalseVal);
Nick Lewycky156999f2012-09-28 09:33:53 +00001532 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001533 }
1534
Chad Rosiercd62bf52016-04-29 21:12:31 +00001535 // See if we can determine the result of this select based on a dominating
1536 // condition.
1537 BasicBlock *Parent = SI.getParent();
1538 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1539 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1540 if (PBI && PBI->isConditional() &&
1541 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1542 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
Chad Rosierdfd1de62017-08-01 20:18:54 +00001543 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
Chad Rosiercd62bf52016-04-29 21:12:31 +00001544 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00001545 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
Chad Rosiercd62bf52016-04-29 21:12:31 +00001546 if (Implication) {
1547 Value *V = *Implication ? TrueVal : FalseVal;
1548 return replaceInstUsesWith(SI, V);
1549 }
1550 }
1551 }
1552
Sanjay Patel51783632017-01-13 17:02:42 +00001553 // If we can compute the condition, there's no need for a select.
1554 // Like the above fold, we are attempting to reduce compile-time cost by
1555 // putting this fold here with limitations rather than in InstSimplify.
1556 // The motivation for this call into value tracking is to take advantage of
1557 // the assumption cache, so make sure that is populated.
1558 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001559 KnownBits Known(1);
1560 computeKnownBits(CondVal, Known, 0, &SI);
Craig Topper73ba1c82017-06-07 07:40:37 +00001561 if (Known.One.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001562 return replaceInstUsesWith(SI, TrueVal);
Craig Topper73ba1c82017-06-07 07:40:37 +00001563 if (Known.Zero.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001564 return replaceInstUsesWith(SI, FalseVal);
1565 }
1566
Craig Topperbb4069e2017-07-07 23:16:26 +00001567 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
Sanjay Patel978f8272016-10-29 15:22:04 +00001568 return BitCastSel;
1569
Craig Topperf40110f2014-04-25 05:29:35 +00001570 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001571}