1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
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 //
10 // This file implements the visitSelect function.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/PatternMatch.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21
22 #define DEBUG_TYPE "instcombine"
23
24 static SelectPatternFlavor
getInverseMinMaxSelectPattern(SelectPatternFlavor SPF)25 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
26 switch (SPF) {
27 default:
28 llvm_unreachable("unhandled!");
29
30 case SPF_SMIN:
31 return SPF_SMAX;
32 case SPF_UMIN:
33 return SPF_UMAX;
34 case SPF_SMAX:
35 return SPF_SMIN;
36 case SPF_UMAX:
37 return SPF_UMIN;
38 }
39 }
40
getCmpPredicateForMinMax(SelectPatternFlavor SPF,bool Ordered=false)41 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
42 bool Ordered=false) {
43 switch (SPF) {
44 default:
45 llvm_unreachable("unhandled!");
46
47 case SPF_SMIN:
48 return ICmpInst::ICMP_SLT;
49 case SPF_UMIN:
50 return ICmpInst::ICMP_ULT;
51 case SPF_SMAX:
52 return ICmpInst::ICMP_SGT;
53 case SPF_UMAX:
54 return ICmpInst::ICMP_UGT;
55 case SPF_FMINNUM:
56 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
57 case SPF_FMAXNUM:
58 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
59 }
60 }
61
generateMinMaxSelectPattern(InstCombiner::BuilderTy * Builder,SelectPatternFlavor SPF,Value * A,Value * B)62 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
63 SelectPatternFlavor SPF, Value *A,
64 Value *B) {
65 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
66 assert(CmpInst::isIntPredicate(Pred));
67 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
68 }
69
70 /// We want to turn code that looks like this:
71 /// %C = or %A, %B
72 /// %D = select %cond, %C, %A
73 /// into:
74 /// %C = select %cond, %B, 0
75 /// %D = or %A, %C
76 ///
77 /// Assuming that the specified instruction is an operand to the select, return
78 /// a bitmask indicating which operands of this instruction are foldable if they
79 /// equal the other incoming value of the select.
80 ///
GetSelectFoldableOperands(Instruction * I)81 static unsigned GetSelectFoldableOperands(Instruction *I) {
82 switch (I->getOpcode()) {
83 case Instruction::Add:
84 case Instruction::Mul:
85 case Instruction::And:
86 case Instruction::Or:
87 case Instruction::Xor:
88 return 3; // Can fold through either operand.
89 case Instruction::Sub: // Can only fold on the amount subtracted.
90 case Instruction::Shl: // Can only fold on the shift amount.
91 case Instruction::LShr:
92 case Instruction::AShr:
93 return 1;
94 default:
95 return 0; // Cannot fold
96 }
97 }
98
99 /// For the same transformation as the previous function, return the identity
100 /// constant that goes into the select.
GetSelectFoldableConstant(Instruction * I)101 static Constant *GetSelectFoldableConstant(Instruction *I) {
102 switch (I->getOpcode()) {
103 default: llvm_unreachable("This cannot happen!");
104 case Instruction::Add:
105 case Instruction::Sub:
106 case Instruction::Or:
107 case Instruction::Xor:
108 case Instruction::Shl:
109 case Instruction::LShr:
110 case Instruction::AShr:
111 return Constant::getNullValue(I->getType());
112 case Instruction::And:
113 return Constant::getAllOnesValue(I->getType());
114 case Instruction::Mul:
115 return ConstantInt::get(I->getType(), 1);
116 }
117 }
118
119 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
FoldSelectOpOp(SelectInst & SI,Instruction * TI,Instruction * FI)120 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
121 Instruction *FI) {
122 // If this is a cast from the same type, merge.
123 if (TI->getNumOperands() == 1 && TI->isCast()) {
124 Type *FIOpndTy = FI->getOperand(0)->getType();
125 if (TI->getOperand(0)->getType() != FIOpndTy)
126 return nullptr;
127
128 // The select condition may be a vector. We may only change the operand
129 // type if the vector width remains the same (and matches the condition).
130 Type *CondTy = SI.getCondition()->getType();
131 if (CondTy->isVectorTy()) {
132 if (!FIOpndTy->isVectorTy())
133 return nullptr;
134 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
135 return nullptr;
136
137 // TODO: If the backend knew how to deal with casts better, we could
138 // remove this limitation. For now, there's too much potential to create
139 // worse codegen by promoting the select ahead of size-altering casts
140 // (PR28160).
141 //
142 // Note that ValueTracking's matchSelectPattern() looks through casts
143 // without checking 'hasOneUse' when it matches min/max patterns, so this
144 // transform may end up happening anyway.
145 if (TI->getOpcode() != Instruction::BitCast &&
146 (!TI->hasOneUse() || !FI->hasOneUse()))
147 return nullptr;
148
149 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
150 // TODO: The one-use restrictions for a scalar select could be eased if
151 // the fold of a select in visitLoadInst() was enhanced to match a pattern
152 // that includes a cast.
153 return nullptr;
154 }
155
156 // Fold this by inserting a select from the input values.
157 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
158 FI->getOperand(0), SI.getName()+".v");
159 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
160 TI->getType());
161 }
162
163 // TODO: This function ends awkwardly in unreachable - fix to be more normal.
164
165 // Only handle binary operators with one-use here. As with the cast case
166 // above, it may be possible to relax the one-use constraint, but that needs
167 // be examined carefully since it may not reduce the total number of
168 // instructions.
169 if (!isa<BinaryOperator>(TI) || !TI->hasOneUse() || !FI->hasOneUse())
170 return nullptr;
171
172 // Figure out if the operations have any operands in common.
173 Value *MatchOp, *OtherOpT, *OtherOpF;
174 bool MatchIsOpZero;
175 if (TI->getOperand(0) == FI->getOperand(0)) {
176 MatchOp = TI->getOperand(0);
177 OtherOpT = TI->getOperand(1);
178 OtherOpF = FI->getOperand(1);
179 MatchIsOpZero = true;
180 } else if (TI->getOperand(1) == FI->getOperand(1)) {
181 MatchOp = TI->getOperand(1);
182 OtherOpT = TI->getOperand(0);
183 OtherOpF = FI->getOperand(0);
184 MatchIsOpZero = false;
185 } else if (!TI->isCommutative()) {
186 return nullptr;
187 } else if (TI->getOperand(0) == FI->getOperand(1)) {
188 MatchOp = TI->getOperand(0);
189 OtherOpT = TI->getOperand(1);
190 OtherOpF = FI->getOperand(0);
191 MatchIsOpZero = true;
192 } else if (TI->getOperand(1) == FI->getOperand(0)) {
193 MatchOp = TI->getOperand(1);
194 OtherOpT = TI->getOperand(0);
195 OtherOpF = FI->getOperand(1);
196 MatchIsOpZero = true;
197 } else {
198 return nullptr;
199 }
200
201 // If we reach here, they do have operations in common.
202 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
203 OtherOpF, SI.getName()+".v");
204
205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
206 if (MatchIsOpZero)
207 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
208 else
209 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
210 }
211 llvm_unreachable("Shouldn't get here");
212 }
213
isSelect01(Constant * C1,Constant * C2)214 static bool isSelect01(Constant *C1, Constant *C2) {
215 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
216 if (!C1I)
217 return false;
218 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
219 if (!C2I)
220 return false;
221 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
222 return false;
223 return C1I->isOne() || C1I->isAllOnesValue() ||
224 C2I->isOne() || C2I->isAllOnesValue();
225 }
226
227 /// Try to fold the select into one of the operands to allow further
228 /// optimization.
FoldSelectIntoOp(SelectInst & SI,Value * TrueVal,Value * FalseVal)229 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
230 Value *FalseVal) {
231 // See the comment above GetSelectFoldableOperands for a description of the
232 // transformation we are doing here.
233 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
234 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
235 !isa<Constant>(FalseVal)) {
236 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
237 unsigned OpToFold = 0;
238 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
239 OpToFold = 1;
240 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
241 OpToFold = 2;
242 }
243
244 if (OpToFold) {
245 Constant *C = GetSelectFoldableConstant(TVI);
246 Value *OOp = TVI->getOperand(2-OpToFold);
247 // Avoid creating select between 2 constants unless it's selecting
248 // between 0, 1 and -1.
249 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
250 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
251 NewSel->takeName(TVI);
252 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
253 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
254 FalseVal, NewSel);
255 BO->copyIRFlags(TVI_BO);
256 return BO;
257 }
258 }
259 }
260 }
261 }
262
263 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
264 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
265 !isa<Constant>(TrueVal)) {
266 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
267 unsigned OpToFold = 0;
268 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
269 OpToFold = 1;
270 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
271 OpToFold = 2;
272 }
273
274 if (OpToFold) {
275 Constant *C = GetSelectFoldableConstant(FVI);
276 Value *OOp = FVI->getOperand(2-OpToFold);
277 // Avoid creating select between 2 constants unless it's selecting
278 // between 0, 1 and -1.
279 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
280 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
281 NewSel->takeName(FVI);
282 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
283 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
284 TrueVal, NewSel);
285 BO->copyIRFlags(FVI_BO);
286 return BO;
287 }
288 }
289 }
290 }
291 }
292
293 return nullptr;
294 }
295
296 /// We want to turn:
297 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
298 /// into:
299 /// (or (shl (and X, C1), C3), y)
300 /// iff:
301 /// C1 and C2 are both powers of 2
302 /// where:
303 /// C3 = Log(C2) - Log(C1)
304 ///
305 /// This transform handles cases where:
306 /// 1. The icmp predicate is inverted
307 /// 2. The select operands are reversed
308 /// 3. The magnitude of C2 and C1 are flipped
foldSelectICmpAndOr(const SelectInst & SI,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy * Builder)309 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
310 Value *FalseVal,
311 InstCombiner::BuilderTy *Builder) {
312 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
313 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
314 return nullptr;
315
316 Value *CmpLHS = IC->getOperand(0);
317 Value *CmpRHS = IC->getOperand(1);
318
319 if (!match(CmpRHS, m_Zero()))
320 return nullptr;
321
322 Value *X;
323 const APInt *C1;
324 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
325 return nullptr;
326
327 const APInt *C2;
328 bool OrOnTrueVal = false;
329 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
330 if (!OrOnFalseVal)
331 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
332
333 if (!OrOnFalseVal && !OrOnTrueVal)
334 return nullptr;
335
336 Value *V = CmpLHS;
337 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
338
339 unsigned C1Log = C1->logBase2();
340 unsigned C2Log = C2->logBase2();
341 if (C2Log > C1Log) {
342 V = Builder->CreateZExtOrTrunc(V, Y->getType());
343 V = Builder->CreateShl(V, C2Log - C1Log);
344 } else if (C1Log > C2Log) {
345 V = Builder->CreateLShr(V, C1Log - C2Log);
346 V = Builder->CreateZExtOrTrunc(V, Y->getType());
347 } else
348 V = Builder->CreateZExtOrTrunc(V, Y->getType());
349
350 ICmpInst::Predicate Pred = IC->getPredicate();
351 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
352 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
353 V = Builder->CreateXor(V, *C2);
354
355 return Builder->CreateOr(V, Y);
356 }
357
358 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
359 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
360 ///
361 /// For example, we can fold the following code sequence:
362 /// \code
363 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
364 /// %1 = icmp ne i32 %x, 0
365 /// %2 = select i1 %1, i32 %0, i32 32
366 /// \code
367 ///
368 /// into:
369 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
foldSelectCttzCtlz(ICmpInst * ICI,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy * Builder)370 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
371 InstCombiner::BuilderTy *Builder) {
372 ICmpInst::Predicate Pred = ICI->getPredicate();
373 Value *CmpLHS = ICI->getOperand(0);
374 Value *CmpRHS = ICI->getOperand(1);
375
376 // Check if the condition value compares a value for equality against zero.
377 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
378 return nullptr;
379
380 Value *Count = FalseVal;
381 Value *ValueOnZero = TrueVal;
382 if (Pred == ICmpInst::ICMP_NE)
383 std::swap(Count, ValueOnZero);
384
385 // Skip zero extend/truncate.
386 Value *V = nullptr;
387 if (match(Count, m_ZExt(m_Value(V))) ||
388 match(Count, m_Trunc(m_Value(V))))
389 Count = V;
390
391 // Check if the value propagated on zero is a constant number equal to the
392 // sizeof in bits of 'Count'.
393 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
394 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
395 return nullptr;
396
397 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
398 // input to the cttz/ctlz is used as LHS for the compare instruction.
399 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
400 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
401 IntrinsicInst *II = cast<IntrinsicInst>(Count);
402 IRBuilder<> Builder(II);
403 // Explicitly clear the 'undef_on_zero' flag.
404 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
405 Type *Ty = NewI->getArgOperand(1)->getType();
406 NewI->setArgOperand(1, Constant::getNullValue(Ty));
407 Builder.Insert(NewI);
408 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
409 }
410
411 return nullptr;
412 }
413
414 /// Visit a SelectInst that has an ICmpInst as its first operand.
visitSelectInstWithICmp(SelectInst & SI,ICmpInst * ICI)415 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
416 ICmpInst *ICI) {
417 bool Changed = false;
418 ICmpInst::Predicate Pred = ICI->getPredicate();
419 Value *CmpLHS = ICI->getOperand(0);
420 Value *CmpRHS = ICI->getOperand(1);
421 Value *TrueVal = SI.getTrueValue();
422 Value *FalseVal = SI.getFalseValue();
423
424 // Check cases where the comparison is with a constant that
425 // can be adjusted to fit the min/max idiom. We may move or edit ICI
426 // here, so make sure the select is the only user.
427 if (ICI->hasOneUse())
428 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
429 switch (Pred) {
430 default: break;
431 case ICmpInst::ICMP_ULT:
432 case ICmpInst::ICMP_SLT:
433 case ICmpInst::ICMP_UGT:
434 case ICmpInst::ICMP_SGT: {
435 // These transformations only work for selects over integers.
436 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
437 if (!SelectTy)
438 break;
439
440 Constant *AdjustedRHS;
441 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
442 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
443 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
444 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
445
446 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
447 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
448 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
449 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
450 ; // Nothing to do here. Values match without any sign/zero extension.
451
452 // Types do not match. Instead of calculating this with mixed types
453 // promote all to the larger type. This enables scalar evolution to
454 // analyze this expression.
455 else if (CmpRHS->getType()->getScalarSizeInBits()
456 < SelectTy->getBitWidth()) {
457 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
458
459 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
460 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
461 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
462 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
463 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
464 sextRHS == FalseVal) {
465 CmpLHS = TrueVal;
466 AdjustedRHS = sextRHS;
467 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
468 sextRHS == TrueVal) {
469 CmpLHS = FalseVal;
470 AdjustedRHS = sextRHS;
471 } else if (ICI->isUnsigned()) {
472 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
473 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
474 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
475 // zext + signed compare cannot be changed:
476 // 0xff <s 0x00, but 0x00ff >s 0x0000
477 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
478 zextRHS == FalseVal) {
479 CmpLHS = TrueVal;
480 AdjustedRHS = zextRHS;
481 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
482 zextRHS == TrueVal) {
483 CmpLHS = FalseVal;
484 AdjustedRHS = zextRHS;
485 } else
486 break;
487 } else
488 break;
489 } else
490 break;
491
492 Pred = ICmpInst::getSwappedPredicate(Pred);
493 CmpRHS = AdjustedRHS;
494 std::swap(FalseVal, TrueVal);
495 ICI->setPredicate(Pred);
496 ICI->setOperand(0, CmpLHS);
497 ICI->setOperand(1, CmpRHS);
498 SI.setOperand(1, TrueVal);
499 SI.setOperand(2, FalseVal);
500
501 // Move ICI instruction right before the select instruction. Otherwise
502 // the sext/zext value may be defined after the ICI instruction uses it.
503 ICI->moveBefore(&SI);
504
505 Changed = true;
506 break;
507 }
508 }
509 }
510
511 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
512 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
513 // FIXME: Type and constness constraints could be lifted, but we have to
514 // watch code size carefully. We should consider xor instead of
515 // sub/add when we decide to do that.
516 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
517 if (TrueVal->getType() == Ty) {
518 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
519 ConstantInt *C1 = nullptr, *C2 = nullptr;
520 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
521 C1 = dyn_cast<ConstantInt>(TrueVal);
522 C2 = dyn_cast<ConstantInt>(FalseVal);
523 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
524 C1 = dyn_cast<ConstantInt>(FalseVal);
525 C2 = dyn_cast<ConstantInt>(TrueVal);
526 }
527 if (C1 && C2) {
528 // This shift results in either -1 or 0.
529 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
530
531 // Check if we can express the operation with a single or.
532 if (C2->isAllOnesValue())
533 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
534
535 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
536 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
537 }
538 }
539 }
540 }
541
542 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
543
544 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
545 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
546 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
547 SI.setOperand(1, CmpRHS);
548 Changed = true;
549 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
550 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
551 SI.setOperand(2, CmpRHS);
552 Changed = true;
553 }
554 }
555
556 {
557 unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType());
558 APInt MinSignedValue = APInt::getSignBit(BitWidth);
559 Value *X;
560 const APInt *Y, *C;
561 bool TrueWhenUnset;
562 bool IsBitTest = false;
563 if (ICmpInst::isEquality(Pred) &&
564 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
565 match(CmpRHS, m_Zero())) {
566 IsBitTest = true;
567 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
568 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
569 X = CmpLHS;
570 Y = &MinSignedValue;
571 IsBitTest = true;
572 TrueWhenUnset = false;
573 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
574 X = CmpLHS;
575 Y = &MinSignedValue;
576 IsBitTest = true;
577 TrueWhenUnset = true;
578 }
579 if (IsBitTest) {
580 Value *V = nullptr;
581 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
582 if (TrueWhenUnset && TrueVal == X &&
583 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
584 V = Builder->CreateAnd(X, ~(*Y));
585 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
586 else if (!TrueWhenUnset && FalseVal == X &&
587 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
588 V = Builder->CreateAnd(X, ~(*Y));
589 // (X & Y) == 0 ? X ^ Y : X --> X | Y
590 else if (TrueWhenUnset && FalseVal == X &&
591 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
592 V = Builder->CreateOr(X, *Y);
593 // (X & Y) != 0 ? X : X ^ Y --> X | Y
594 else if (!TrueWhenUnset && TrueVal == X &&
595 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
596 V = Builder->CreateOr(X, *Y);
597
598 if (V)
599 return replaceInstUsesWith(SI, V);
600 }
601 }
602
603 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
604 return replaceInstUsesWith(SI, V);
605
606 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
607 return replaceInstUsesWith(SI, V);
608
609 return Changed ? &SI : nullptr;
610 }
611
612
613 /// SI is a select whose condition is a PHI node (but the two may be in
614 /// different blocks). See if the true/false values (V) are live in all of the
615 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
616 ///
617 /// X = phi [ C1, BB1], [C2, BB2]
618 /// Y = add
619 /// Z = select X, Y, 0
620 ///
621 /// because Y is not live in BB1/BB2.
622 ///
CanSelectOperandBeMappingIntoPredBlock(const Value * V,const SelectInst & SI)623 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
624 const SelectInst &SI) {
625 // If the value is a non-instruction value like a constant or argument, it
626 // can always be mapped.
627 const Instruction *I = dyn_cast<Instruction>(V);
628 if (!I) return true;
629
630 // If V is a PHI node defined in the same block as the condition PHI, we can
631 // map the arguments.
632 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
633
634 if (const PHINode *VP = dyn_cast<PHINode>(I))
635 if (VP->getParent() == CondPHI->getParent())
636 return true;
637
638 // Otherwise, if the PHI and select are defined in the same block and if V is
639 // defined in a different block, then we can transform it.
640 if (SI.getParent() == CondPHI->getParent() &&
641 I->getParent() != CondPHI->getParent())
642 return true;
643
644 // Otherwise we have a 'hard' case and we can't tell without doing more
645 // detailed dominator based analysis, punt.
646 return false;
647 }
648
649 /// We have an SPF (e.g. a min or max) of an SPF of the form:
650 /// SPF2(SPF1(A, B), C)
FoldSPFofSPF(Instruction * Inner,SelectPatternFlavor SPF1,Value * A,Value * B,Instruction & Outer,SelectPatternFlavor SPF2,Value * C)651 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
652 SelectPatternFlavor SPF1,
653 Value *A, Value *B,
654 Instruction &Outer,
655 SelectPatternFlavor SPF2, Value *C) {
656 if (Outer.getType() != Inner->getType())
657 return nullptr;
658
659 if (C == A || C == B) {
660 // MAX(MAX(A, B), B) -> MAX(A, B)
661 // MIN(MIN(a, b), a) -> MIN(a, b)
662 if (SPF1 == SPF2)
663 return replaceInstUsesWith(Outer, Inner);
664
665 // MAX(MIN(a, b), a) -> a
666 // MIN(MAX(a, b), a) -> a
667 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
668 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
669 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
670 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
671 return replaceInstUsesWith(Outer, C);
672 }
673
674 if (SPF1 == SPF2) {
675 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
676 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
677 const APInt &ACB = CB->getValue();
678 const APInt &ACC = CC->getValue();
679
680 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
681 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
682 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
683 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
684 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
685 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
686 return replaceInstUsesWith(Outer, Inner);
687
688 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
689 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
690 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
691 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
692 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
693 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
694 Outer.replaceUsesOfWith(Inner, A);
695 return &Outer;
696 }
697 }
698 }
699 }
700
701 // ABS(ABS(X)) -> ABS(X)
702 // NABS(NABS(X)) -> NABS(X)
703 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
704 return replaceInstUsesWith(Outer, Inner);
705 }
706
707 // ABS(NABS(X)) -> ABS(X)
708 // NABS(ABS(X)) -> NABS(X)
709 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
710 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
711 SelectInst *SI = cast<SelectInst>(Inner);
712 Value *NewSI = Builder->CreateSelect(
713 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
714 return replaceInstUsesWith(Outer, NewSI);
715 }
716
717 auto IsFreeOrProfitableToInvert =
718 [&](Value *V, Value *&NotV, bool &ElidesXor) {
719 if (match(V, m_Not(m_Value(NotV)))) {
720 // If V has at most 2 uses then we can get rid of the xor operation
721 // entirely.
722 ElidesXor |= !V->hasNUsesOrMore(3);
723 return true;
724 }
725
726 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
727 NotV = nullptr;
728 return true;
729 }
730
731 return false;
732 };
733
734 Value *NotA, *NotB, *NotC;
735 bool ElidesXor = false;
736
737 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
738 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
739 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
740 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
741 //
742 // This transform is performance neutral if we can elide at least one xor from
743 // the set of three operands, since we'll be tacking on an xor at the very
744 // end.
745 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
746 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
747 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
748 if (!NotA)
749 NotA = Builder->CreateNot(A);
750 if (!NotB)
751 NotB = Builder->CreateNot(B);
752 if (!NotC)
753 NotC = Builder->CreateNot(C);
754
755 Value *NewInner = generateMinMaxSelectPattern(
756 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
757 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
758 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
759 return replaceInstUsesWith(Outer, NewOuter);
760 }
761
762 return nullptr;
763 }
764
765 /// If one of the constants is zero (we know they can't both be) and we have an
766 /// icmp instruction with zero, and we have an 'and' with the non-constant value
767 /// and a power of two we can turn the select into a shift on the result of the
768 /// 'and'.
foldSelectICmpAnd(const SelectInst & SI,ConstantInt * TrueVal,ConstantInt * FalseVal,InstCombiner::BuilderTy * Builder)769 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
770 ConstantInt *FalseVal,
771 InstCombiner::BuilderTy *Builder) {
772 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
773 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
774 return nullptr;
775
776 if (!match(IC->getOperand(1), m_Zero()))
777 return nullptr;
778
779 ConstantInt *AndRHS;
780 Value *LHS = IC->getOperand(0);
781 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
782 return nullptr;
783
784 // If both select arms are non-zero see if we have a select of the form
785 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
786 // for 'x ? 2^n : 0' and fix the thing up at the end.
787 ConstantInt *Offset = nullptr;
788 if (!TrueVal->isZero() && !FalseVal->isZero()) {
789 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
790 Offset = FalseVal;
791 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
792 Offset = TrueVal;
793 else
794 return nullptr;
795
796 // Adjust TrueVal and FalseVal to the offset.
797 TrueVal = ConstantInt::get(Builder->getContext(),
798 TrueVal->getValue() - Offset->getValue());
799 FalseVal = ConstantInt::get(Builder->getContext(),
800 FalseVal->getValue() - Offset->getValue());
801 }
802
803 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
804 if (!AndRHS->getValue().isPowerOf2() ||
805 (!TrueVal->getValue().isPowerOf2() &&
806 !FalseVal->getValue().isPowerOf2()))
807 return nullptr;
808
809 // Determine which shift is needed to transform result of the 'and' into the
810 // desired result.
811 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
812 unsigned ValZeros = ValC->getValue().logBase2();
813 unsigned AndZeros = AndRHS->getValue().logBase2();
814
815 // If types don't match we can still convert the select by introducing a zext
816 // or a trunc of the 'and'. The trunc case requires that all of the truncated
817 // bits are zero, we can figure that out by looking at the 'and' mask.
818 if (AndZeros >= ValC->getBitWidth())
819 return nullptr;
820
821 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
822 if (ValZeros > AndZeros)
823 V = Builder->CreateShl(V, ValZeros - AndZeros);
824 else if (ValZeros < AndZeros)
825 V = Builder->CreateLShr(V, AndZeros - ValZeros);
826
827 // Okay, now we know that everything is set up, we just don't know whether we
828 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
829 bool ShouldNotVal = !TrueVal->isZero();
830 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
831 if (ShouldNotVal)
832 V = Builder->CreateXor(V, ValC);
833
834 // Apply an offset if needed.
835 if (Offset)
836 V = Builder->CreateAdd(V, Offset);
837 return V;
838 }
839
840 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
841 /// This is even legal for FP.
foldAddSubSelect(SelectInst & SI,InstCombiner::BuilderTy & Builder)842 static Instruction *foldAddSubSelect(SelectInst &SI,
843 InstCombiner::BuilderTy &Builder) {
844 Value *CondVal = SI.getCondition();
845 Value *TrueVal = SI.getTrueValue();
846 Value *FalseVal = SI.getFalseValue();
847 auto *TI = dyn_cast<Instruction>(TrueVal);
848 auto *FI = dyn_cast<Instruction>(FalseVal);
849 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
850 return nullptr;
851
852 Instruction *AddOp = nullptr, *SubOp = nullptr;
853 if ((TI->getOpcode() == Instruction::Sub &&
854 FI->getOpcode() == Instruction::Add) ||
855 (TI->getOpcode() == Instruction::FSub &&
856 FI->getOpcode() == Instruction::FAdd)) {
857 AddOp = FI;
858 SubOp = TI;
859 } else if ((FI->getOpcode() == Instruction::Sub &&
860 TI->getOpcode() == Instruction::Add) ||
861 (FI->getOpcode() == Instruction::FSub &&
862 TI->getOpcode() == Instruction::FAdd)) {
863 AddOp = TI;
864 SubOp = FI;
865 }
866
867 if (AddOp) {
868 Value *OtherAddOp = nullptr;
869 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
870 OtherAddOp = AddOp->getOperand(1);
871 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
872 OtherAddOp = AddOp->getOperand(0);
873 }
874
875 if (OtherAddOp) {
876 // So at this point we know we have (Y -> OtherAddOp):
877 // select C, (add X, Y), (sub X, Z)
878 Value *NegVal; // Compute -Z
879 if (SI.getType()->isFPOrFPVectorTy()) {
880 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
881 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
882 FastMathFlags Flags = AddOp->getFastMathFlags();
883 Flags &= SubOp->getFastMathFlags();
884 NegInst->setFastMathFlags(Flags);
885 }
886 } else {
887 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
888 }
889
890 Value *NewTrueOp = OtherAddOp;
891 Value *NewFalseOp = NegVal;
892 if (AddOp != TI)
893 std::swap(NewTrueOp, NewFalseOp);
894 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
895 SI.getName() + ".p");
896
897 if (SI.getType()->isFPOrFPVectorTy()) {
898 Instruction *RI =
899 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
900
901 FastMathFlags Flags = AddOp->getFastMathFlags();
902 Flags &= SubOp->getFastMathFlags();
903 RI->setFastMathFlags(Flags);
904 return RI;
905 } else
906 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
907 }
908 }
909 return nullptr;
910 }
911
visitSelectInst(SelectInst & SI)912 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
913 Value *CondVal = SI.getCondition();
914 Value *TrueVal = SI.getTrueValue();
915 Value *FalseVal = SI.getFalseValue();
916 Type *SelType = SI.getType();
917
918 if (Value *V =
919 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
920 return replaceInstUsesWith(SI, V);
921
922 if (SelType->getScalarType()->isIntegerTy(1) &&
923 TrueVal->getType() == CondVal->getType()) {
924 if (match(TrueVal, m_One())) {
925 // Change: A = select B, true, C --> A = or B, C
926 return BinaryOperator::CreateOr(CondVal, FalseVal);
927 }
928 if (match(TrueVal, m_Zero())) {
929 // Change: A = select B, false, C --> A = and !B, C
930 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
931 return BinaryOperator::CreateAnd(NotCond, FalseVal);
932 }
933 if (match(FalseVal, m_Zero())) {
934 // Change: A = select B, C, false --> A = and B, C
935 return BinaryOperator::CreateAnd(CondVal, TrueVal);
936 }
937 if (match(FalseVal, m_One())) {
938 // Change: A = select B, C, true --> A = or !B, C
939 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
940 return BinaryOperator::CreateOr(NotCond, TrueVal);
941 }
942
943 // select a, a, b -> a | b
944 // select a, b, a -> a & b
945 if (CondVal == TrueVal)
946 return BinaryOperator::CreateOr(CondVal, FalseVal);
947 if (CondVal == FalseVal)
948 return BinaryOperator::CreateAnd(CondVal, TrueVal);
949
950 // select a, ~a, b -> (~a) & b
951 // select a, b, ~a -> (~a) | b
952 if (match(TrueVal, m_Not(m_Specific(CondVal))))
953 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
954 if (match(FalseVal, m_Not(m_Specific(CondVal))))
955 return BinaryOperator::CreateOr(TrueVal, FalseVal);
956 }
957
958 // Selecting between two integer or vector splat integer constants?
959 //
960 // Note that we don't handle a scalar select of vectors:
961 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
962 // because that may need 3 instructions to splat the condition value:
963 // extend, insertelement, shufflevector.
964 if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
965 // select C, 1, 0 -> zext C to int
966 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
967 return new ZExtInst(CondVal, SelType);
968
969 // select C, -1, 0 -> sext C to int
970 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
971 return new SExtInst(CondVal, SelType);
972
973 // select C, 0, 1 -> zext !C to int
974 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
975 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
976 return new ZExtInst(NotCond, SelType);
977 }
978
979 // select C, 0, -1 -> sext !C to int
980 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
981 Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
982 return new SExtInst(NotCond, SelType);
983 }
984 }
985
986 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
987 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
988 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
989 return replaceInstUsesWith(SI, V);
990
991 // See if we are selecting two values based on a comparison of the two values.
992 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
993 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
994 // Transform (X == Y) ? X : Y -> Y
995 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
996 // This is not safe in general for floating point:
997 // consider X== -0, Y== +0.
998 // It becomes safe if either operand is a nonzero constant.
999 ConstantFP *CFPt, *CFPf;
1000 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1001 !CFPt->getValueAPF().isZero()) ||
1002 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1003 !CFPf->getValueAPF().isZero()))
1004 return replaceInstUsesWith(SI, FalseVal);
1005 }
1006 // Transform (X une Y) ? X : Y -> X
1007 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1008 // This is not safe in general for floating point:
1009 // consider X== -0, Y== +0.
1010 // It becomes safe if either operand is a nonzero constant.
1011 ConstantFP *CFPt, *CFPf;
1012 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1013 !CFPt->getValueAPF().isZero()) ||
1014 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1015 !CFPf->getValueAPF().isZero()))
1016 return replaceInstUsesWith(SI, TrueVal);
1017 }
1018
1019 // Canonicalize to use ordered comparisons by swapping the select
1020 // operands.
1021 //
1022 // e.g.
1023 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1024 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1025 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1026 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1027 Builder->setFastMathFlags(FCI->getFastMathFlags());
1028 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1029 FCI->getName() + ".inv");
1030
1031 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1032 SI.getName() + ".p");
1033 }
1034
1035 // NOTE: if we wanted to, this is where to detect MIN/MAX
1036 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1037 // Transform (X == Y) ? Y : X -> X
1038 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1039 // This is not safe in general for floating point:
1040 // consider X== -0, Y== +0.
1041 // It becomes safe if either operand is a nonzero constant.
1042 ConstantFP *CFPt, *CFPf;
1043 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1044 !CFPt->getValueAPF().isZero()) ||
1045 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1046 !CFPf->getValueAPF().isZero()))
1047 return replaceInstUsesWith(SI, FalseVal);
1048 }
1049 // Transform (X une Y) ? Y : X -> Y
1050 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1051 // This is not safe in general for floating point:
1052 // consider X== -0, Y== +0.
1053 // It becomes safe if either operand is a nonzero constant.
1054 ConstantFP *CFPt, *CFPf;
1055 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1056 !CFPt->getValueAPF().isZero()) ||
1057 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1058 !CFPf->getValueAPF().isZero()))
1059 return replaceInstUsesWith(SI, TrueVal);
1060 }
1061
1062 // Canonicalize to use ordered comparisons by swapping the select
1063 // operands.
1064 //
1065 // e.g.
1066 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1067 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1068 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1069 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1070 Builder->setFastMathFlags(FCI->getFastMathFlags());
1071 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1072 FCI->getName() + ".inv");
1073
1074 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1075 SI.getName() + ".p");
1076 }
1077
1078 // NOTE: if we wanted to, this is where to detect MIN/MAX
1079 }
1080 // NOTE: if we wanted to, this is where to detect ABS
1081 }
1082
1083 // See if we are selecting two values based on a comparison of the two values.
1084 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1085 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1086 return Result;
1087
1088 if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1089 return Add;
1090
1091 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1092 auto *TI = dyn_cast<Instruction>(TrueVal);
1093 auto *FI = dyn_cast<Instruction>(FalseVal);
1094 if (TI && FI && TI->getOpcode() == FI->getOpcode())
1095 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1096 return IV;
1097
1098 // See if we can fold the select into one of our operands.
1099 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1100 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1101 return FoldI;
1102
1103 Value *LHS, *RHS, *LHS2, *RHS2;
1104 Instruction::CastOps CastOp;
1105 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1106 auto SPF = SPR.Flavor;
1107
1108 if (SelectPatternResult::isMinOrMax(SPF)) {
1109 // Canonicalize so that type casts are outside select patterns.
1110 if (LHS->getType()->getPrimitiveSizeInBits() !=
1111 SelType->getPrimitiveSizeInBits()) {
1112 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1113
1114 Value *Cmp;
1115 if (CmpInst::isIntPredicate(Pred)) {
1116 Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1117 } else {
1118 IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1119 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1120 Builder->setFastMathFlags(FMF);
1121 Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1122 }
1123
1124 Value *NewSI = Builder->CreateCast(CastOp,
1125 Builder->CreateSelect(Cmp, LHS, RHS),
1126 SelType);
1127 return replaceInstUsesWith(SI, NewSI);
1128 }
1129 }
1130
1131 if (SPF) {
1132 // MAX(MAX(a, b), a) -> MAX(a, b)
1133 // MIN(MIN(a, b), a) -> MIN(a, b)
1134 // MAX(MIN(a, b), a) -> a
1135 // MIN(MAX(a, b), a) -> a
1136 // ABS(ABS(a)) -> ABS(a)
1137 // NABS(NABS(a)) -> NABS(a)
1138 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1139 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1140 SI, SPF, RHS))
1141 return R;
1142 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1143 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1144 SI, SPF, LHS))
1145 return R;
1146 }
1147
1148 // MAX(~a, ~b) -> ~MIN(a, b)
1149 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1150 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1151 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1152
1153 // This transform adds a xor operation and that extra cost needs to be
1154 // justified. We look for simplifications that will result from
1155 // applying this rule:
1156
1157 bool Profitable =
1158 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1159 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1160 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1161
1162 if (Profitable) {
1163 Value *NewLHS = Builder->CreateNot(LHS);
1164 Value *NewRHS = Builder->CreateNot(RHS);
1165 Value *NewCmp = SPF == SPF_SMAX
1166 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1167 : Builder->CreateICmpULT(NewLHS, NewRHS);
1168 Value *NewSI =
1169 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1170 return replaceInstUsesWith(SI, NewSI);
1171 }
1172 }
1173 }
1174
1175 // TODO.
1176 // ABS(-X) -> ABS(X)
1177 }
1178
1179 // See if we can fold the select into a phi node if the condition is a select.
1180 if (isa<PHINode>(SI.getCondition()))
1181 // The true/false values have to be live in the PHI predecessor's blocks.
1182 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1183 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1184 if (Instruction *NV = FoldOpIntoPhi(SI))
1185 return NV;
1186
1187 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1188 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1189 // select(C, select(C, a, b), c) -> select(C, a, c)
1190 if (TrueSI->getCondition() == CondVal) {
1191 if (SI.getTrueValue() == TrueSI->getTrueValue())
1192 return nullptr;
1193 SI.setOperand(1, TrueSI->getTrueValue());
1194 return &SI;
1195 }
1196 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1197 // We choose this as normal form to enable folding on the And and shortening
1198 // paths for the values (this helps GetUnderlyingObjects() for example).
1199 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1200 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1201 SI.setOperand(0, And);
1202 SI.setOperand(1, TrueSI->getTrueValue());
1203 return &SI;
1204 }
1205 }
1206 }
1207 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1208 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1209 // select(C, a, select(C, b, c)) -> select(C, a, c)
1210 if (FalseSI->getCondition() == CondVal) {
1211 if (SI.getFalseValue() == FalseSI->getFalseValue())
1212 return nullptr;
1213 SI.setOperand(2, FalseSI->getFalseValue());
1214 return &SI;
1215 }
1216 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1217 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1218 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1219 SI.setOperand(0, Or);
1220 SI.setOperand(2, FalseSI->getFalseValue());
1221 return &SI;
1222 }
1223 }
1224 }
1225
1226 if (BinaryOperator::isNot(CondVal)) {
1227 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1228 SI.setOperand(1, FalseVal);
1229 SI.setOperand(2, TrueVal);
1230 return &SI;
1231 }
1232
1233 if (VectorType* VecTy = dyn_cast<VectorType>(SelType)) {
1234 unsigned VWidth = VecTy->getNumElements();
1235 APInt UndefElts(VWidth, 0);
1236 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1237 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1238 if (V != &SI)
1239 return replaceInstUsesWith(SI, V);
1240 return &SI;
1241 }
1242
1243 if (isa<ConstantAggregateZero>(CondVal)) {
1244 return replaceInstUsesWith(SI, FalseVal);
1245 }
1246 }
1247
1248 // See if we can determine the result of this select based on a dominating
1249 // condition.
1250 BasicBlock *Parent = SI.getParent();
1251 if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1252 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1253 if (PBI && PBI->isConditional() &&
1254 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1255 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1256 bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1257 Optional<bool> Implication = isImpliedCondition(
1258 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1259 if (Implication) {
1260 Value *V = *Implication ? TrueVal : FalseVal;
1261 return replaceInstUsesWith(SI, V);
1262 }
1263 }
1264 }
1265
1266 return nullptr;
1267 }
1268