blob: 83aeda5935e06a12add1db802b54ceac066e6886 [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"
Craig Topper882f2962017-08-16 21:52:07 +000015#include "llvm/Analysis/CmpInstAnalysis.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000016#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000017#include "llvm/Analysis/InstructionSimplify.h"
James Molloy71b91c22015-05-11 14:42:20 +000018#include "llvm/Analysis/ValueTracking.h"
Xinliang David Licad3a992016-08-25 00:26:32 +000019#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000020#include "llvm/IR/PatternMatch.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000021#include "llvm/Support/KnownBits.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000022using namespace llvm;
23using namespace PatternMatch;
24
Chandler Carruth964daaa2014-04-22 02:55:47 +000025#define DEBUG_TYPE "instcombine"
26
Sanjoy Das08e95b42015-04-30 04:56:04 +000027static SelectPatternFlavor
28getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
29 switch (SPF) {
30 default:
31 llvm_unreachable("unhandled!");
32
33 case SPF_SMIN:
34 return SPF_SMAX;
35 case SPF_UMIN:
36 return SPF_UMAX;
37 case SPF_SMAX:
38 return SPF_SMIN;
39 case SPF_UMAX:
40 return SPF_UMIN;
41 }
42}
43
James Molloy134bec22015-08-11 09:12:57 +000044static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
45 bool Ordered=false) {
Sanjoy Das08e95b42015-04-30 04:56:04 +000046 switch (SPF) {
47 default:
48 llvm_unreachable("unhandled!");
49
50 case SPF_SMIN:
51 return ICmpInst::ICMP_SLT;
52 case SPF_UMIN:
53 return ICmpInst::ICMP_ULT;
54 case SPF_SMAX:
55 return ICmpInst::ICMP_SGT;
56 case SPF_UMAX:
57 return ICmpInst::ICMP_UGT;
James Molloy134bec22015-08-11 09:12:57 +000058 case SPF_FMINNUM:
59 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
60 case SPF_FMAXNUM:
61 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
Sanjoy Das08e95b42015-04-30 04:56:04 +000062 }
63}
64
Craig Topperbb4069e2017-07-07 23:16:26 +000065static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
Sanjoy Das08e95b42015-04-30 04:56:04 +000066 SelectPatternFlavor SPF, Value *A,
67 Value *B) {
James Molloy134bec22015-08-11 09:12:57 +000068 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
69 assert(CmpInst::isIntPredicate(Pred));
Craig Topperbb4069e2017-07-07 23:16:26 +000070 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
Sanjoy Das08e95b42015-04-30 04:56:04 +000071}
72
Sanjay Patel6eccf482015-09-09 15:24:36 +000073/// We want to turn code that looks like this:
Chris Lattner8f771cb2010-01-05 06:03:12 +000074/// %C = or %A, %B
75/// %D = select %cond, %C, %A
76/// into:
77/// %C = select %cond, %B, 0
78/// %D = or %A, %C
79///
80/// Assuming that the specified instruction is an operand to the select, return
81/// a bitmask indicating which operands of this instruction are foldable if they
82/// equal the other incoming value of the select.
83///
Craig Topper8e351e92017-08-08 06:19:24 +000084static unsigned getSelectFoldableOperands(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +000085 switch (I->getOpcode()) {
86 case Instruction::Add:
87 case Instruction::Mul:
88 case Instruction::And:
89 case Instruction::Or:
90 case Instruction::Xor:
91 return 3; // Can fold through either operand.
92 case Instruction::Sub: // Can only fold on the amount subtracted.
93 case Instruction::Shl: // Can only fold on the shift amount.
94 case Instruction::LShr:
95 case Instruction::AShr:
96 return 1;
97 default:
98 return 0; // Cannot fold
99 }
100}
101
Sanjay Patel6eccf482015-09-09 15:24:36 +0000102/// For the same transformation as the previous function, return the identity
103/// constant that goes into the select.
Craig Topper8e351e92017-08-08 06:19:24 +0000104static Constant *getSelectFoldableConstant(BinaryOperator *I) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000105 switch (I->getOpcode()) {
106 default: llvm_unreachable("This cannot happen!");
107 case Instruction::Add:
108 case Instruction::Sub:
109 case Instruction::Or:
110 case Instruction::Xor:
111 case Instruction::Shl:
112 case Instruction::LShr:
113 case Instruction::AShr:
114 return Constant::getNullValue(I->getType());
115 case Instruction::And:
116 return Constant::getAllOnesValue(I->getType());
117 case Instruction::Mul:
118 return ConstantInt::get(I->getType(), 1);
119 }
120}
121
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000122/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
Sanjay Patel453ceff2016-09-29 22:18:30 +0000123Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000124 Instruction *FI) {
Sanjay Patel6105bb52017-03-16 20:42:45 +0000125 // Don't break up min/max patterns. The hasOneUse checks below prevent that
126 // for most cases, but vector min/max with bitcasts can be transformed. If the
127 // one-use restrictions are eased for other patterns, we still don't want to
128 // obfuscate min/max.
129 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
130 match(&SI, m_SMax(m_Value(), m_Value())) ||
131 match(&SI, m_UMin(m_Value(), m_Value())) ||
132 match(&SI, m_UMax(m_Value(), m_Value()))))
133 return nullptr;
134
Sanjay Patel384d0f22016-06-08 20:31:52 +0000135 // If this is a cast from the same type, merge.
136 if (TI->getNumOperands() == 1 && TI->isCast()) {
137 Type *FIOpndTy = FI->getOperand(0)->getType();
138 if (TI->getOperand(0)->getType() != FIOpndTy)
139 return nullptr;
140
141 // The select condition may be a vector. We may only change the operand
142 // type if the vector width remains the same (and matches the condition).
143 Type *CondTy = SI.getCondition()->getType();
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000144 if (CondTy->isVectorTy()) {
145 if (!FIOpndTy->isVectorTy())
146 return nullptr;
147 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
148 return nullptr;
149
150 // TODO: If the backend knew how to deal with casts better, we could
151 // remove this limitation. For now, there's too much potential to create
152 // worse codegen by promoting the select ahead of size-altering casts
153 // (PR28160).
154 //
155 // Note that ValueTracking's matchSelectPattern() looks through casts
156 // without checking 'hasOneUse' when it matches min/max patterns, so this
157 // transform may end up happening anyway.
158 if (TI->getOpcode() != Instruction::BitCast &&
159 (!TI->hasOneUse() || !FI->hasOneUse()))
160 return nullptr;
161
162 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
163 // TODO: The one-use restrictions for a scalar select could be eased if
164 // the fold of a select in visitLoadInst() was enhanced to match a pattern
165 // that includes a cast.
Sanjay Patel384d0f22016-06-08 20:31:52 +0000166 return nullptr;
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000167 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000168
169 // Fold this by inserting a select from the input values.
Xinliang David Licad3a992016-08-25 00:26:32 +0000170 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000171 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
172 FI->getOperand(0), SI.getName() + ".v", &SI);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000173 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000174 TI->getType());
175 }
176
Sanjay Patel216d8cf2016-06-17 16:46:50 +0000177 // Only handle binary operators with one-use here. As with the cast case
178 // above, it may be possible to relax the one-use constraint, but that needs
179 // be examined carefully since it may not reduce the total number of
180 // instructions.
Sanjay Patel84ae9432016-11-11 23:20:01 +0000181 BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
182 if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +0000183 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000184
185 // Figure out if the operations have any operands in common.
186 Value *MatchOp, *OtherOpT, *OtherOpF;
187 bool MatchIsOpZero;
188 if (TI->getOperand(0) == FI->getOperand(0)) {
189 MatchOp = TI->getOperand(0);
190 OtherOpT = TI->getOperand(1);
191 OtherOpF = FI->getOperand(1);
192 MatchIsOpZero = true;
193 } else if (TI->getOperand(1) == FI->getOperand(1)) {
194 MatchOp = TI->getOperand(1);
195 OtherOpT = TI->getOperand(0);
196 OtherOpF = FI->getOperand(0);
197 MatchIsOpZero = false;
198 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000199 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000200 } else if (TI->getOperand(0) == FI->getOperand(1)) {
201 MatchOp = TI->getOperand(0);
202 OtherOpT = TI->getOperand(1);
203 OtherOpF = FI->getOperand(0);
204 MatchIsOpZero = true;
205 } else if (TI->getOperand(1) == FI->getOperand(0)) {
206 MatchOp = TI->getOperand(1);
207 OtherOpT = TI->getOperand(0);
208 OtherOpF = FI->getOperand(1);
209 MatchIsOpZero = true;
210 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000211 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000212 }
213
214 // If we reach here, they do have operations in common.
Craig Topperbb4069e2017-07-07 23:16:26 +0000215 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
216 SI.getName() + ".v", &SI);
Sanjay Patelcb2199b2016-11-11 23:01:20 +0000217 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
218 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
219 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000220}
221
222static bool isSelect01(Constant *C1, Constant *C2) {
Craig Topper516e39c2017-08-28 22:00:27 +0000223 const APInt *C1I, *C2I;
224 if (!match(C1, m_APInt(C1I)))
Chris Lattner8f771cb2010-01-05 06:03:12 +0000225 return false;
Craig Topper516e39c2017-08-28 22:00:27 +0000226 if (!match(C2, m_APInt(C2I)))
Chris Lattner8f771cb2010-01-05 06:03:12 +0000227 return false;
Craig Topper516e39c2017-08-28 22:00:27 +0000228 if (!C1I->isNullValue() && !C2I->isNullValue()) // One side must be zero.
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000229 return false;
Craig Topper516e39c2017-08-28 22:00:27 +0000230 return C1I->isOneValue() || C1I->isAllOnesValue() ||
231 C2I->isOneValue() || C2I->isAllOnesValue();
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.
Craig Topper8e351e92017-08-08 06:19:24 +0000240 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
241 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000242 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000243 unsigned OpToFold = 0;
244 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
245 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000246 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000247 OpToFold = 2;
248 }
249
250 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000251 Constant *C = getSelectFoldableConstant(TVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000252 Value *OOp = TVI->getOperand(2-OpToFold);
253 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000254 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000255 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000256 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000257 NewSel->takeName(TVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000258 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000259 FalseVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000260 BO->copyIRFlags(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000261 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000262 }
263 }
264 }
265 }
266 }
267
Craig Topper8e351e92017-08-08 06:19:24 +0000268 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
269 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000270 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000271 unsigned OpToFold = 0;
272 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
273 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000274 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000275 OpToFold = 2;
276 }
277
278 if (OpToFold) {
Sanjay Patel453ceff2016-09-29 22:18:30 +0000279 Constant *C = getSelectFoldableConstant(FVI);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000280 Value *OOp = FVI->getOperand(2-OpToFold);
281 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000282 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000283 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000284 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000285 NewSel->takeName(FVI);
Craig Topper8e351e92017-08-08 06:19:24 +0000286 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
Nick Lewycky85442282011-03-27 19:51:23 +0000287 TrueVal, NewSel);
Craig Topper8e351e92017-08-08 06:19:24 +0000288 BO->copyIRFlags(FVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000289 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000290 }
291 }
292 }
293 }
294 }
295
Craig Topperf40110f2014-04-25 05:29:35 +0000296 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000297}
298
Sanjay Patel6eccf482015-09-09 15:24:36 +0000299/// We want to turn:
David Majnemer8d048d02013-04-30 08:57:58 +0000300/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
301/// into:
Craig Topperae86cc72017-06-21 16:07:13 +0000302/// (or (shl (and X, C1), C3), Y)
David Majnemer8d048d02013-04-30 08:57:58 +0000303/// iff:
304/// C1 and C2 are both powers of 2
305/// where:
306/// C3 = Log(C2) - Log(C1)
307///
308/// This transform handles cases where:
309/// 1. The icmp predicate is inverted
310/// 2. The select operands are reversed
311/// 3. The magnitude of C2 and C1 are flipped
Craig Topper5d6ddda2017-08-29 00:13:49 +0000312static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000313 Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000314 InstCombiner::BuilderTy &Builder) {
Craig Topper5d6ddda2017-08-29 00:13:49 +0000315 // Only handle integer compares. Also, if this is a vector select, we need a
316 // vector compare.
317 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
318 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000319 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000320
321 Value *CmpLHS = IC->getOperand(0);
322 Value *CmpRHS = IC->getOperand(1);
323
Craig Topperdffbbcb2017-06-22 16:23:30 +0000324 Value *V;
325 unsigned C1Log;
326 bool IsEqualZero;
327 bool NeedAnd = false;
328 if (IC->isEquality()) {
329 if (!match(CmpRHS, m_Zero()))
330 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000331
Craig Topperdffbbcb2017-06-22 16:23:30 +0000332 const APInt *C1;
333 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
334 return nullptr;
335
336 V = CmpLHS;
337 C1Log = C1->logBase2();
338 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
339 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
340 IC->getPredicate() == ICmpInst::ICMP_SGT) {
341 // We also need to recognize (icmp slt (trunc (X)), 0) and
342 // (icmp sgt (trunc (X)), -1).
343 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
344 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
345 (!IsEqualZero && !match(CmpRHS, m_Zero())))
346 return nullptr;
347
348 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
349 return nullptr;
350
351 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
352 NeedAnd = true;
353 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000354 return nullptr;
Craig Topperdffbbcb2017-06-22 16:23:30 +0000355 }
David Majnemer8d048d02013-04-30 08:57:58 +0000356
357 const APInt *C2;
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000358 bool OrOnTrueVal = false;
359 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
360 if (!OrOnFalseVal)
361 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000362
363 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000364 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000365
David Majnemer8d048d02013-04-30 08:57:58 +0000366 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
367
David Majnemer8d048d02013-04-30 08:57:58 +0000368 unsigned C2Log = C2->logBase2();
Craig Topperae86cc72017-06-21 16:07:13 +0000369
Craig Topperdffbbcb2017-06-22 16:23:30 +0000370 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
Craig Topperae86cc72017-06-21 16:07:13 +0000371 bool NeedShift = C1Log != C2Log;
Craig Topper5d6ddda2017-08-29 00:13:49 +0000372 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
373 V->getType()->getScalarSizeInBits();
Craig Topperae86cc72017-06-21 16:07:13 +0000374
375 // Make sure we don't create more instructions than we save.
376 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
377 if ((NeedShift + NeedXor + NeedZExtTrunc) >
378 (IC->hasOneUse() + Or->hasOneUse()))
379 return nullptr;
380
Craig Topperdffbbcb2017-06-22 16:23:30 +0000381 if (NeedAnd) {
382 // Insert the AND instruction on the input to the truncate.
383 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
Craig Topperbb4069e2017-07-07 23:16:26 +0000384 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
Craig Topperdffbbcb2017-06-22 16:23:30 +0000385 }
386
David Majnemer8d048d02013-04-30 08:57:58 +0000387 if (C2Log > C1Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000388 V = Builder.CreateZExtOrTrunc(V, Y->getType());
389 V = Builder.CreateShl(V, C2Log - C1Log);
David Majnemer8d048d02013-04-30 08:57:58 +0000390 } else if (C1Log > C2Log) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000391 V = Builder.CreateLShr(V, C1Log - C2Log);
392 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000393 } else
Craig Topperbb4069e2017-07-07 23:16:26 +0000394 V = Builder.CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000395
Craig Topperae86cc72017-06-21 16:07:13 +0000396 if (NeedXor)
Craig Topperbb4069e2017-07-07 23:16:26 +0000397 V = Builder.CreateXor(V, *C2);
David Majnemer8d048d02013-04-30 08:57:58 +0000398
Craig Topperbb4069e2017-07-07 23:16:26 +0000399 return Builder.CreateOr(V, Y);
David Majnemer8d048d02013-04-30 08:57:58 +0000400}
401
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000402/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
403/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
404///
405/// For example, we can fold the following code sequence:
406/// \code
407/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
408/// %1 = icmp ne i32 %x, 0
409/// %2 = select i1 %1, i32 %0, i32 32
410/// \code
Junmo Park820964e2016-03-23 01:38:35 +0000411///
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000412/// into:
413/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
414static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
Craig Topperbb4069e2017-07-07 23:16:26 +0000415 InstCombiner::BuilderTy &Builder) {
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000416 ICmpInst::Predicate Pred = ICI->getPredicate();
417 Value *CmpLHS = ICI->getOperand(0);
418 Value *CmpRHS = ICI->getOperand(1);
419
420 // Check if the condition value compares a value for equality against zero.
421 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
422 return nullptr;
423
424 Value *Count = FalseVal;
425 Value *ValueOnZero = TrueVal;
426 if (Pred == ICmpInst::ICMP_NE)
427 std::swap(Count, ValueOnZero);
428
429 // Skip zero extend/truncate.
430 Value *V = nullptr;
431 if (match(Count, m_ZExt(m_Value(V))) ||
432 match(Count, m_Trunc(m_Value(V))))
433 Count = V;
434
435 // Check if the value propagated on zero is a constant number equal to the
436 // sizeof in bits of 'Count'.
437 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
438 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
439 return nullptr;
440
441 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
442 // input to the cttz/ctlz is used as LHS for the compare instruction.
443 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
444 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
445 IntrinsicInst *II = cast<IntrinsicInst>(Count);
Andrea Di Biagio30d471f2015-02-13 16:33:34 +0000446 // Explicitly clear the 'undef_on_zero' flag.
447 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
Craig Topper3b74a682017-08-04 16:07:18 +0000448 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
Craig Topperbb4069e2017-07-07 23:16:26 +0000449 Builder.Insert(NewI);
450 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000451 }
452
453 return nullptr;
454}
455
Sanjay Patel7ce65832016-11-01 17:46:08 +0000456/// Return true if we find and adjust an icmp+select pattern where the compare
457/// is with a constant that can be incremented or decremented to match the
458/// minimum or maximum idiom.
Sanjay Patel644d7c32016-11-01 18:15:03 +0000459static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
460 ICmpInst::Predicate Pred = Cmp.getPredicate();
461 Value *CmpLHS = Cmp.getOperand(0);
462 Value *CmpRHS = Cmp.getOperand(1);
463 Value *TrueVal = Sel.getTrueValue();
464 Value *FalseVal = Sel.getFalseValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000465
Sanjay Patel644d7c32016-11-01 18:15:03 +0000466 // We may move or edit the compare, so make sure the select is the only user.
Sanjay Patel86408a82016-11-07 15:52:45 +0000467 const APInt *CmpC;
468 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
Sanjay Patel644d7c32016-11-01 18:15:03 +0000469 return false;
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000470
Sanjay Patel86408a82016-11-07 15:52:45 +0000471 // These transforms only work for selects of integers or vector selects of
472 // integer vectors.
473 Type *SelTy = Sel.getType();
474 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
475 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
Sanjay Patel644d7c32016-11-01 18:15:03 +0000476 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000477
Sanjay Patel644d7c32016-11-01 18:15:03 +0000478 Constant *AdjustedRHS;
479 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000480 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000481 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
Sanjay Patel86408a82016-11-07 15:52:45 +0000482 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000483 else
484 return false;
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000485
Sanjay Patel644d7c32016-11-01 18:15:03 +0000486 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
487 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
488 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
489 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
490 ; // Nothing to do here. Values match without any sign/zero extension.
491 }
492 // Types do not match. Instead of calculating this with mixed types, promote
493 // all to the larger type. This enables scalar evolution to analyze this
494 // expression.
Sanjay Patel86408a82016-11-07 15:52:45 +0000495 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
496 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000497
Sanjay Patel644d7c32016-11-01 18:15:03 +0000498 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
499 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
500 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
501 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
502 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
503 CmpLHS = TrueVal;
504 AdjustedRHS = SextRHS;
505 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
506 SextRHS == TrueVal) {
507 CmpLHS = FalseVal;
508 AdjustedRHS = SextRHS;
509 } else if (Cmp.isUnsigned()) {
Sanjay Patel86408a82016-11-07 15:52:45 +0000510 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
Sanjay Patel644d7c32016-11-01 18:15:03 +0000511 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
512 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
513 // zext + signed compare cannot be changed:
514 // 0xff <s 0x00, but 0x00ff >s 0x0000
515 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
516 CmpLHS = TrueVal;
517 AdjustedRHS = ZextRHS;
518 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
519 ZextRHS == TrueVal) {
520 CmpLHS = FalseVal;
521 AdjustedRHS = ZextRHS;
522 } else {
523 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000524 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000525 } else {
526 return false;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000527 }
Sanjay Patel644d7c32016-11-01 18:15:03 +0000528 } else {
529 return false;
530 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000531
Sanjay Patel644d7c32016-11-01 18:15:03 +0000532 Pred = ICmpInst::getSwappedPredicate(Pred);
533 CmpRHS = AdjustedRHS;
534 std::swap(FalseVal, TrueVal);
535 Cmp.setPredicate(Pred);
536 Cmp.setOperand(0, CmpLHS);
537 Cmp.setOperand(1, CmpRHS);
538 Sel.setOperand(1, TrueVal);
539 Sel.setOperand(2, FalseVal);
540 Sel.swapProfMetadata();
541
542 // Move the compare instruction right before the select instruction. Otherwise
543 // the sext/zext value may be defined after the compare instruction uses it.
544 Cmp.moveBefore(&Sel);
545
546 return true;
Sanjay Patel7ce65832016-11-01 17:46:08 +0000547}
548
Sanjay Patelcb731f12017-02-21 19:33:53 +0000549/// If this is an integer min/max (icmp + select) with a constant operand,
550/// create the canonical icmp for the min/max operation and canonicalize the
551/// constant to the 'false' operand of the select:
552/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
553/// Note: if C1 != C2, this will change the icmp constant to the existing
554/// constant operand of the select.
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000555static Instruction *
556canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
557 InstCombiner::BuilderTy &Builder) {
Sanjay Patelcb731f12017-02-21 19:33:53 +0000558 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000559 return nullptr;
560
561 // Canonicalize the compare predicate based on whether we have min or max.
562 Value *LHS, *RHS;
563 ICmpInst::Predicate NewPred;
564 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
565 switch (SPR.Flavor) {
566 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
567 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
568 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
569 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
570 default: return nullptr;
571 }
572
Sanjay Patelcb731f12017-02-21 19:33:53 +0000573 // Is this already canonical?
574 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
575 Cmp.getPredicate() == NewPred)
576 return nullptr;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000577
Sanjay Patelcb731f12017-02-21 19:33:53 +0000578 // Create the canonical compare and plug it into the select.
579 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000580
Sanjay Patelcb731f12017-02-21 19:33:53 +0000581 // If the select operands did not change, we're done.
582 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
583 return &Sel;
584
585 // If we are swapping the select operands, swap the metadata too.
586 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
587 "Unexpected results from matchSelectPattern");
588 Sel.setTrueValue(LHS);
589 Sel.setFalseValue(RHS);
590 Sel.swapProfMetadata();
591 return &Sel;
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000592}
593
Craig Topperc2d3c632017-08-04 05:12:37 +0000594/// If one of the constants is zero (we know they can't both be) and we have an
595/// icmp instruction with zero, and we have an 'and' with the non-constant value
596/// and a power of two we can turn the select into a shift on the result of the
597/// 'and'.
Craig Topper74177e12017-08-21 19:02:06 +0000598/// This folds:
599/// select (icmp eq (and X, C1)), C2, C3
600/// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
601/// To something like:
602/// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
603/// Or:
604/// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
605/// With some variations depending if C3 is larger than C2, or the shift
606/// isn't needed, or the bit widths don't match.
Craig Topper1bbcab92017-08-05 20:00:41 +0000607static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
Craig Topperc2d3c632017-08-04 05:12:37 +0000608 APInt TrueVal, APInt FalseVal,
609 InstCombiner::BuilderTy &Builder) {
Craig Topper1bbcab92017-08-05 20:00:41 +0000610 assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
611
612 // If this is a vector select, we need a vector compare.
613 if (SelType->isVectorTy() != IC->getType()->isVectorTy())
614 return nullptr;
615
Craig Topper74177e12017-08-21 19:02:06 +0000616 Value *V;
617 APInt AndMask;
618 bool CreateAnd = false;
619 ICmpInst::Predicate Pred = IC->getPredicate();
620 if (ICmpInst::isEquality(Pred)) {
621 if (!match(IC->getOperand(1), m_Zero()))
622 return nullptr;
Craig Topperc2d3c632017-08-04 05:12:37 +0000623
Craig Topper74177e12017-08-21 19:02:06 +0000624 V = IC->getOperand(0);
Craig Topperc2d3c632017-08-04 05:12:37 +0000625
Craig Topper74177e12017-08-21 19:02:06 +0000626 const APInt *AndRHS;
627 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
628 return nullptr;
629
630 AndMask = *AndRHS;
631 } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
632 Pred, V, AndMask)) {
633 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
634
635 if (!AndMask.isPowerOf2())
636 return nullptr;
637
638 CreateAnd = true;
639 } else {
Craig Topperc2d3c632017-08-04 05:12:37 +0000640 return nullptr;
Craig Topper74177e12017-08-21 19:02:06 +0000641 }
Craig Topperc2d3c632017-08-04 05:12:37 +0000642
643 // If both select arms are non-zero see if we have a select of the form
644 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
645 // for 'x ? 2^n : 0' and fix the thing up at the end.
646 APInt Offset(TrueVal.getBitWidth(), 0);
647 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
648 if ((TrueVal - FalseVal).isPowerOf2())
649 Offset = FalseVal;
650 else if ((FalseVal - TrueVal).isPowerOf2())
651 Offset = TrueVal;
652 else
653 return nullptr;
654
655 // Adjust TrueVal and FalseVal to the offset.
656 TrueVal -= Offset;
657 FalseVal -= Offset;
658 }
659
Craig Topper1bbcab92017-08-05 20:00:41 +0000660 // Make sure one of the select arms is a power of 2.
661 if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
Craig Topperc2d3c632017-08-04 05:12:37 +0000662 return nullptr;
663
664 // Determine which shift is needed to transform result of the 'and' into the
665 // desired result.
666 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
667 unsigned ValZeros = ValC.logBase2();
Craig Topper74177e12017-08-21 19:02:06 +0000668 unsigned AndZeros = AndMask.logBase2();
669
670 if (CreateAnd) {
671 // Insert the AND instruction on the input to the truncate.
672 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
673 }
Craig Topperc2d3c632017-08-04 05:12:37 +0000674
675 // If types don't match we can still convert the select by introducing a zext
Craig Topperfc528302017-08-05 01:45:17 +0000676 // or a trunc of the 'and'.
Craig Topperfc528302017-08-05 01:45:17 +0000677 if (ValZeros > AndZeros) {
Craig Topper1bbcab92017-08-05 20:00:41 +0000678 V = Builder.CreateZExtOrTrunc(V, SelType);
Craig Topperc2d3c632017-08-04 05:12:37 +0000679 V = Builder.CreateShl(V, ValZeros - AndZeros);
Craig Topperfc528302017-08-05 01:45:17 +0000680 } else if (ValZeros < AndZeros) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000681 V = Builder.CreateLShr(V, AndZeros - ValZeros);
Craig Topper1bbcab92017-08-05 20:00:41 +0000682 V = Builder.CreateZExtOrTrunc(V, SelType);
Craig Topperfc528302017-08-05 01:45:17 +0000683 } else
Craig Topper1bbcab92017-08-05 20:00:41 +0000684 V = Builder.CreateZExtOrTrunc(V, SelType);
Craig Topperc2d3c632017-08-04 05:12:37 +0000685
686 // Okay, now we know that everything is set up, we just don't know whether we
687 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
688 bool ShouldNotVal = !TrueVal.isNullValue();
Craig Topper74177e12017-08-21 19:02:06 +0000689 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
Craig Topperc2d3c632017-08-04 05:12:37 +0000690 if (ShouldNotVal)
691 V = Builder.CreateXor(V, ValC);
692
693 // Apply an offset if needed.
694 if (!Offset.isNullValue())
695 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
696 return V;
697}
698
Sanjay Patel7ce65832016-11-01 17:46:08 +0000699/// Visit a SelectInst that has an ICmpInst as its first operand.
700Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
701 ICmpInst *ICI) {
Craig Topperc2d3c632017-08-04 05:12:37 +0000702 Value *TrueVal = SI.getTrueValue();
703 Value *FalseVal = SI.getFalseValue();
704
Craig Topperbb4069e2017-07-07 23:16:26 +0000705 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
Sanjay Patel3b0bafe2016-11-21 22:04:14 +0000706 return NewSel;
707
Sanjay Patel644d7c32016-11-01 18:15:03 +0000708 bool Changed = adjustMinMax(SI, *ICI);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000709
710 ICmpInst::Predicate Pred = ICI->getPredicate();
711 Value *CmpLHS = ICI->getOperand(0);
712 Value *CmpRHS = ICI->getOperand(1);
Sanjay Patel7ce65832016-11-01 17:46:08 +0000713
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000714 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
715 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
716 // FIXME: Type and constness constraints could be lifted, but we have to
717 // watch code size carefully. We should consider xor instead of
718 // sub/add when we decide to do that.
Craig Topper74177e12017-08-21 19:02:06 +0000719 // TODO: Merge this with foldSelectICmpAnd somehow.
Craig Topper882f2962017-08-16 21:52:07 +0000720 if (CmpLHS->getType()->isIntOrIntVectorTy() &&
721 CmpLHS->getType() == TrueVal->getType()) {
722 const APInt *C1, *C2;
723 if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
724 ICmpInst::Predicate Pred = ICI->getPredicate();
725 Value *X;
726 APInt Mask;
Craig Topper924f2022017-09-01 21:27:34 +0000727 if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
Craig Topper882f2962017-08-16 21:52:07 +0000728 if (Mask.isSignMask()) {
729 assert(X == CmpLHS && "Expected to use the compare input directly");
730 assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
731
732 if (Pred == ICmpInst::ICMP_NE)
733 std::swap(C1, C2);
734
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000735 // This shift results in either -1 or 0.
Craig Topper882f2962017-08-16 21:52:07 +0000736 Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000737
738 // Check if we can express the operation with a single or.
Craig Topper882f2962017-08-16 21:52:07 +0000739 if (C2->isAllOnesValue())
740 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000741
Craig Topper882f2962017-08-16 21:52:07 +0000742 Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
743 return replaceInstUsesWith(SI, Builder.CreateAdd(And,
744 ConstantInt::get(And->getType(), *C1)));
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000745 }
746 }
747 }
748 }
749
Craig Topper74177e12017-08-21 19:02:06 +0000750 {
751 const APInt *TrueValC, *FalseValC;
752 if (match(TrueVal, m_APInt(TrueValC)) &&
753 match(FalseVal, m_APInt(FalseValC)))
754 if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
755 *FalseValC, Builder))
756 return replaceInstUsesWith(SI, V);
757 }
758
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000759 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
760
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000761 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000762 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
763 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
764 SI.setOperand(1, CmpRHS);
765 Changed = true;
766 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
767 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
768 SI.setOperand(2, CmpRHS);
769 Changed = true;
770 }
771 }
772
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000773 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
774 // decomposeBitTestICmp() might help.
David Majnemer3f0fb982015-06-06 22:40:21 +0000775 {
Sanjay Patel5f3c7032016-07-20 23:40:01 +0000776 unsigned BitWidth =
777 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
Craig Topperbcfd2d12017-04-20 16:56:25 +0000778 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
David Majnemer40157d52014-11-27 07:25:21 +0000779 Value *X;
780 const APInt *Y, *C;
David Majnemerb0362e42014-12-20 04:45:35 +0000781 bool TrueWhenUnset;
782 bool IsBitTest = false;
783 if (ICmpInst::isEquality(Pred) &&
784 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
David Majnemer40157d52014-11-27 07:25:21 +0000785 match(CmpRHS, m_Zero())) {
David Majnemerb0362e42014-12-20 04:45:35 +0000786 IsBitTest = true;
787 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
788 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
789 X = CmpLHS;
790 Y = &MinSignedValue;
791 IsBitTest = true;
792 TrueWhenUnset = false;
793 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
794 X = CmpLHS;
795 Y = &MinSignedValue;
796 IsBitTest = true;
797 TrueWhenUnset = true;
798 }
799 if (IsBitTest) {
David Majnemer40157d52014-11-27 07:25:21 +0000800 Value *V = nullptr;
801 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000802 if (TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000803 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000804 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000805 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
David Majnemerb0362e42014-12-20 04:45:35 +0000806 else if (!TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000807 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000808 V = Builder.CreateAnd(X, ~(*Y));
David Majnemer40157d52014-11-27 07:25:21 +0000809 // (X & Y) == 0 ? X ^ Y : X --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000810 else if (TrueWhenUnset && FalseVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000811 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000812 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000813 // (X & Y) != 0 ? X : X ^ Y --> X | Y
David Majnemerb0362e42014-12-20 04:45:35 +0000814 else if (!TrueWhenUnset && TrueVal == X &&
David Majnemer40157d52014-11-27 07:25:21 +0000815 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
Craig Topperbb4069e2017-07-07 23:16:26 +0000816 V = Builder.CreateOr(X, *Y);
David Majnemer40157d52014-11-27 07:25:21 +0000817
818 if (V)
Sanjay Patel4b198802016-02-01 22:23:39 +0000819 return replaceInstUsesWith(SI, V);
David Majnemer40157d52014-11-27 07:25:21 +0000820 }
821 }
822
Craig Topper5d6ddda2017-08-29 00:13:49 +0000823 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000824 return replaceInstUsesWith(SI, V);
David Majnemer8d048d02013-04-30 08:57:58 +0000825
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000826 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +0000827 return replaceInstUsesWith(SI, V);
Andrea Di Biagio086cbc32015-01-27 15:58:14 +0000828
Craig Topperf40110f2014-04-25 05:29:35 +0000829 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000830}
831
832
Sanjay Patel6eccf482015-09-09 15:24:36 +0000833/// SI is a select whose condition is a PHI node (but the two may be in
834/// different blocks). See if the true/false values (V) are live in all of the
835/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000836///
837/// X = phi [ C1, BB1], [C2, BB2]
838/// Y = add
839/// Z = select X, Y, 0
840///
841/// because Y is not live in BB1/BB2.
842///
Sanjay Patel453ceff2016-09-29 22:18:30 +0000843static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000844 const SelectInst &SI) {
845 // If the value is a non-instruction value like a constant or argument, it
846 // can always be mapped.
847 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000848 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000849
Chris Lattner8f771cb2010-01-05 06:03:12 +0000850 // If V is a PHI node defined in the same block as the condition PHI, we can
851 // map the arguments.
852 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000853
Chris Lattner8f771cb2010-01-05 06:03:12 +0000854 if (const PHINode *VP = dyn_cast<PHINode>(I))
855 if (VP->getParent() == CondPHI->getParent())
856 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000857
Chris Lattner8f771cb2010-01-05 06:03:12 +0000858 // Otherwise, if the PHI and select are defined in the same block and if V is
859 // defined in a different block, then we can transform it.
860 if (SI.getParent() == CondPHI->getParent() &&
861 I->getParent() != CondPHI->getParent())
862 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000863
Chris Lattner8f771cb2010-01-05 06:03:12 +0000864 // Otherwise we have a 'hard' case and we can't tell without doing more
865 // detailed dominator based analysis, punt.
866 return false;
867}
868
Sanjay Patel6eccf482015-09-09 15:24:36 +0000869/// We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000870/// SPF2(SPF1(A, B), C)
Sanjay Patel453ceff2016-09-29 22:18:30 +0000871Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000872 SelectPatternFlavor SPF1,
873 Value *A, Value *B,
874 Instruction &Outer,
875 SelectPatternFlavor SPF2, Value *C) {
David Majnemer56737722016-04-08 16:51:49 +0000876 if (Outer.getType() != Inner->getType())
877 return nullptr;
878
Chris Lattner8f771cb2010-01-05 06:03:12 +0000879 if (C == A || C == B) {
880 // MAX(MAX(A, B), B) -> MAX(A, B)
881 // MIN(MIN(a, b), a) -> MIN(a, b)
882 if (SPF1 == SPF2)
Sanjay Patel4b198802016-02-01 22:23:39 +0000883 return replaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000884
Chris Lattner8f771cb2010-01-05 06:03:12 +0000885 // MAX(MIN(a, b), a) -> a
886 // MIN(MAX(a, b), a) -> a
887 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
888 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
889 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
890 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Sanjay Patel4b198802016-02-01 22:23:39 +0000891 return replaceInstUsesWith(Outer, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000892 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000893
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000894 if (SPF1 == SPF2) {
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000895 const APInt *CB, *CC;
896 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
897 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
898 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
899 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
900 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
901 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
902 (SPF1 == SPF_SMAX && CB->sge(*CC)))
903 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000904
Sanjay Patelc0de9c92016-10-27 21:19:40 +0000905 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
906 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
907 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
908 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
909 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
910 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
911 Outer.replaceUsesOfWith(Inner, A);
912 return &Outer;
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000913 }
914 }
915 }
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000916
917 // ABS(ABS(X)) -> ABS(X)
918 // NABS(NABS(X)) -> NABS(X)
919 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
Sanjay Patel4b198802016-02-01 22:23:39 +0000920 return replaceInstUsesWith(Outer, Inner);
Dinesh Dwivedi3217b6c2014-06-06 06:54:45 +0000921 }
922
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000923 // ABS(NABS(X)) -> ABS(X)
924 // NABS(ABS(X)) -> NABS(X)
925 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
926 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
927 SelectInst *SI = cast<SelectInst>(Inner);
Xinliang David Licad3a992016-08-25 00:26:32 +0000928 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +0000929 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
930 SI->getTrueValue(), SI->getName(), SI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000931 return replaceInstUsesWith(Outer, NewSI);
Dinesh Dwivedi95f0d512014-06-12 14:06:00 +0000932 }
Sanjoy Das08e95b42015-04-30 04:56:04 +0000933
934 auto IsFreeOrProfitableToInvert =
935 [&](Value *V, Value *&NotV, bool &ElidesXor) {
936 if (match(V, m_Not(m_Value(NotV)))) {
937 // If V has at most 2 uses then we can get rid of the xor operation
938 // entirely.
939 ElidesXor |= !V->hasNUsesOrMore(3);
940 return true;
941 }
942
943 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
944 NotV = nullptr;
945 return true;
946 }
947
948 return false;
949 };
950
951 Value *NotA, *NotB, *NotC;
952 bool ElidesXor = false;
953
954 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
955 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
956 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
957 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
958 //
959 // This transform is performance neutral if we can elide at least one xor from
960 // the set of three operands, since we'll be tacking on an xor at the very
961 // end.
Anna Thomasec36f3b2017-02-21 14:40:28 +0000962 if (SelectPatternResult::isMinOrMax(SPF1) &&
963 SelectPatternResult::isMinOrMax(SPF2) &&
964 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
Sanjoy Das08e95b42015-04-30 04:56:04 +0000965 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
966 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
967 if (!NotA)
Craig Topperbb4069e2017-07-07 23:16:26 +0000968 NotA = Builder.CreateNot(A);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000969 if (!NotB)
Craig Topperbb4069e2017-07-07 23:16:26 +0000970 NotB = Builder.CreateNot(B);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000971 if (!NotC)
Craig Topperbb4069e2017-07-07 23:16:26 +0000972 NotC = Builder.CreateNot(C);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000973
974 Value *NewInner = generateMinMaxSelectPattern(
975 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
Craig Topperbb4069e2017-07-07 23:16:26 +0000976 Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
Sanjoy Das08e95b42015-04-30 04:56:04 +0000977 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
Sanjay Patel4b198802016-02-01 22:23:39 +0000978 return replaceInstUsesWith(Outer, NewOuter);
Sanjoy Das08e95b42015-04-30 04:56:04 +0000979 }
980
Craig Topperf40110f2014-04-25 05:29:35 +0000981 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000982}
983
Sanjay Patel39293132016-06-08 21:10:01 +0000984/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
985/// This is even legal for FP.
986static Instruction *foldAddSubSelect(SelectInst &SI,
987 InstCombiner::BuilderTy &Builder) {
988 Value *CondVal = SI.getCondition();
989 Value *TrueVal = SI.getTrueValue();
990 Value *FalseVal = SI.getFalseValue();
991 auto *TI = dyn_cast<Instruction>(TrueVal);
992 auto *FI = dyn_cast<Instruction>(FalseVal);
993 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
994 return nullptr;
995
996 Instruction *AddOp = nullptr, *SubOp = nullptr;
997 if ((TI->getOpcode() == Instruction::Sub &&
998 FI->getOpcode() == Instruction::Add) ||
999 (TI->getOpcode() == Instruction::FSub &&
1000 FI->getOpcode() == Instruction::FAdd)) {
1001 AddOp = FI;
1002 SubOp = TI;
1003 } else if ((FI->getOpcode() == Instruction::Sub &&
1004 TI->getOpcode() == Instruction::Add) ||
1005 (FI->getOpcode() == Instruction::FSub &&
1006 TI->getOpcode() == Instruction::FAdd)) {
1007 AddOp = TI;
1008 SubOp = FI;
1009 }
1010
1011 if (AddOp) {
1012 Value *OtherAddOp = nullptr;
1013 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
1023 if (SI.getType()->isFPOrFPVectorTy()) {
1024 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1025 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1026 FastMathFlags Flags = AddOp->getFastMathFlags();
1027 Flags &= SubOp->getFastMathFlags();
1028 NegInst->setFastMathFlags(Flags);
1029 }
1030 } else {
1031 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1032 }
1033
1034 Value *NewTrueOp = OtherAddOp;
1035 Value *NewFalseOp = NegVal;
1036 if (AddOp != TI)
1037 std::swap(NewTrueOp, NewFalseOp);
1038 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
Xinliang David Licad3a992016-08-25 00:26:32 +00001039 SI.getName() + ".p", &SI);
Sanjay Patel39293132016-06-08 21:10:01 +00001040
1041 if (SI.getType()->isFPOrFPVectorTy()) {
1042 Instruction *RI =
1043 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1044
1045 FastMathFlags Flags = AddOp->getFastMathFlags();
1046 Flags &= SubOp->getFastMathFlags();
1047 RI->setFastMathFlags(Flags);
1048 return RI;
1049 } else
1050 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1051 }
1052 }
1053 return nullptr;
1054}
1055
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001056Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1057 Instruction *ExtInst;
1058 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1059 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1060 return nullptr;
1061
1062 auto ExtOpcode = ExtInst->getOpcode();
1063 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1064 return nullptr;
1065
Sanjay Patel453ceff2016-09-29 22:18:30 +00001066 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001067 Value *X = ExtInst->getOperand(0);
1068 Type *SmallType = X->getType();
Craig Topperfde47232017-07-09 07:04:03 +00001069 if (!SmallType->isIntOrIntVectorTy(1))
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001070 return nullptr;
1071
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001072 Constant *C;
1073 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1074 !match(Sel.getFalseValue(), m_Constant(C)))
1075 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001076
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001077 // If the constant is the same after truncation to the smaller type and
1078 // extension to the original type, we can narrow the select.
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001079 Value *Cond = Sel.getCondition();
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001080 Type *SelType = Sel.getType();
1081 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1082 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1083 if (ExtC == C) {
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001084 Value *TruncCVal = cast<Value>(TruncC);
1085 if (ExtInst == Sel.getFalseValue())
1086 std::swap(X, TruncCVal);
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001087
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001088 // select Cond, (ext X), C --> ext(select Cond, X, C')
1089 // select Cond, C, (ext X) --> ext(select Cond, C', X)
Craig Topperbb4069e2017-07-07 23:16:26 +00001090 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001091 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
Sanjay Patel453ceff2016-09-29 22:18:30 +00001092 }
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001093
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001094 // If one arm of the select is the extend of the condition, replace that arm
1095 // with the extension of the appropriate known bool value.
1096 if (Cond == X) {
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001097 if (ExtInst == Sel.getTrueValue()) {
1098 // select X, (sext X), C --> select X, -1, C
1099 // select X, (zext X), C --> select X, 1, C
1100 Constant *One = ConstantInt::getTrue(SmallType);
1101 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001102 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001103 } else {
1104 // select X, C, (sext X) --> select X, C, 0
1105 // select X, C, (zext X) --> select X, C, 0
1106 Constant *Zero = ConstantInt::getNullValue(SelType);
Sanjay Patel91e73a72016-11-26 15:01:59 +00001107 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001108 }
Sanjay Patel4326c4a2016-10-07 17:53:07 +00001109 }
1110
Sanjay Patel453ceff2016-09-29 22:18:30 +00001111 return nullptr;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001112}
1113
Sanjay Patelf26710d2016-09-16 22:16:18 +00001114/// Try to transform a vector select with a constant condition vector into a
1115/// shuffle for easier combining with other shuffles and insert/extract.
1116static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1117 Value *CondVal = SI.getCondition();
1118 Constant *CondC;
1119 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1120 return nullptr;
1121
1122 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1123 SmallVector<Constant *, 16> Mask;
1124 Mask.reserve(NumElts);
1125 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1126 for (unsigned i = 0; i != NumElts; ++i) {
1127 Constant *Elt = CondC->getAggregateElement(i);
1128 if (!Elt)
1129 return nullptr;
1130
1131 if (Elt->isOneValue()) {
1132 // If the select condition element is true, choose from the 1st vector.
1133 Mask.push_back(ConstantInt::get(Int32Ty, i));
1134 } else if (Elt->isNullValue()) {
1135 // If the select condition element is false, choose from the 2nd vector.
1136 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1137 } else if (isa<UndefValue>(Elt)) {
Sanjay Patel6e410182017-04-12 18:39:53 +00001138 // Undef in a select condition (choose one of the operands) does not mean
1139 // the same thing as undef in a shuffle mask (any value is acceptable), so
1140 // give up.
1141 return nullptr;
Sanjay Patelf26710d2016-09-16 22:16:18 +00001142 } else {
1143 // Bail out on a constant expression.
1144 return nullptr;
1145 }
1146 }
1147
1148 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1149 ConstantVector::get(Mask));
1150}
1151
Sanjay Patel978f8272016-10-29 15:22:04 +00001152/// Reuse bitcasted operands between a compare and select:
1153/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1154/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1155static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1156 InstCombiner::BuilderTy &Builder) {
1157 Value *Cond = Sel.getCondition();
1158 Value *TVal = Sel.getTrueValue();
1159 Value *FVal = Sel.getFalseValue();
1160
1161 CmpInst::Predicate Pred;
1162 Value *A, *B;
1163 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1164 return nullptr;
1165
1166 // The select condition is a compare instruction. If the select's true/false
1167 // values are already the same as the compare operands, there's nothing to do.
1168 if (TVal == A || TVal == B || FVal == A || FVal == B)
1169 return nullptr;
1170
1171 Value *C, *D;
1172 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1173 return nullptr;
1174
1175 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1176 Value *TSrc, *FSrc;
1177 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1178 !match(FVal, m_BitCast(m_Value(FSrc))))
1179 return nullptr;
1180
1181 // If the select true/false values are *different bitcasts* of the same source
1182 // operands, make the select operands the same as the compare operands and
1183 // cast the result. This is the canonical select form for min/max.
1184 Value *NewSel;
1185 if (TSrc == C && FSrc == D) {
1186 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1187 // bitcast (select (cmp A, B), A, B)
1188 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1189 } else if (TSrc == D && FSrc == C) {
1190 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1191 // bitcast (select (cmp A, B), B, A)
1192 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1193 } else {
1194 return nullptr;
1195 }
1196 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1197}
1198
Chris Lattner8f771cb2010-01-05 06:03:12 +00001199Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1200 Value *CondVal = SI.getCondition();
1201 Value *TrueVal = SI.getTrueValue();
1202 Value *FalseVal = SI.getFalseValue();
Sanjay Patel25600f32016-07-07 15:28:17 +00001203 Type *SelType = SI.getType();
Chris Lattner8f771cb2010-01-05 06:03:12 +00001204
Wei Mifc0e2452017-07-25 23:37:17 +00001205 // FIXME: Remove this workaround when freeze related patches are done.
1206 // For select with undef operand which feeds into an equality comparison,
1207 // don't simplify it so loop unswitch can know the equality comparison
1208 // may have an undef operand. This is a workaround for PR31652 caused by
1209 // descrepancy about branch on undef between LoopUnswitch and GVN.
1210 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1211 if (any_of(SI.users(), [&](User *U) {
1212 ICmpInst *CI = dyn_cast<ICmpInst>(U);
1213 if (CI && CI->isEquality())
1214 return true;
1215 return false;
1216 })) {
1217 return nullptr;
1218 }
1219 }
1220
Craig Toppera4205622017-06-09 03:21:29 +00001221 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1222 SQ.getWithInstruction(&SI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001223 return replaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001224
Sanjay Patelf26710d2016-09-16 22:16:18 +00001225 if (Instruction *I = canonicalizeSelectToShuffle(SI))
1226 return I;
1227
Sanjay Patel72272762017-06-27 17:53:22 +00001228 // Canonicalize a one-use integer compare with a non-canonical predicate by
1229 // inverting the predicate and swapping the select operands. This matches a
1230 // compare canonicalization for conditional branches.
1231 // TODO: Should we do the same for FP compares?
1232 CmpInst::Predicate Pred;
1233 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1234 !isCanonicalPredicate(Pred)) {
1235 // Swap true/false values and condition.
1236 CmpInst *Cond = cast<CmpInst>(CondVal);
1237 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1238 SI.setOperand(1, FalseVal);
1239 SI.setOperand(2, TrueVal);
1240 SI.swapProfMetadata();
1241 Worklist.Add(Cond);
1242 return &SI;
1243 }
1244
Craig Topperfde47232017-07-09 07:04:03 +00001245 if (SelType->isIntOrIntVectorTy(1) &&
Sanjay Patelcbaac412016-07-03 14:34:39 +00001246 TrueVal->getType() == CondVal->getType()) {
Sanjay Patelea234362016-07-06 21:01:26 +00001247 if (match(TrueVal, m_One())) {
1248 // Change: A = select B, true, C --> A = or B, C
1249 return BinaryOperator::CreateOr(CondVal, FalseVal);
1250 }
1251 if (match(TrueVal, m_Zero())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001252 // Change: A = select B, false, C --> A = and !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001253 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001254 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001255 }
Sanjay Patelea234362016-07-06 21:01:26 +00001256 if (match(FalseVal, m_Zero())) {
1257 // Change: A = select B, C, false --> A = and B, C
1258 return BinaryOperator::CreateAnd(CondVal, TrueVal);
1259 }
1260 if (match(FalseVal, m_One())) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00001261 // Change: A = select B, C, true --> A = or !B, C
Craig Topperbb4069e2017-07-07 23:16:26 +00001262 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +00001263 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001264 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001265
Sanjay Patela1a4e102016-07-03 14:08:19 +00001266 // select a, a, b -> a | b
1267 // select a, b, a -> a & b
Chris Lattner8f771cb2010-01-05 06:03:12 +00001268 if (CondVal == TrueVal)
1269 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001270 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001271 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +00001272
Sanjay Patela1a4e102016-07-03 14:08:19 +00001273 // select a, ~a, b -> (~a) & b
1274 // select a, b, ~a -> (~a) | b
Pete Cooperb33c2972011-12-15 00:56:45 +00001275 if (match(TrueVal, m_Not(m_Specific(CondVal))))
1276 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +00001277 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +00001278 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001279 }
1280
Sanjay Patel65a51c22016-07-06 22:23:01 +00001281 // Selecting between two integer or vector splat integer constants?
1282 //
1283 // Note that we don't handle a scalar select of vectors:
1284 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1285 // because that may need 3 instructions to splat the condition value:
1286 // extend, insertelement, shufflevector.
Craig Toppere79b3e72017-07-09 03:25:17 +00001287 if (SelType->isIntOrIntVectorTy() &&
1288 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
Sanjay Patel65a51c22016-07-06 22:23:01 +00001289 // select C, 1, 0 -> zext C to int
1290 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001291 return new ZExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001292
1293 // select C, -1, 0 -> sext C to int
1294 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
Sanjay Patel25600f32016-07-07 15:28:17 +00001295 return new SExtInst(CondVal, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001296
1297 // select C, 0, 1 -> zext !C to int
1298 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001299 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001300 return new ZExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001301 }
1302
1303 // select C, 0, -1 -> sext !C to int
1304 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001305 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
Sanjay Patel25600f32016-07-07 15:28:17 +00001306 return new SExtInst(NotCond, SelType);
Sanjay Patel65a51c22016-07-06 22:23:01 +00001307 }
1308 }
1309
Chris Lattner8f771cb2010-01-05 06:03:12 +00001310 // See if we are selecting two values based on a comparison of the two values.
1311 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1312 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1313 // Transform (X == Y) ? X : Y -> Y
1314 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001315 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001316 // consider X== -0, Y== +0.
1317 // It becomes safe if either operand is a nonzero constant.
1318 ConstantFP *CFPt, *CFPf;
1319 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1320 !CFPt->getValueAPF().isZero()) ||
1321 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1322 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001323 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001324 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001325 // Transform (X une Y) ? X : Y -> X
1326 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001327 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001328 // consider X== -0, Y== +0.
1329 // It becomes safe if either operand is a nonzero constant.
1330 ConstantFP *CFPt, *CFPf;
1331 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1332 !CFPt->getValueAPF().isZero()) ||
1333 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1334 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001335 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001336 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001337
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001338 // Canonicalize to use ordered comparisons by swapping the select
1339 // operands.
1340 //
1341 // e.g.
1342 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1343 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1344 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001345 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1346 Builder.setFastMathFlags(FCI->getFastMathFlags());
1347 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1348 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001349
1350 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1351 SI.getName() + ".p");
1352 }
1353
1354 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattner8f771cb2010-01-05 06:03:12 +00001355 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1356 // Transform (X == Y) ? Y : X -> X
1357 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001358 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +00001359 // consider X== -0, Y== +0.
1360 // It becomes safe if either operand is a nonzero constant.
1361 ConstantFP *CFPt, *CFPf;
1362 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1363 !CFPt->getValueAPF().isZero()) ||
1364 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1365 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001366 return replaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +00001367 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001368 // Transform (X une Y) ? Y : X -> Y
1369 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001370 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001371 // consider X== -0, Y== +0.
1372 // It becomes safe if either operand is a nonzero constant.
1373 ConstantFP *CFPt, *CFPf;
1374 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1375 !CFPt->getValueAPF().isZero()) ||
1376 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1377 !CFPf->getValueAPF().isZero()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001378 return replaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +00001379 }
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001380
1381 // Canonicalize to use ordered comparisons by swapping the select
1382 // operands.
1383 //
1384 // e.g.
1385 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1386 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1387 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
Craig Topperbb4069e2017-07-07 23:16:26 +00001388 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1389 Builder.setFastMathFlags(FCI->getFastMathFlags());
1390 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1391 FCI->getName() + ".inv");
Matt Arsenault238ff1a2014-11-24 23:15:18 +00001392
1393 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1394 SI.getName() + ".p");
1395 }
1396
Chris Lattner8f771cb2010-01-05 06:03:12 +00001397 // NOTE: if we wanted to, this is where to detect MIN/MAX
1398 }
1399 // NOTE: if we wanted to, this is where to detect ABS
1400 }
1401
1402 // See if we are selecting two values based on a comparison of the two values.
1403 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
Sanjay Patel453ceff2016-09-29 22:18:30 +00001404 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001405 return Result;
1406
Craig Topperbb4069e2017-07-07 23:16:26 +00001407 if (Instruction *Add = foldAddSubSelect(SI, Builder))
Sanjay Patel39293132016-06-08 21:10:01 +00001408 return Add;
1409
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001410 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
Sanjay Patel10a2c382016-06-08 20:09:04 +00001411 auto *TI = dyn_cast<Instruction>(TrueVal);
1412 auto *FI = dyn_cast<Instruction>(FalseVal);
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001413 if (TI && FI && TI->getOpcode() == FI->getOpcode())
Sanjay Patel453ceff2016-09-29 22:18:30 +00001414 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
Sanjay Patel216d8cf2016-06-17 16:46:50 +00001415 return IV;
Sanjay Patel10a2c382016-06-08 20:09:04 +00001416
Sanjay Patelf7b851f2016-09-30 19:49:22 +00001417 if (Instruction *I = foldSelectExtConst(SI))
1418 return I;
Nicolai Haehnle870bf172016-08-05 08:22:29 +00001419
Chris Lattner8f771cb2010-01-05 06:03:12 +00001420 // See if we can fold the select into one of our operands.
Sanjay Patel25600f32016-07-07 15:28:17 +00001421 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
Sanjay Patel453ceff2016-09-29 22:18:30 +00001422 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001423 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001424
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001425 Value *LHS, *RHS, *LHS2, *RHS2;
James Molloy2b21a7c2015-05-20 18:41:25 +00001426 Instruction::CastOps CastOp;
James Molloy134bec22015-08-11 09:12:57 +00001427 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1428 auto SPF = SPR.Flavor;
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001429
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001430 if (SelectPatternResult::isMinOrMax(SPF)) {
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001431 // Canonicalize so that
1432 // - type casts are outside select patterns.
1433 // - float clamp is transformed to min/max pattern
1434
1435 bool IsCastNeeded = LHS->getType() != SelType;
1436 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1437 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1438 if (IsCastNeeded ||
1439 (LHS->getType()->isFPOrFPVectorTy() &&
1440 ((CmpLHS != LHS && CmpLHS != RHS) ||
1441 (CmpRHS != LHS && CmpRHS != RHS)))) {
James Molloy134bec22015-08-11 09:12:57 +00001442 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1443
1444 Value *Cmp;
1445 if (CmpInst::isIntPredicate(Pred)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001446 Cmp = Builder.CreateICmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001447 } else {
Craig Topperbb4069e2017-07-07 23:16:26 +00001448 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
James Molloy134bec22015-08-11 09:12:57 +00001449 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
Craig Topperbb4069e2017-07-07 23:16:26 +00001450 Builder.setFastMathFlags(FMF);
1451 Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
James Molloy134bec22015-08-11 09:12:57 +00001452 }
1453
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00001454 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1455 if (!IsCastNeeded)
1456 return replaceInstUsesWith(SI, NewSI);
1457
1458 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1459 return replaceInstUsesWith(SI, NewCast);
James Molloy2b21a7c2015-05-20 18:41:25 +00001460 }
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001461 }
James Molloy2b21a7c2015-05-20 18:41:25 +00001462
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001463 if (SPF) {
James Molloy2b21a7c2015-05-20 18:41:25 +00001464 // MAX(MAX(a, b), a) -> MAX(a, b)
1465 // MIN(MIN(a, b), a) -> MIN(a, b)
1466 // MAX(MIN(a, b), a) -> a
1467 // MIN(MAX(a, b), a) -> a
Sanjoy Das9fe86d92015-12-05 23:44:22 +00001468 // ABS(ABS(a)) -> ABS(a)
1469 // NABS(NABS(a)) -> NABS(a)
James Molloy134bec22015-08-11 09:12:57 +00001470 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001471 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001472 SI, SPF, RHS))
1473 return R;
James Molloy134bec22015-08-11 09:12:57 +00001474 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
Sanjay Patel453ceff2016-09-29 22:18:30 +00001475 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001476 SI, SPF, LHS))
1477 return R;
1478 }
1479
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001480 // MAX(~a, ~b) -> ~MIN(a, b)
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001481 if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1482 IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1483 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001484 // For this transform to be profitable, we need to eliminate at least two
1485 // 'not' instructions if we're going to add one 'not' instruction.
1486 int NumberOfNots =
1487 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1488 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001489 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001490
Sanjay Patel4e9d6cd2016-11-09 00:13:11 +00001491 if (NumberOfNots >= 2) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001492 Value *NewLHS = Builder.CreateNot(LHS);
1493 Value *NewRHS = Builder.CreateNot(RHS);
1494 Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1495 : Builder.CreateICmpULT(NewLHS, NewRHS);
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001496 Value *NewSI =
Craig Topperbb4069e2017-07-07 23:16:26 +00001497 Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
Sanjay Patel99dc5fe2016-11-08 23:49:15 +00001498 return replaceInstUsesWith(SI, NewSI);
Sanjoy Das82ea3d42015-02-24 00:08:41 +00001499 }
1500 }
1501
Chris Lattner8f771cb2010-01-05 06:03:12 +00001502 // TODO.
1503 // ABS(-X) -> ABS(X)
Chris Lattner8f771cb2010-01-05 06:03:12 +00001504 }
1505
1506 // See if we can fold the select into a phi node if the condition is a select.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001507 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001508 // The true/false values have to be live in the PHI predecessor's blocks.
Sanjay Patel453ceff2016-09-29 22:18:30 +00001509 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1510 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
Craig Topperfb71b7d2017-04-14 19:20:12 +00001511 if (Instruction *NV = foldOpIntoPhi(SI, PN))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001512 return NV;
1513
Nick Lewyckyb074e322011-01-28 03:28:10 +00001514 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001515 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1516 // select(C, select(C, a, b), c) -> select(C, a, c)
1517 if (TrueSI->getCondition() == CondVal) {
1518 if (SI.getTrueValue() == TrueSI->getTrueValue())
1519 return nullptr;
1520 SI.setOperand(1, TrueSI->getTrueValue());
1521 return &SI;
1522 }
1523 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1524 // We choose this as normal form to enable folding on the And and shortening
1525 // paths for the values (this helps GetUnderlyingObjects() for example).
1526 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001527 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001528 SI.setOperand(0, And);
1529 SI.setOperand(1, TrueSI->getTrueValue());
1530 return &SI;
1531 }
Matthias Braun2e404592015-02-06 17:49:36 +00001532 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001533 }
1534 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
David Majnemer1bacc0a2015-03-03 22:40:36 +00001535 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1536 // select(C, a, select(C, b, c)) -> select(C, a, c)
1537 if (FalseSI->getCondition() == CondVal) {
1538 if (SI.getFalseValue() == FalseSI->getFalseValue())
1539 return nullptr;
1540 SI.setOperand(2, FalseSI->getFalseValue());
1541 return &SI;
1542 }
1543 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1544 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001545 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
David Majnemer1bacc0a2015-03-03 22:40:36 +00001546 SI.setOperand(0, Or);
1547 SI.setOperand(2, FalseSI->getFalseValue());
1548 return &SI;
1549 }
Matthias Braun2e404592015-02-06 17:49:36 +00001550 }
Nick Lewyckyb074e322011-01-28 03:28:10 +00001551 }
1552
Chris Lattner8f771cb2010-01-05 06:03:12 +00001553 if (BinaryOperator::isNot(CondVal)) {
1554 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1555 SI.setOperand(1, FalseVal);
1556 SI.setOperand(2, TrueVal);
1557 return &SI;
1558 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001559
Sanjay Patel4e463b42016-09-06 18:16:31 +00001560 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001561 unsigned VWidth = VecTy->getNumElements();
1562 APInt UndefElts(VWidth, 0);
1563 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1564 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1565 if (V != &SI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001566 return replaceInstUsesWith(SI, V);
Pete Cooperabc13af2012-07-26 23:10:24 +00001567 return &SI;
1568 }
1569 }
1570
Chad Rosiercd62bf52016-04-29 21:12:31 +00001571 // See if we can determine the result of this select based on a dominating
1572 // condition.
1573 BasicBlock *Parent = SI.getParent();
1574 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1575 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1576 if (PBI && PBI->isConditional() &&
1577 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1578 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
Chad Rosierdfd1de62017-08-01 20:18:54 +00001579 bool CondIsTrue = PBI->getSuccessor(0) == Parent;
Chad Rosiercd62bf52016-04-29 21:12:31 +00001580 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00001581 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
Chad Rosiercd62bf52016-04-29 21:12:31 +00001582 if (Implication) {
1583 Value *V = *Implication ? TrueVal : FalseVal;
1584 return replaceInstUsesWith(SI, V);
1585 }
1586 }
1587 }
1588
Sanjay Patel51783632017-01-13 17:02:42 +00001589 // If we can compute the condition, there's no need for a select.
1590 // Like the above fold, we are attempting to reduce compile-time cost by
1591 // putting this fold here with limitations rather than in InstSimplify.
1592 // The motivation for this call into value tracking is to take advantage of
1593 // the assumption cache, so make sure that is populated.
1594 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001595 KnownBits Known(1);
1596 computeKnownBits(CondVal, Known, 0, &SI);
Craig Topper73ba1c82017-06-07 07:40:37 +00001597 if (Known.One.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001598 return replaceInstUsesWith(SI, TrueVal);
Craig Topper73ba1c82017-06-07 07:40:37 +00001599 if (Known.Zero.isOneValue())
Sanjay Patel51783632017-01-13 17:02:42 +00001600 return replaceInstUsesWith(SI, FalseVal);
1601 }
1602
Craig Topperbb4069e2017-07-07 23:16:26 +00001603 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
Sanjay Patel978f8272016-10-29 15:22:04 +00001604 return BitCastSel;
1605
Craig Topperf40110f2014-04-25 05:29:35 +00001606 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001607}