blob: 8b9261b8fe00564eb3a6889344563860dacea456 [file] [log] [blame]
Chris Lattner1c22c802010-01-05 06:05:07 +00001//===- InstCombineSelect.cpp ----------------------------------------------===//
Chris Lattnerc6334b92010-01-05 06:03:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner1c22c802010-01-05 06:05:07 +000010// This file implements the visitSelect function.
Chris Lattnerc6334b92010-01-05 06:03:12 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Chris Lattnerc6334b92010-01-05 06:03:12 +000015#include "llvm/Support/PatternMatch.h"
Chris Lattner04754262010-04-20 05:32:14 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerc6334b92010-01-05 06:03:12 +000017using namespace llvm;
18using namespace PatternMatch;
19
20/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
21/// returning the kind and providing the out parameter results if we
22/// successfully match.
23static SelectPatternFlavor
24MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
25 SelectInst *SI = dyn_cast<SelectInst>(V);
26 if (SI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000027
Chris Lattnerc6334b92010-01-05 06:03:12 +000028 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
29 if (ICI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000030
Chris Lattnerc6334b92010-01-05 06:03:12 +000031 LHS = ICI->getOperand(0);
32 RHS = ICI->getOperand(1);
Tobias Grosser8d088bd2011-01-07 21:33:13 +000033
34 // (icmp X, Y) ? X : Y
Chris Lattnerc6334b92010-01-05 06:03:12 +000035 if (SI->getTrueValue() == ICI->getOperand(0) &&
36 SI->getFalseValue() == ICI->getOperand(1)) {
37 switch (ICI->getPredicate()) {
38 default: return SPF_UNKNOWN; // Equality.
39 case ICmpInst::ICMP_UGT:
40 case ICmpInst::ICMP_UGE: return SPF_UMAX;
41 case ICmpInst::ICMP_SGT:
42 case ICmpInst::ICMP_SGE: return SPF_SMAX;
43 case ICmpInst::ICMP_ULT:
44 case ICmpInst::ICMP_ULE: return SPF_UMIN;
45 case ICmpInst::ICMP_SLT:
46 case ICmpInst::ICMP_SLE: return SPF_SMIN;
47 }
48 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000049
50 // (icmp X, Y) ? Y : X
Chris Lattnerc6334b92010-01-05 06:03:12 +000051 if (SI->getTrueValue() == ICI->getOperand(1) &&
52 SI->getFalseValue() == ICI->getOperand(0)) {
53 switch (ICI->getPredicate()) {
54 default: return SPF_UNKNOWN; // Equality.
55 case ICmpInst::ICMP_UGT:
56 case ICmpInst::ICMP_UGE: return SPF_UMIN;
57 case ICmpInst::ICMP_SGT:
58 case ICmpInst::ICMP_SGE: return SPF_SMIN;
59 case ICmpInst::ICMP_ULT:
60 case ICmpInst::ICMP_ULE: return SPF_UMAX;
61 case ICmpInst::ICMP_SLT:
62 case ICmpInst::ICMP_SLE: return SPF_SMAX;
63 }
64 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000065
Chris Lattnerc6334b92010-01-05 06:03:12 +000066 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
Tobias Grosser8d088bd2011-01-07 21:33:13 +000067
Chris Lattnerc6334b92010-01-05 06:03:12 +000068 return SPF_UNKNOWN;
69}
70
71
72/// GetSelectFoldableOperands - We want to turn code that looks like this:
73/// %C = or %A, %B
74/// %D = select %cond, %C, %A
75/// into:
76/// %C = select %cond, %B, 0
77/// %D = or %A, %C
78///
79/// Assuming that the specified instruction is an operand to the select, return
80/// a bitmask indicating which operands of this instruction are foldable if they
81/// equal the other incoming value of the select.
82///
83static unsigned GetSelectFoldableOperands(Instruction *I) {
84 switch (I->getOpcode()) {
85 case Instruction::Add:
86 case Instruction::Mul:
87 case Instruction::And:
88 case Instruction::Or:
89 case Instruction::Xor:
90 return 3; // Can fold through either operand.
91 case Instruction::Sub: // Can only fold on the amount subtracted.
92 case Instruction::Shl: // Can only fold on the shift amount.
93 case Instruction::LShr:
94 case Instruction::AShr:
95 return 1;
96 default:
97 return 0; // Cannot fold
98 }
99}
100
101/// GetSelectFoldableConstant - For the same transformation as the previous
102/// function, return the identity constant that goes into the select.
103static Constant *GetSelectFoldableConstant(Instruction *I) {
104 switch (I->getOpcode()) {
105 default: llvm_unreachable("This cannot happen!");
106 case Instruction::Add:
107 case Instruction::Sub:
108 case Instruction::Or:
109 case Instruction::Xor:
110 case Instruction::Shl:
111 case Instruction::LShr:
112 case Instruction::AShr:
113 return Constant::getNullValue(I->getType());
114 case Instruction::And:
115 return Constant::getAllOnesValue(I->getType());
116 case Instruction::Mul:
117 return ConstantInt::get(I->getType(), 1);
118 }
119}
120
121/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
122/// have the same opcode and only one use each. Try to simplify this.
123Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI) {
125 if (TI->getNumOperands() == 1) {
126 // If this is a non-volatile load or a cast from the same type,
127 // merge.
128 if (TI->isCast()) {
129 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
130 return 0;
131 } else {
132 return 0; // unknown unary op.
133 }
134
135 // Fold this by inserting a select from the input values.
136 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
137 FI->getOperand(0), SI.getName()+".v");
138 InsertNewInstBefore(NewSI, SI);
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattnerc6334b92010-01-05 06:03:12 +0000140 TI->getType());
141 }
142
143 // Only handle binary operators here.
144 if (!isa<BinaryOperator>(TI))
145 return 0;
146
147 // Figure out if the operations have any operands in common.
148 Value *MatchOp, *OtherOpT, *OtherOpF;
149 bool MatchIsOpZero;
150 if (TI->getOperand(0) == FI->getOperand(0)) {
151 MatchOp = TI->getOperand(0);
152 OtherOpT = TI->getOperand(1);
153 OtherOpF = FI->getOperand(1);
154 MatchIsOpZero = true;
155 } else if (TI->getOperand(1) == FI->getOperand(1)) {
156 MatchOp = TI->getOperand(1);
157 OtherOpT = TI->getOperand(0);
158 OtherOpF = FI->getOperand(0);
159 MatchIsOpZero = false;
160 } else if (!TI->isCommutative()) {
161 return 0;
162 } else if (TI->getOperand(0) == FI->getOperand(1)) {
163 MatchOp = TI->getOperand(0);
164 OtherOpT = TI->getOperand(1);
165 OtherOpF = FI->getOperand(0);
166 MatchIsOpZero = true;
167 } else if (TI->getOperand(1) == FI->getOperand(0)) {
168 MatchOp = TI->getOperand(1);
169 OtherOpT = TI->getOperand(0);
170 OtherOpF = FI->getOperand(1);
171 MatchIsOpZero = true;
172 } else {
173 return 0;
174 }
175
176 // If we reach here, they do have operations in common.
177 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
178 OtherOpF, SI.getName()+".v");
179 InsertNewInstBefore(NewSI, SI);
180
181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
182 if (MatchIsOpZero)
183 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
184 else
185 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
186 }
187 llvm_unreachable("Shouldn't get here");
188 return 0;
189}
190
191static bool isSelect01(Constant *C1, Constant *C2) {
192 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
193 if (!C1I)
194 return false;
195 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
196 if (!C2I)
197 return false;
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000198 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
199 return false;
200 return C1I->isOne() || C1I->isAllOnesValue() ||
201 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattnerc6334b92010-01-05 06:03:12 +0000202}
203
204/// FoldSelectIntoOp - Try fold the select into one of the operands to
205/// facilitate further optimization.
206Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
207 Value *FalseVal) {
208 // See the comment above GetSelectFoldableOperands for a description of the
209 // transformation we are doing here.
210 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
211 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
212 !isa<Constant>(FalseVal)) {
213 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
214 unsigned OpToFold = 0;
215 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
216 OpToFold = 1;
217 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
218 OpToFold = 2;
219 }
220
221 if (OpToFold) {
222 Constant *C = GetSelectFoldableConstant(TVI);
223 Value *OOp = TVI->getOperand(2-OpToFold);
224 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000225 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000226 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
227 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
228 InsertNewInstBefore(NewSel, SI);
229 NewSel->takeName(TVI);
230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
231 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
232 llvm_unreachable("Unknown instruction!!");
233 }
234 }
235 }
236 }
237 }
238
239 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
240 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
241 !isa<Constant>(TrueVal)) {
242 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
243 unsigned OpToFold = 0;
244 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
245 OpToFold = 1;
246 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
247 OpToFold = 2;
248 }
249
250 if (OpToFold) {
251 Constant *C = GetSelectFoldableConstant(FVI);
252 Value *OOp = FVI->getOperand(2-OpToFold);
253 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000254 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000255 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
256 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
257 InsertNewInstBefore(NewSel, SI);
258 NewSel->takeName(FVI);
259 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
260 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
261 llvm_unreachable("Unknown instruction!!");
262 }
263 }
264 }
265 }
266 }
267
268 return 0;
269}
270
271/// visitSelectInstWithICmp - Visit a SelectInst that has an
272/// ICmpInst as its first operand.
273///
274Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
275 ICmpInst *ICI) {
276 bool Changed = false;
277 ICmpInst::Predicate Pred = ICI->getPredicate();
278 Value *CmpLHS = ICI->getOperand(0);
279 Value *CmpRHS = ICI->getOperand(1);
280 Value *TrueVal = SI.getTrueValue();
281 Value *FalseVal = SI.getFalseValue();
282
283 // Check cases where the comparison is with a constant that
Tobias Grosseraa2be842011-01-09 16:00:11 +0000284 // can be adjusted to fit the min/max idiom. We may move or edit ICI
285 // here, so make sure the select is the only user.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000286 if (ICI->hasOneUse())
287 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Tobias Grosser46431d72011-01-07 21:33:14 +0000288 // X < MIN ? T : F --> F
289 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
290 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
291 return ReplaceInstUsesWith(SI, FalseVal);
292 // X > MAX ? T : F --> F
293 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
294 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
295 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000296 switch (Pred) {
297 default: break;
298 case ICmpInst::ICMP_ULT:
Tobias Grosser46431d72011-01-07 21:33:14 +0000299 case ICmpInst::ICMP_SLT:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000300 case ICmpInst::ICMP_UGT:
301 case ICmpInst::ICMP_SGT: {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000302 // These transformations only work for selects over integers.
303 const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
304 if (!SelectTy)
305 break;
306
Tobias Grosser46431d72011-01-07 21:33:14 +0000307 Constant *AdjustedRHS;
308 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
309 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
310 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
311 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
312
Chris Lattnerc6334b92010-01-05 06:03:12 +0000313 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosser46431d72011-01-07 21:33:14 +0000314 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattnerc6334b92010-01-05 06:03:12 +0000315 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosser46431d72011-01-07 21:33:14 +0000316 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
317 ; // Nothing to do here. Values match without any sign/zero extension.
318
319 // Types do not match. Instead of calculating this with mixed types
320 // promote all to the larger type. This enables scalar evolution to
321 // analyze this expression.
322 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommelb686eb92011-01-08 10:51:36 +0000323 < SelectTy->getBitWidth()) {
324 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000325
326 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
327 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
328 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
329 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
330 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
331 sextRHS == FalseVal) {
332 CmpLHS = TrueVal;
333 AdjustedRHS = sextRHS;
334 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
335 sextRHS == TrueVal) {
336 CmpLHS = FalseVal;
337 AdjustedRHS = sextRHS;
338 } else if (ICI->isUnsigned()) {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000339 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000340 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
341 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
342 // zext + signed compare cannot be changed:
343 // 0xff <s 0x00, but 0x00ff >s 0x0000
344 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
345 zextRHS == FalseVal) {
346 CmpLHS = TrueVal;
347 AdjustedRHS = zextRHS;
348 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
349 zextRHS == TrueVal) {
350 CmpLHS = FalseVal;
351 AdjustedRHS = zextRHS;
352 } else
353 break;
354 } else
355 break;
356 } else
357 break;
358
359 Pred = ICmpInst::getSwappedPredicate(Pred);
360 CmpRHS = AdjustedRHS;
361 std::swap(FalseVal, TrueVal);
362 ICI->setPredicate(Pred);
363 ICI->setOperand(0, CmpLHS);
364 ICI->setOperand(1, CmpRHS);
365 SI.setOperand(1, TrueVal);
366 SI.setOperand(2, FalseVal);
Tobias Grosseraa2be842011-01-09 16:00:11 +0000367
368 // Move ICI instruction right before the select instruction. Otherwise
369 // the sext/zext value may be defined after the ICI instruction uses it.
370 ICI->moveBefore(&SI);
371
Tobias Grosser46431d72011-01-07 21:33:14 +0000372 Changed = true;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000373 break;
374 }
375 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000376 }
377
Benjamin Kramer1db071f2010-07-08 11:39:10 +0000378 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
379 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
380 // FIXME: Type and constness constraints could be lifted, but we have to
381 // watch code size carefully. We should consider xor instead of
382 // sub/add when we decide to do that.
383 if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
384 if (TrueVal->getType() == Ty) {
385 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
386 ConstantInt *C1 = NULL, *C2 = NULL;
387 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
388 C1 = dyn_cast<ConstantInt>(TrueVal);
389 C2 = dyn_cast<ConstantInt>(FalseVal);
390 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
391 C1 = dyn_cast<ConstantInt>(FalseVal);
392 C2 = dyn_cast<ConstantInt>(TrueVal);
393 }
394 if (C1 && C2) {
395 // This shift results in either -1 or 0.
396 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
397
398 // Check if we can express the operation with a single or.
399 if (C2->isAllOnesValue())
400 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
401
402 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
403 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
404 }
405 }
406 }
407 }
408
Chris Lattnerc6334b92010-01-05 06:03:12 +0000409 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
410 // Transform (X == Y) ? X : Y -> Y
411 if (Pred == ICmpInst::ICMP_EQ)
412 return ReplaceInstUsesWith(SI, FalseVal);
413 // Transform (X != Y) ? X : Y -> X
414 if (Pred == ICmpInst::ICMP_NE)
415 return ReplaceInstUsesWith(SI, TrueVal);
416 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
417
418 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
419 // Transform (X == Y) ? Y : X -> X
420 if (Pred == ICmpInst::ICMP_EQ)
421 return ReplaceInstUsesWith(SI, FalseVal);
422 // Transform (X != Y) ? Y : X -> Y
423 if (Pred == ICmpInst::ICMP_NE)
424 return ReplaceInstUsesWith(SI, TrueVal);
425 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
426 }
427 return Changed ? &SI : 0;
428}
429
430
431/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
432/// PHI node (but the two may be in different blocks). See if the true/false
433/// values (V) are live in all of the predecessor blocks of the PHI. For
434/// example, cases like this cannot be mapped:
435///
436/// X = phi [ C1, BB1], [C2, BB2]
437/// Y = add
438/// Z = select X, Y, 0
439///
440/// because Y is not live in BB1/BB2.
441///
442static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
443 const SelectInst &SI) {
444 // If the value is a non-instruction value like a constant or argument, it
445 // can always be mapped.
446 const Instruction *I = dyn_cast<Instruction>(V);
447 if (I == 0) return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000448
Chris Lattnerc6334b92010-01-05 06:03:12 +0000449 // If V is a PHI node defined in the same block as the condition PHI, we can
450 // map the arguments.
451 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000452
Chris Lattnerc6334b92010-01-05 06:03:12 +0000453 if (const PHINode *VP = dyn_cast<PHINode>(I))
454 if (VP->getParent() == CondPHI->getParent())
455 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000456
Chris Lattnerc6334b92010-01-05 06:03:12 +0000457 // Otherwise, if the PHI and select are defined in the same block and if V is
458 // defined in a different block, then we can transform it.
459 if (SI.getParent() == CondPHI->getParent() &&
460 I->getParent() != CondPHI->getParent())
461 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000462
Chris Lattnerc6334b92010-01-05 06:03:12 +0000463 // Otherwise we have a 'hard' case and we can't tell without doing more
464 // detailed dominator based analysis, punt.
465 return false;
466}
467
468/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000469/// SPF2(SPF1(A, B), C)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000470Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
471 SelectPatternFlavor SPF1,
472 Value *A, Value *B,
473 Instruction &Outer,
474 SelectPatternFlavor SPF2, Value *C) {
475 if (C == A || C == B) {
476 // MAX(MAX(A, B), B) -> MAX(A, B)
477 // MIN(MIN(a, b), a) -> MIN(a, b)
478 if (SPF1 == SPF2)
479 return ReplaceInstUsesWith(Outer, Inner);
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000480
Chris Lattnerc6334b92010-01-05 06:03:12 +0000481 // MAX(MIN(a, b), a) -> a
482 // MIN(MAX(a, b), a) -> a
483 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
484 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
485 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
486 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
487 return ReplaceInstUsesWith(Outer, C);
488 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000489
Chris Lattnerc6334b92010-01-05 06:03:12 +0000490 // TODO: MIN(MIN(A, 23), 97)
491 return 0;
492}
493
494
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000495/// foldSelectICmpAnd - If one of the constants is zero (we know they can't
496/// both be) and we have an icmp instruction with zero, and we have an 'and'
497/// with the non-constant value and a power of two we can turn the select
498/// into a shift on the result of the 'and'.
499static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
500 ConstantInt *FalseVal,
501 InstCombiner::BuilderTy *Builder) {
502 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
503 if (!IC || !IC->isEquality())
504 return 0;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000505
Benjamin Kramer6b497252011-03-11 11:37:40 +0000506 if (!match(IC->getOperand(1), m_Zero()))
507 return 0;
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000508
509 ConstantInt *AndRHS;
510 Value *LHS = IC->getOperand(0);
511 if (LHS->getType() != SI.getType() ||
512 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
513 return 0;
514
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000515 // If both select arms are non-zero see if we have a select of the form
516 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
517 // for 'x ? 2^n : 0' and fix the thing up at the end.
518 ConstantInt *Offset = 0;
519 if (!TrueVal->isZero() && !FalseVal->isZero()) {
520 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
521 Offset = FalseVal;
522 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
523 Offset = TrueVal;
524 else
525 return 0;
526
527 // Adjust TrueVal and FalseVal to the offset.
528 TrueVal = ConstantInt::get(Builder->getContext(),
529 TrueVal->getValue() - Offset->getValue());
530 FalseVal = ConstantInt::get(Builder->getContext(),
531 FalseVal->getValue() - Offset->getValue());
532 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000533
534 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
535 if (!AndRHS->getValue().isPowerOf2() ||
536 (!TrueVal->getValue().isPowerOf2() &&
537 !FalseVal->getValue().isPowerOf2()))
538 return 0;
539
540 // Determine which shift is needed to transform result of the 'and' into the
541 // desired result.
542 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
543 unsigned ValZeros = ValC->getValue().logBase2();
544 unsigned AndZeros = AndRHS->getValue().logBase2();
545
546 Value *V = LHS;
547 if (ValZeros > AndZeros)
548 V = Builder->CreateShl(V, ValZeros - AndZeros);
549 else if (ValZeros < AndZeros)
550 V = Builder->CreateLShr(V, AndZeros - ValZeros);
551
552 // Okay, now we know that everything is set up, we just don't know whether we
553 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
554 bool ShouldNotVal = !TrueVal->isZero();
555 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
556 if (ShouldNotVal)
557 V = Builder->CreateXor(V, ValC);
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000558
559 // Apply an offset if needed.
560 if (Offset)
561 V = Builder->CreateAdd(V, Offset);
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000562 return V;
563}
Chris Lattnerc6334b92010-01-05 06:03:12 +0000564
565Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
566 Value *CondVal = SI.getCondition();
567 Value *TrueVal = SI.getTrueValue();
568 Value *FalseVal = SI.getFalseValue();
569
Chris Lattner04754262010-04-20 05:32:14 +0000570 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
571 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000572
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000573 if (SI.getType()->isIntegerTy(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000574 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
575 if (C->getZExtValue()) {
576 // Change: A = select B, true, C --> A = or B, C
577 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000578 }
Chris Lattner04754262010-04-20 05:32:14 +0000579 // Change: A = select B, false, C --> A = and !B, C
580 Value *NotCond =
581 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
582 "not."+CondVal->getName()), SI);
583 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000584 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
585 if (C->getZExtValue() == false) {
586 // Change: A = select B, C, false --> A = and B, C
587 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000588 }
Chris Lattner04754262010-04-20 05:32:14 +0000589 // Change: A = select B, C, true --> A = or !B, C
590 Value *NotCond =
591 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
592 "not."+CondVal->getName()), SI);
593 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000594 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000595
Chris Lattnerc6334b92010-01-05 06:03:12 +0000596 // select a, b, a -> a&b
597 // select a, a, b -> a|b
598 if (CondVal == TrueVal)
599 return BinaryOperator::CreateOr(CondVal, FalseVal);
600 else if (CondVal == FalseVal)
601 return BinaryOperator::CreateAnd(CondVal, TrueVal);
602 }
603
604 // Selecting between two integer constants?
605 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
606 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
607 // select C, 1, 0 -> zext C to int
Chris Lattnerabb992d2010-01-24 00:09:49 +0000608 if (FalseValC->isZero() && TrueValC->getValue() == 1)
609 return new ZExtInst(CondVal, SI.getType());
610
611 // select C, -1, 0 -> sext C to int
612 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
613 return new SExtInst(CondVal, SI.getType());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000614
Chris Lattnerabb992d2010-01-24 00:09:49 +0000615 // select C, 0, 1 -> zext !C to int
616 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
617 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
618 return new ZExtInst(NotCond, SI.getType());
Chris Lattnerc6334b92010-01-05 06:03:12 +0000619 }
620
Chris Lattnerabb992d2010-01-24 00:09:49 +0000621 // select C, 0, -1 -> sext !C to int
622 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
623 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
624 return new SExtInst(NotCond, SI.getType());
625 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000626
627 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
628 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000629 }
630
631 // See if we are selecting two values based on a comparison of the two values.
632 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
633 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
634 // Transform (X == Y) ? X : Y -> Y
635 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000636 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000637 // consider X== -0, Y== +0.
638 // It becomes safe if either operand is a nonzero constant.
639 ConstantFP *CFPt, *CFPf;
640 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
641 !CFPt->getValueAPF().isZero()) ||
642 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
643 !CFPf->getValueAPF().isZero()))
644 return ReplaceInstUsesWith(SI, FalseVal);
645 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000646 // Transform (X une Y) ? X : Y -> X
647 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000648 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000649 // consider X== -0, Y== +0.
650 // It becomes safe if either operand is a nonzero constant.
651 ConstantFP *CFPt, *CFPf;
652 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
653 !CFPt->getValueAPF().isZero()) ||
654 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
655 !CFPf->getValueAPF().isZero()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000656 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman21dc20c2010-02-23 17:17:57 +0000657 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000658 // NOTE: if we wanted to, this is where to detect MIN/MAX
659
660 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
661 // Transform (X == Y) ? Y : X -> X
662 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000663 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000664 // consider X== -0, Y== +0.
665 // It becomes safe if either operand is a nonzero constant.
666 ConstantFP *CFPt, *CFPf;
667 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
668 !CFPt->getValueAPF().isZero()) ||
669 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
670 !CFPf->getValueAPF().isZero()))
671 return ReplaceInstUsesWith(SI, FalseVal);
672 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000673 // Transform (X une Y) ? Y : X -> Y
674 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000675 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000676 // consider X== -0, Y== +0.
677 // It becomes safe if either operand is a nonzero constant.
678 ConstantFP *CFPt, *CFPf;
679 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
680 !CFPt->getValueAPF().isZero()) ||
681 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
682 !CFPf->getValueAPF().isZero()))
683 return ReplaceInstUsesWith(SI, TrueVal);
684 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000685 // NOTE: if we wanted to, this is where to detect MIN/MAX
686 }
687 // NOTE: if we wanted to, this is where to detect ABS
688 }
689
690 // See if we are selecting two values based on a comparison of the two values.
691 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
692 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
693 return Result;
694
695 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
696 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
697 if (TI->hasOneUse() && FI->hasOneUse()) {
698 Instruction *AddOp = 0, *SubOp = 0;
699
700 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
701 if (TI->getOpcode() == FI->getOpcode())
702 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
703 return IV;
704
705 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
706 // even legal for FP.
707 if ((TI->getOpcode() == Instruction::Sub &&
708 FI->getOpcode() == Instruction::Add) ||
709 (TI->getOpcode() == Instruction::FSub &&
710 FI->getOpcode() == Instruction::FAdd)) {
711 AddOp = FI; SubOp = TI;
712 } else if ((FI->getOpcode() == Instruction::Sub &&
713 TI->getOpcode() == Instruction::Add) ||
714 (FI->getOpcode() == Instruction::FSub &&
715 TI->getOpcode() == Instruction::FAdd)) {
716 AddOp = TI; SubOp = FI;
717 }
718
719 if (AddOp) {
720 Value *OtherAddOp = 0;
721 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
722 OtherAddOp = AddOp->getOperand(1);
723 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
724 OtherAddOp = AddOp->getOperand(0);
725 }
726
727 if (OtherAddOp) {
728 // So at this point we know we have (Y -> OtherAddOp):
729 // select C, (add X, Y), (sub X, Z)
730 Value *NegVal; // Compute -Z
731 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
732 NegVal = ConstantExpr::getNeg(C);
Dale Johannesenf514f522010-10-27 23:45:18 +0000733 } else if (SI.getType()->isFloatingPointTy()) {
734 NegVal = InsertNewInstBefore(
735 BinaryOperator::CreateFNeg(SubOp->getOperand(1),
736 "tmp"), SI);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000737 } else {
738 NegVal = InsertNewInstBefore(
739 BinaryOperator::CreateNeg(SubOp->getOperand(1),
740 "tmp"), SI);
741 }
742
743 Value *NewTrueOp = OtherAddOp;
744 Value *NewFalseOp = NegVal;
745 if (AddOp != TI)
746 std::swap(NewTrueOp, NewFalseOp);
747 Instruction *NewSel =
748 SelectInst::Create(CondVal, NewTrueOp,
749 NewFalseOp, SI.getName() + ".p");
750
751 NewSel = InsertNewInstBefore(NewSel, SI);
Dale Johannesenf514f522010-10-27 23:45:18 +0000752 if (SI.getType()->isFloatingPointTy())
753 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
754 else
755 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000756 }
757 }
758 }
759
760 // See if we can fold the select into one of our operands.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000761 if (SI.getType()->isIntegerTy()) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000762 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
763 return FoldI;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000764
Chris Lattnerc6334b92010-01-05 06:03:12 +0000765 // MAX(MAX(a, b), a) -> MAX(a, b)
766 // MIN(MIN(a, b), a) -> MIN(a, b)
767 // MAX(MIN(a, b), a) -> a
768 // MIN(MAX(a, b), a) -> a
769 Value *LHS, *RHS, *LHS2, *RHS2;
770 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
771 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
772 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
773 SI, SPF, RHS))
774 return R;
775 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
776 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
777 SI, SPF, LHS))
778 return R;
779 }
780
781 // TODO.
782 // ABS(-X) -> ABS(X)
783 // ABS(ABS(X)) -> ABS(X)
784 }
785
786 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000787 if (isa<PHINode>(SI.getCondition()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000788 // The true/false values have to be live in the PHI predecessor's blocks.
789 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
790 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
791 if (Instruction *NV = FoldOpIntoPhi(SI))
792 return NV;
793
Nick Lewyckydf3bfae2011-01-28 03:28:10 +0000794 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
795 if (TrueSI->getCondition() == CondVal) {
796 SI.setOperand(1, TrueSI->getTrueValue());
797 return &SI;
798 }
799 }
800 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
801 if (FalseSI->getCondition() == CondVal) {
802 SI.setOperand(2, FalseSI->getFalseValue());
803 return &SI;
804 }
805 }
806
Chris Lattnerc6334b92010-01-05 06:03:12 +0000807 if (BinaryOperator::isNot(CondVal)) {
808 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
809 SI.setOperand(1, FalseVal);
810 SI.setOperand(2, TrueVal);
811 return &SI;
812 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000813
814 return 0;
815}