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