blob: a34b73ace49c8ce589b4bd70800541a1fe2b3b01 [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"
Eli Friedman74703252011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner04754262010-04-20 05:32:14 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/Support/PatternMatch.h"
Chris Lattnerc6334b92010-01-05 06:03:12 +000018using namespace llvm;
19using namespace PatternMatch;
20
21/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
22/// returning the kind and providing the out parameter results if we
23/// successfully match.
24static SelectPatternFlavor
25MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
26 SelectInst *SI = dyn_cast<SelectInst>(V);
27 if (SI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000028
Chris Lattnerc6334b92010-01-05 06:03:12 +000029 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
30 if (ICI == 0) return SPF_UNKNOWN;
Tobias Grosser8d088bd2011-01-07 21:33:13 +000031
Chris Lattnerc6334b92010-01-05 06:03:12 +000032 LHS = ICI->getOperand(0);
33 RHS = ICI->getOperand(1);
Tobias Grosser8d088bd2011-01-07 21:33:13 +000034
35 // (icmp X, Y) ? X : Y
Chris Lattnerc6334b92010-01-05 06:03:12 +000036 if (SI->getTrueValue() == ICI->getOperand(0) &&
37 SI->getFalseValue() == ICI->getOperand(1)) {
38 switch (ICI->getPredicate()) {
39 default: return SPF_UNKNOWN; // Equality.
40 case ICmpInst::ICMP_UGT:
41 case ICmpInst::ICMP_UGE: return SPF_UMAX;
42 case ICmpInst::ICMP_SGT:
43 case ICmpInst::ICMP_SGE: return SPF_SMAX;
44 case ICmpInst::ICMP_ULT:
45 case ICmpInst::ICMP_ULE: return SPF_UMIN;
46 case ICmpInst::ICMP_SLT:
47 case ICmpInst::ICMP_SLE: return SPF_SMIN;
48 }
49 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000050
51 // (icmp X, Y) ? Y : X
Chris Lattnerc6334b92010-01-05 06:03:12 +000052 if (SI->getTrueValue() == ICI->getOperand(1) &&
53 SI->getFalseValue() == ICI->getOperand(0)) {
54 switch (ICI->getPredicate()) {
55 default: return SPF_UNKNOWN; // Equality.
56 case ICmpInst::ICMP_UGT:
57 case ICmpInst::ICMP_UGE: return SPF_UMIN;
58 case ICmpInst::ICMP_SGT:
59 case ICmpInst::ICMP_SGE: return SPF_SMIN;
60 case ICmpInst::ICMP_ULT:
61 case ICmpInst::ICMP_ULE: return SPF_UMAX;
62 case ICmpInst::ICMP_SLT:
63 case ICmpInst::ICMP_SLE: return SPF_SMAX;
64 }
65 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +000066
Chris Lattnerc6334b92010-01-05 06:03:12 +000067 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
Tobias Grosser8d088bd2011-01-07 21:33:13 +000068
Chris Lattnerc6334b92010-01-05 06:03:12 +000069 return SPF_UNKNOWN;
70}
71
72
73/// GetSelectFoldableOperands - We want to turn code that looks like this:
74/// %C = or %A, %B
75/// %D = select %cond, %C, %A
76/// into:
77/// %C = select %cond, %B, 0
78/// %D = or %A, %C
79///
80/// Assuming that the specified instruction is an operand to the select, return
81/// a bitmask indicating which operands of this instruction are foldable if they
82/// equal the other incoming value of the select.
83///
84static unsigned GetSelectFoldableOperands(Instruction *I) {
85 switch (I->getOpcode()) {
86 case Instruction::Add:
87 case Instruction::Mul:
88 case Instruction::And:
89 case Instruction::Or:
90 case Instruction::Xor:
91 return 3; // Can fold through either operand.
92 case Instruction::Sub: // Can only fold on the amount subtracted.
93 case Instruction::Shl: // Can only fold on the shift amount.
94 case Instruction::LShr:
95 case Instruction::AShr:
96 return 1;
97 default:
98 return 0; // Cannot fold
99 }
100}
101
102/// GetSelectFoldableConstant - For the same transformation as the previous
103/// function, return the identity constant that goes into the select.
104static Constant *GetSelectFoldableConstant(Instruction *I) {
105 switch (I->getOpcode()) {
106 default: llvm_unreachable("This cannot happen!");
107 case Instruction::Add:
108 case Instruction::Sub:
109 case Instruction::Or:
110 case Instruction::Xor:
111 case Instruction::Shl:
112 case Instruction::LShr:
113 case Instruction::AShr:
114 return Constant::getNullValue(I->getType());
115 case Instruction::And:
116 return Constant::getAllOnesValue(I->getType());
117 case Instruction::Mul:
118 return ConstantInt::get(I->getType(), 1);
119 }
120}
121
122/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
123/// have the same opcode and only one use each. Try to simplify this.
124Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
125 Instruction *FI) {
126 if (TI->getNumOperands() == 1) {
127 // If this is a non-volatile load or a cast from the same type,
128 // merge.
129 if (TI->isCast()) {
Akira Hatanakad7216a22013-03-28 01:28:02 +0000130 Type *FIOpndTy = FI->getOperand(0)->getType();
131 if (TI->getOperand(0)->getType() != FIOpndTy)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000132 return 0;
Nadav Rotem2f6622c2012-06-07 20:28:57 +0000133 // The select condition may be a vector. We may only change the operand
134 // type if the vector width remains the same (and matches the condition).
135 Type *CondTy = SI.getCondition()->getType();
Akira Hatanakad7216a22013-03-28 01:28:02 +0000136 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
137 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
Nadav Rotem2f6622c2012-06-07 20:28:57 +0000138 return 0;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000139 } else {
140 return 0; // unknown unary op.
141 }
142
143 // Fold this by inserting a select from the input values.
Eli Friedman976e7e12011-05-18 18:10:28 +0000144 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
145 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000146 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattnerc6334b92010-01-05 06:03:12 +0000147 TI->getType());
148 }
149
150 // Only handle binary operators here.
151 if (!isa<BinaryOperator>(TI))
152 return 0;
153
154 // Figure out if the operations have any operands in common.
155 Value *MatchOp, *OtherOpT, *OtherOpF;
156 bool MatchIsOpZero;
157 if (TI->getOperand(0) == FI->getOperand(0)) {
158 MatchOp = TI->getOperand(0);
159 OtherOpT = TI->getOperand(1);
160 OtherOpF = FI->getOperand(1);
161 MatchIsOpZero = true;
162 } else if (TI->getOperand(1) == FI->getOperand(1)) {
163 MatchOp = TI->getOperand(1);
164 OtherOpT = TI->getOperand(0);
165 OtherOpF = FI->getOperand(0);
166 MatchIsOpZero = false;
167 } else if (!TI->isCommutative()) {
168 return 0;
169 } else if (TI->getOperand(0) == FI->getOperand(1)) {
170 MatchOp = TI->getOperand(0);
171 OtherOpT = TI->getOperand(1);
172 OtherOpF = FI->getOperand(0);
173 MatchIsOpZero = true;
174 } else if (TI->getOperand(1) == FI->getOperand(0)) {
175 MatchOp = TI->getOperand(1);
176 OtherOpT = TI->getOperand(0);
177 OtherOpF = FI->getOperand(1);
178 MatchIsOpZero = true;
179 } else {
180 return 0;
181 }
182
183 // If we reach here, they do have operations in common.
Eli Friedman976e7e12011-05-18 18:10:28 +0000184 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
185 OtherOpF, SI.getName()+".v");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000186
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
188 if (MatchIsOpZero)
189 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
190 else
191 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
192 }
193 llvm_unreachable("Shouldn't get here");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000194}
195
196static bool isSelect01(Constant *C1, Constant *C2) {
197 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
198 if (!C1I)
199 return false;
200 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
201 if (!C2I)
202 return false;
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000203 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
204 return false;
205 return C1I->isOne() || C1I->isAllOnesValue() ||
206 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattnerc6334b92010-01-05 06:03:12 +0000207}
208
209/// FoldSelectIntoOp - Try fold the select into one of the operands to
210/// facilitate further optimization.
211Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
212 Value *FalseVal) {
213 // See the comment above GetSelectFoldableOperands for a description of the
214 // transformation we are doing here.
215 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
216 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
217 !isa<Constant>(FalseVal)) {
218 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
219 unsigned OpToFold = 0;
220 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
221 OpToFold = 1;
Nick Lewycky675619c2011-03-27 19:51:23 +0000222 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000223 OpToFold = 2;
224 }
225
226 if (OpToFold) {
227 Constant *C = GetSelectFoldableConstant(TVI);
228 Value *OOp = TVI->getOperand(2-OpToFold);
229 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000230 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000231 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman976e7e12011-05-18 18:10:28 +0000232 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000233 NewSel->takeName(TVI);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000234 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky675619c2011-03-27 19:51:23 +0000235 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
236 FalseVal, NewSel);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000237 if (isa<PossiblyExactOperator>(BO))
238 BO->setIsExact(TVI_BO->isExact());
239 if (isa<OverflowingBinaryOperator>(BO)) {
240 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
241 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
242 }
243 return BO;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000244 }
245 }
246 }
247 }
248 }
249
250 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
251 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
252 !isa<Constant>(TrueVal)) {
253 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
254 unsigned OpToFold = 0;
255 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
256 OpToFold = 1;
Nick Lewycky675619c2011-03-27 19:51:23 +0000257 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000258 OpToFold = 2;
259 }
260
261 if (OpToFold) {
262 Constant *C = GetSelectFoldableConstant(FVI);
263 Value *OOp = FVI->getOperand(2-OpToFold);
264 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer4ac19472010-12-22 23:12:15 +0000265 // between 0, 1 and -1.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000266 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman976e7e12011-05-18 18:10:28 +0000267 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000268 NewSel->takeName(FVI);
Nick Lewycky675619c2011-03-27 19:51:23 +0000269 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
270 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
271 TrueVal, NewSel);
Nick Lewycky2bf026e2011-03-28 17:48:26 +0000272 if (isa<PossiblyExactOperator>(BO))
273 BO->setIsExact(FVI_BO->isExact());
274 if (isa<OverflowingBinaryOperator>(BO)) {
275 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
276 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
277 }
278 return BO;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000279 }
280 }
281 }
282 }
283 }
284
285 return 0;
286}
287
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000288/// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
289/// replaced with RepOp.
290static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Micah Villmow3574eca2012-10-08 16:38:25 +0000291 const DataLayout *TD,
Chad Rosieraab8e282011-12-02 01:26:24 +0000292 const TargetLibraryInfo *TLI) {
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000293 // Trivial replacement.
294 if (V == Op)
295 return RepOp;
296
297 Instruction *I = dyn_cast<Instruction>(V);
298 if (!I)
299 return 0;
300
301 // If this is a binary operator, try to simplify it with the replaced op.
302 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
303 if (B->getOperand(0) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000304 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000305 if (B->getOperand(1) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000306 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000307 }
308
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000309 // Same for CmpInsts.
310 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
311 if (C->getOperand(0) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000312 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
313 TLI);
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000314 if (C->getOperand(1) == Op)
Chad Rosieraab8e282011-12-02 01:26:24 +0000315 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
316 TLI);
Benjamin Kramer2c5cc682011-05-28 10:16:58 +0000317 }
318
319 // TODO: We could hand off more cases to instsimplify here.
320
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000321 // If all operands are constant after substituting Op for RepOp then we can
322 // constant fold the instruction.
323 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
324 // Build a list of all constant operands.
325 SmallVector<Constant*, 8> ConstOps;
326 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
327 if (I->getOperand(i) == Op)
328 ConstOps.push_back(CRepOp);
329 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
330 ConstOps.push_back(COp);
331 else
332 break;
333 }
334
335 // All operands were constants, fold it.
Nick Lewycky267236a2011-10-02 09:12:55 +0000336 if (ConstOps.size() == I->getNumOperands()) {
Benjamin Kramer82a18332012-10-20 08:43:52 +0000337 if (CmpInst *C = dyn_cast<CmpInst>(I))
338 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
339 ConstOps[1], TD, TLI);
340
Nick Lewycky267236a2011-10-02 09:12:55 +0000341 if (LoadInst *LI = dyn_cast<LoadInst>(I))
342 if (!LI->isVolatile())
343 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
344
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000345 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Chad Rosieraab8e282011-12-02 01:26:24 +0000346 ConstOps, TD, TLI);
Nick Lewycky267236a2011-10-02 09:12:55 +0000347 }
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000348 }
349
350 return 0;
351}
352
David Majnemerdefce4c2013-04-30 08:57:58 +0000353/// foldSelectICmpAndOr - We want to turn:
354/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
355/// into:
356/// (or (shl (and X, C1), C3), y)
357/// iff:
358/// C1 and C2 are both powers of 2
359/// where:
360/// C3 = Log(C2) - Log(C1)
361///
362/// This transform handles cases where:
363/// 1. The icmp predicate is inverted
364/// 2. The select operands are reversed
365/// 3. The magnitude of C2 and C1 are flipped
366static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
367 Value *FalseVal,
368 InstCombiner::BuilderTy *Builder) {
369 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
370 if (!IC || !IC->isEquality())
371 return 0;
372
373 Value *CmpLHS = IC->getOperand(0);
374 Value *CmpRHS = IC->getOperand(1);
375
376 if (!match(CmpRHS, m_Zero()))
377 return 0;
378
379 Value *X;
380 const APInt *C1;
381 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
382 return 0;
383
384 const APInt *C2;
385 bool OrOnTrueVal = false;
386 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
387 if (!OrOnFalseVal)
388 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
389
390 if (!OrOnFalseVal && !OrOnTrueVal)
391 return 0;
392
393 Value *V = CmpLHS;
394 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
395
396 unsigned C1Log = C1->logBase2();
397 unsigned C2Log = C2->logBase2();
398 if (C2Log > C1Log) {
399 V = Builder->CreateZExtOrTrunc(V, Y->getType());
400 V = Builder->CreateShl(V, C2Log - C1Log);
401 } else if (C1Log > C2Log) {
402 V = Builder->CreateLShr(V, C1Log - C2Log);
403 V = Builder->CreateZExtOrTrunc(V, Y->getType());
404 }
405
406 ICmpInst::Predicate Pred = IC->getPredicate();
407 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
408 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
409 V = Builder->CreateXor(V, *C2);
410
411 return Builder->CreateOr(V, Y);
412}
413
Chris Lattnerc6334b92010-01-05 06:03:12 +0000414/// visitSelectInstWithICmp - Visit a SelectInst that has an
415/// ICmpInst as its first operand.
416///
417Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
418 ICmpInst *ICI) {
419 bool Changed = false;
420 ICmpInst::Predicate Pred = ICI->getPredicate();
421 Value *CmpLHS = ICI->getOperand(0);
422 Value *CmpRHS = ICI->getOperand(1);
423 Value *TrueVal = SI.getTrueValue();
424 Value *FalseVal = SI.getFalseValue();
425
426 // Check cases where the comparison is with a constant that
Tobias Grosseraa2be842011-01-09 16:00:11 +0000427 // can be adjusted to fit the min/max idiom. We may move or edit ICI
428 // here, so make sure the select is the only user.
Chris Lattnerc6334b92010-01-05 06:03:12 +0000429 if (ICI->hasOneUse())
430 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Tobias Grosser46431d72011-01-07 21:33:14 +0000431 // X < MIN ? T : F --> F
432 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
433 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
434 return ReplaceInstUsesWith(SI, FalseVal);
435 // X > MAX ? T : F --> F
436 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
437 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
438 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000439 switch (Pred) {
440 default: break;
441 case ICmpInst::ICMP_ULT:
Tobias Grosser46431d72011-01-07 21:33:14 +0000442 case ICmpInst::ICMP_SLT:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000443 case ICmpInst::ICMP_UGT:
444 case ICmpInst::ICMP_SGT: {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000445 // These transformations only work for selects over integers.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000446 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommelb686eb92011-01-08 10:51:36 +0000447 if (!SelectTy)
448 break;
449
Tobias Grosser46431d72011-01-07 21:33:14 +0000450 Constant *AdjustedRHS;
451 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
452 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
453 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
454 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
455
Chris Lattnerc6334b92010-01-05 06:03:12 +0000456 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosser46431d72011-01-07 21:33:14 +0000457 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattnerc6334b92010-01-05 06:03:12 +0000458 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosser46431d72011-01-07 21:33:14 +0000459 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
460 ; // Nothing to do here. Values match without any sign/zero extension.
461
462 // Types do not match. Instead of calculating this with mixed types
463 // promote all to the larger type. This enables scalar evolution to
464 // analyze this expression.
465 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommelb686eb92011-01-08 10:51:36 +0000466 < SelectTy->getBitWidth()) {
467 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000468
469 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
470 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
471 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
472 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
473 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
474 sextRHS == FalseVal) {
475 CmpLHS = TrueVal;
476 AdjustedRHS = sextRHS;
477 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
478 sextRHS == TrueVal) {
479 CmpLHS = FalseVal;
480 AdjustedRHS = sextRHS;
481 } else if (ICI->isUnsigned()) {
Frits van Bommelb686eb92011-01-08 10:51:36 +0000482 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosser46431d72011-01-07 21:33:14 +0000483 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
484 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
485 // zext + signed compare cannot be changed:
486 // 0xff <s 0x00, but 0x00ff >s 0x0000
487 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
488 zextRHS == FalseVal) {
489 CmpLHS = TrueVal;
490 AdjustedRHS = zextRHS;
491 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
492 zextRHS == TrueVal) {
493 CmpLHS = FalseVal;
494 AdjustedRHS = zextRHS;
495 } else
496 break;
497 } else
498 break;
499 } else
500 break;
501
502 Pred = ICmpInst::getSwappedPredicate(Pred);
503 CmpRHS = AdjustedRHS;
504 std::swap(FalseVal, TrueVal);
505 ICI->setPredicate(Pred);
506 ICI->setOperand(0, CmpLHS);
507 ICI->setOperand(1, CmpRHS);
508 SI.setOperand(1, TrueVal);
509 SI.setOperand(2, FalseVal);
Tobias Grosseraa2be842011-01-09 16:00:11 +0000510
511 // Move ICI instruction right before the select instruction. Otherwise
512 // the sext/zext value may be defined after the ICI instruction uses it.
513 ICI->moveBefore(&SI);
514
Tobias Grosser46431d72011-01-07 21:33:14 +0000515 Changed = true;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000516 break;
517 }
518 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000519 }
520
Benjamin Kramer1db071f2010-07-08 11:39:10 +0000521 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
522 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
523 // FIXME: Type and constness constraints could be lifted, but we have to
524 // watch code size carefully. We should consider xor instead of
525 // sub/add when we decide to do that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000526 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer1db071f2010-07-08 11:39:10 +0000527 if (TrueVal->getType() == Ty) {
528 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
529 ConstantInt *C1 = NULL, *C2 = NULL;
530 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
531 C1 = dyn_cast<ConstantInt>(TrueVal);
532 C2 = dyn_cast<ConstantInt>(FalseVal);
533 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
534 C1 = dyn_cast<ConstantInt>(FalseVal);
535 C2 = dyn_cast<ConstantInt>(TrueVal);
536 }
537 if (C1 && C2) {
538 // This shift results in either -1 or 0.
539 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
540
541 // Check if we can express the operation with a single or.
542 if (C2->isAllOnesValue())
543 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
544
545 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
546 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
547 }
548 }
549 }
550 }
551
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000552 // If we have an equality comparison then we know the value in one of the
553 // arms of the select. See if substituting this value into the arm and
554 // simplifying the result yields the same value as the other arm.
555 if (Pred == ICmpInst::ICMP_EQ) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000556 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
557 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000558 return ReplaceInstUsesWith(SI, FalseVal);
Chad Rosieraab8e282011-12-02 01:26:24 +0000559 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
560 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
Nick Lewycky11357d42011-10-02 10:37:37 +0000561 return ReplaceInstUsesWith(SI, FalseVal);
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000562 } else if (Pred == ICmpInst::ICMP_NE) {
Chad Rosieraab8e282011-12-02 01:26:24 +0000563 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
564 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000565 return ReplaceInstUsesWith(SI, TrueVal);
Chad Rosieraab8e282011-12-02 01:26:24 +0000566 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
567 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
Nick Lewycky11357d42011-10-02 10:37:37 +0000568 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000569 }
Nick Lewycky98cd7502011-03-27 07:30:57 +0000570
Benjamin Kramer17c1bb52011-05-27 13:00:16 +0000571 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
572
Benjamin Kramer37fa1c82012-05-28 19:18:16 +0000573 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky98cd7502011-03-27 07:30:57 +0000574 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
575 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
576 SI.setOperand(1, CmpRHS);
577 Changed = true;
578 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
579 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
580 SI.setOperand(2, CmpRHS);
581 Changed = true;
582 }
583 }
584
David Majnemerdefce4c2013-04-30 08:57:58 +0000585 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
586 return ReplaceInstUsesWith(SI, V);
587
Chris Lattnerc6334b92010-01-05 06:03:12 +0000588 return Changed ? &SI : 0;
589}
590
591
592/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
593/// PHI node (but the two may be in different blocks). See if the true/false
594/// values (V) are live in all of the predecessor blocks of the PHI. For
595/// example, cases like this cannot be mapped:
596///
597/// X = phi [ C1, BB1], [C2, BB2]
598/// Y = add
599/// Z = select X, Y, 0
600///
601/// because Y is not live in BB1/BB2.
602///
603static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
604 const SelectInst &SI) {
605 // If the value is a non-instruction value like a constant or argument, it
606 // can always be mapped.
607 const Instruction *I = dyn_cast<Instruction>(V);
608 if (I == 0) return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000609
Chris Lattnerc6334b92010-01-05 06:03:12 +0000610 // If V is a PHI node defined in the same block as the condition PHI, we can
611 // map the arguments.
612 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000613
Chris Lattnerc6334b92010-01-05 06:03:12 +0000614 if (const PHINode *VP = dyn_cast<PHINode>(I))
615 if (VP->getParent() == CondPHI->getParent())
616 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000617
Chris Lattnerc6334b92010-01-05 06:03:12 +0000618 // Otherwise, if the PHI and select are defined in the same block and if V is
619 // defined in a different block, then we can transform it.
620 if (SI.getParent() == CondPHI->getParent() &&
621 I->getParent() != CondPHI->getParent())
622 return true;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000623
Chris Lattnerc6334b92010-01-05 06:03:12 +0000624 // Otherwise we have a 'hard' case and we can't tell without doing more
625 // detailed dominator based analysis, punt.
626 return false;
627}
628
629/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000630/// SPF2(SPF1(A, B), C)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000631Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
632 SelectPatternFlavor SPF1,
633 Value *A, Value *B,
634 Instruction &Outer,
635 SelectPatternFlavor SPF2, Value *C) {
636 if (C == A || C == B) {
637 // MAX(MAX(A, B), B) -> MAX(A, B)
638 // MIN(MIN(a, b), a) -> MIN(a, b)
639 if (SPF1 == SPF2)
640 return ReplaceInstUsesWith(Outer, Inner);
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000641
Chris Lattnerc6334b92010-01-05 06:03:12 +0000642 // MAX(MIN(a, b), a) -> a
643 // MIN(MAX(a, b), a) -> a
644 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
645 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
646 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
647 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
648 return ReplaceInstUsesWith(Outer, C);
649 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000650
Chris Lattnerc6334b92010-01-05 06:03:12 +0000651 // TODO: MIN(MIN(A, 23), 97)
652 return 0;
653}
654
655
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000656/// foldSelectICmpAnd - If one of the constants is zero (we know they can't
657/// both be) and we have an icmp instruction with zero, and we have an 'and'
658/// with the non-constant value and a power of two we can turn the select
659/// into a shift on the result of the 'and'.
660static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
661 ConstantInt *FalseVal,
662 InstCombiner::BuilderTy *Builder) {
663 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
664 if (!IC || !IC->isEquality())
665 return 0;
Chris Lattnerc6334b92010-01-05 06:03:12 +0000666
Benjamin Kramer6b497252011-03-11 11:37:40 +0000667 if (!match(IC->getOperand(1), m_Zero()))
668 return 0;
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000669
670 ConstantInt *AndRHS;
671 Value *LHS = IC->getOperand(0);
672 if (LHS->getType() != SI.getType() ||
673 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
674 return 0;
675
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000676 // If both select arms are non-zero see if we have a select of the form
677 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
678 // for 'x ? 2^n : 0' and fix the thing up at the end.
679 ConstantInt *Offset = 0;
680 if (!TrueVal->isZero() && !FalseVal->isZero()) {
681 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
682 Offset = FalseVal;
683 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
684 Offset = TrueVal;
685 else
686 return 0;
687
688 // Adjust TrueVal and FalseVal to the offset.
689 TrueVal = ConstantInt::get(Builder->getContext(),
690 TrueVal->getValue() - Offset->getValue());
691 FalseVal = ConstantInt::get(Builder->getContext(),
692 FalseVal->getValue() - Offset->getValue());
693 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000694
695 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
696 if (!AndRHS->getValue().isPowerOf2() ||
697 (!TrueVal->getValue().isPowerOf2() &&
698 !FalseVal->getValue().isPowerOf2()))
699 return 0;
700
701 // Determine which shift is needed to transform result of the 'and' into the
702 // desired result.
703 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
704 unsigned ValZeros = ValC->getValue().logBase2();
705 unsigned AndZeros = AndRHS->getValue().logBase2();
706
707 Value *V = LHS;
708 if (ValZeros > AndZeros)
709 V = Builder->CreateShl(V, ValZeros - AndZeros);
710 else if (ValZeros < AndZeros)
711 V = Builder->CreateLShr(V, AndZeros - ValZeros);
712
713 // Okay, now we know that everything is set up, we just don't know whether we
714 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
715 bool ShouldNotVal = !TrueVal->isZero();
716 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
717 if (ShouldNotVal)
718 V = Builder->CreateXor(V, ValC);
Benjamin Kramer2f7228b2010-12-11 10:49:22 +0000719
720 // Apply an offset if needed.
721 if (Offset)
722 V = Builder->CreateAdd(V, Offset);
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000723 return V;
724}
Chris Lattnerc6334b92010-01-05 06:03:12 +0000725
726Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
727 Value *CondVal = SI.getCondition();
728 Value *TrueVal = SI.getTrueValue();
729 Value *FalseVal = SI.getFalseValue();
730
Chris Lattner04754262010-04-20 05:32:14 +0000731 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
732 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000733
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000734 if (SI.getType()->isIntegerTy(1)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000735 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
736 if (C->getZExtValue()) {
737 // Change: A = select B, true, C --> A = or B, C
738 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000739 }
Chris Lattner04754262010-04-20 05:32:14 +0000740 // Change: A = select B, false, C --> A = and !B, C
Eli Friedmane87ca452011-05-18 17:31:55 +0000741 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattner04754262010-04-20 05:32:14 +0000742 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak9affd162013-04-19 01:18:04 +0000743 }
744 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000745 if (C->getZExtValue() == false) {
746 // Change: A = select B, C, false --> A = and B, C
747 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000748 }
Chris Lattner04754262010-04-20 05:32:14 +0000749 // Change: A = select B, C, true --> A = or !B, C
Eli Friedmane87ca452011-05-18 17:31:55 +0000750 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattner04754262010-04-20 05:32:14 +0000751 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000752 }
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000753
Chris Lattnerc6334b92010-01-05 06:03:12 +0000754 // select a, b, a -> a&b
755 // select a, a, b -> a|b
756 if (CondVal == TrueVal)
757 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak9affd162013-04-19 01:18:04 +0000758 if (CondVal == FalseVal)
Chris Lattnerc6334b92010-01-05 06:03:12 +0000759 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooper4e5a1ab2011-12-15 00:56:45 +0000760
761 // select a, ~a, b -> (~a)&b
762 // select a, b, ~a -> (~a)|b
763 if (match(TrueVal, m_Not(m_Specific(CondVal))))
764 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak9affd162013-04-19 01:18:04 +0000765 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooper4e5a1ab2011-12-15 00:56:45 +0000766 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000767 }
768
769 // Selecting between two integer constants?
770 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
771 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
772 // select C, 1, 0 -> zext C to int
Chris Lattnerabb992d2010-01-24 00:09:49 +0000773 if (FalseValC->isZero() && TrueValC->getValue() == 1)
774 return new ZExtInst(CondVal, SI.getType());
775
776 // select C, -1, 0 -> sext C to int
777 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
778 return new SExtInst(CondVal, SI.getType());
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000779
Chris Lattnerabb992d2010-01-24 00:09:49 +0000780 // select C, 0, 1 -> zext !C to int
781 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
782 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
783 return new ZExtInst(NotCond, SI.getType());
Chris Lattnerc6334b92010-01-05 06:03:12 +0000784 }
785
Chris Lattnerabb992d2010-01-24 00:09:49 +0000786 // select C, 0, -1 -> sext !C to int
787 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
788 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
789 return new SExtInst(NotCond, SI.getType());
790 }
Benjamin Kramer20e3b4b2010-12-11 09:42:59 +0000791
792 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
793 return ReplaceInstUsesWith(SI, V);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000794 }
795
796 // See if we are selecting two values based on a comparison of the two values.
797 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
798 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
799 // Transform (X == Y) ? X : Y -> Y
800 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000801 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000802 // consider X== -0, Y== +0.
803 // It becomes safe if either operand is a nonzero constant.
804 ConstantFP *CFPt, *CFPf;
805 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
806 !CFPt->getValueAPF().isZero()) ||
807 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
808 !CFPf->getValueAPF().isZero()))
809 return ReplaceInstUsesWith(SI, FalseVal);
810 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000811 // Transform (X une Y) ? X : Y -> X
812 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000813 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000814 // consider X== -0, Y== +0.
815 // It becomes safe if either operand is a nonzero constant.
816 ConstantFP *CFPt, *CFPf;
817 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
818 !CFPt->getValueAPF().isZero()) ||
819 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
820 !CFPf->getValueAPF().isZero()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000821 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman21dc20c2010-02-23 17:17:57 +0000822 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000823 // NOTE: if we wanted to, this is where to detect MIN/MAX
824
825 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
826 // Transform (X == Y) ? Y : X -> X
827 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000828 // This is not safe in general for floating point:
Chris Lattnerc6334b92010-01-05 06:03:12 +0000829 // consider X== -0, Y== +0.
830 // It becomes safe if either operand is a nonzero constant.
831 ConstantFP *CFPt, *CFPf;
832 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
833 !CFPt->getValueAPF().isZero()) ||
834 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
835 !CFPf->getValueAPF().isZero()))
836 return ReplaceInstUsesWith(SI, FalseVal);
837 }
Dan Gohman21dc20c2010-02-23 17:17:57 +0000838 // Transform (X une Y) ? Y : X -> Y
839 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000840 // This is not safe in general for floating point:
Dan Gohman21dc20c2010-02-23 17:17:57 +0000841 // consider X== -0, Y== +0.
842 // It becomes safe if either operand is a nonzero constant.
843 ConstantFP *CFPt, *CFPf;
844 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
845 !CFPt->getValueAPF().isZero()) ||
846 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
847 !CFPf->getValueAPF().isZero()))
848 return ReplaceInstUsesWith(SI, TrueVal);
849 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000850 // NOTE: if we wanted to, this is where to detect MIN/MAX
851 }
852 // NOTE: if we wanted to, this is where to detect ABS
853 }
854
855 // See if we are selecting two values based on a comparison of the two values.
856 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
857 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
858 return Result;
859
860 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
861 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
862 if (TI->hasOneUse() && FI->hasOneUse()) {
863 Instruction *AddOp = 0, *SubOp = 0;
864
865 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
866 if (TI->getOpcode() == FI->getOpcode())
867 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
868 return IV;
869
870 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
871 // even legal for FP.
872 if ((TI->getOpcode() == Instruction::Sub &&
873 FI->getOpcode() == Instruction::Add) ||
874 (TI->getOpcode() == Instruction::FSub &&
875 FI->getOpcode() == Instruction::FAdd)) {
876 AddOp = FI; SubOp = TI;
877 } else if ((FI->getOpcode() == Instruction::Sub &&
878 TI->getOpcode() == Instruction::Add) ||
879 (FI->getOpcode() == Instruction::FSub &&
880 TI->getOpcode() == Instruction::FAdd)) {
881 AddOp = TI; SubOp = FI;
882 }
883
884 if (AddOp) {
885 Value *OtherAddOp = 0;
886 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
887 OtherAddOp = AddOp->getOperand(1);
888 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
889 OtherAddOp = AddOp->getOperand(0);
890 }
891
892 if (OtherAddOp) {
893 // So at this point we know we have (Y -> OtherAddOp):
894 // select C, (add X, Y), (sub X, Z)
895 Value *NegVal; // Compute -Z
Eli Friedman00805fa2011-06-23 20:40:23 +0000896 if (SI.getType()->isFPOrFPVectorTy()) {
Eli Friedman1eca76a2011-05-18 17:58:37 +0000897 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
Chris Lattnerc6334b92010-01-05 06:03:12 +0000898 } else {
Eli Friedman1eca76a2011-05-18 17:58:37 +0000899 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
Chris Lattnerc6334b92010-01-05 06:03:12 +0000900 }
901
902 Value *NewTrueOp = OtherAddOp;
903 Value *NewFalseOp = NegVal;
904 if (AddOp != TI)
905 std::swap(NewTrueOp, NewFalseOp);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000906 Value *NewSel =
Eli Friedman1eca76a2011-05-18 17:58:37 +0000907 Builder->CreateSelect(CondVal, NewTrueOp,
908 NewFalseOp, SI.getName() + ".p");
Chris Lattnerc6334b92010-01-05 06:03:12 +0000909
Eli Friedman00805fa2011-06-23 20:40:23 +0000910 if (SI.getType()->isFPOrFPVectorTy())
Dale Johannesenf514f522010-10-27 23:45:18 +0000911 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
912 else
913 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattnerc6334b92010-01-05 06:03:12 +0000914 }
915 }
916 }
917
918 // See if we can fold the select into one of our operands.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000919 if (SI.getType()->isIntegerTy()) {
Chris Lattnerc6334b92010-01-05 06:03:12 +0000920 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
921 return FoldI;
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000922
Chris Lattnerc6334b92010-01-05 06:03:12 +0000923 // MAX(MAX(a, b), a) -> MAX(a, b)
924 // MIN(MIN(a, b), a) -> MIN(a, b)
925 // MAX(MIN(a, b), a) -> a
926 // MIN(MAX(a, b), a) -> a
927 Value *LHS, *RHS, *LHS2, *RHS2;
928 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
929 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
Jim Grosbach03fceff2013-04-05 21:20:12 +0000930 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattnerc6334b92010-01-05 06:03:12 +0000931 SI, SPF, RHS))
932 return R;
933 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
934 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
935 SI, SPF, LHS))
936 return R;
937 }
938
939 // TODO.
940 // ABS(-X) -> ABS(X)
941 // ABS(ABS(X)) -> ABS(X)
942 }
943
944 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser8d088bd2011-01-07 21:33:13 +0000945 if (isa<PHINode>(SI.getCondition()))
Chris Lattnerc6334b92010-01-05 06:03:12 +0000946 // The true/false values have to be live in the PHI predecessor's blocks.
947 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
948 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
949 if (Instruction *NV = FoldOpIntoPhi(SI))
950 return NV;
951
Nick Lewyckydf3bfae2011-01-28 03:28:10 +0000952 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
953 if (TrueSI->getCondition() == CondVal) {
Nuno Lopes75564e32012-07-27 18:03:57 +0000954 if (SI.getTrueValue() == TrueSI->getTrueValue())
955 return 0;
Nick Lewyckydf3bfae2011-01-28 03:28:10 +0000956 SI.setOperand(1, TrueSI->getTrueValue());
957 return &SI;
958 }
959 }
960 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
961 if (FalseSI->getCondition() == CondVal) {
Nuno Lopes75564e32012-07-27 18:03:57 +0000962 if (SI.getFalseValue() == FalseSI->getFalseValue())
963 return 0;
Nick Lewyckydf3bfae2011-01-28 03:28:10 +0000964 SI.setOperand(2, FalseSI->getFalseValue());
965 return &SI;
966 }
967 }
968
Chris Lattnerc6334b92010-01-05 06:03:12 +0000969 if (BinaryOperator::isNot(CondVal)) {
970 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
971 SI.setOperand(1, FalseVal);
972 SI.setOperand(2, TrueVal);
973 return &SI;
974 }
Chris Lattnerc6334b92010-01-05 06:03:12 +0000975
Nick Lewycky466e0f32012-09-27 08:33:56 +0000976 if (VectorType *VecTy = dyn_cast<VectorType>(SI.getType())) {
Pete Cooper7971de42012-07-26 23:10:24 +0000977 unsigned VWidth = VecTy->getNumElements();
978 APInt UndefElts(VWidth, 0);
979 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
980 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
981 if (V != &SI)
982 return ReplaceInstUsesWith(SI, V);
983 return &SI;
984 }
Nick Lewycky466e0f32012-09-27 08:33:56 +0000985
986 if (ConstantVector *CV = dyn_cast<ConstantVector>(CondVal)) {
987 // Form a shufflevector instruction.
988 SmallVector<Constant *, 8> Mask(VWidth);
989 Type *Int32Ty = Type::getInt32Ty(CV->getContext());
990 for (unsigned i = 0; i != VWidth; ++i) {
991 Constant *Elem = cast<Constant>(CV->getOperand(i));
992 if (ConstantInt *E = dyn_cast<ConstantInt>(Elem))
993 Mask[i] = ConstantInt::get(Int32Ty, i + (E->isZero() ? VWidth : 0));
994 else if (isa<UndefValue>(Elem))
995 Mask[i] = UndefValue::get(Int32Ty);
996 else
997 return 0;
998 }
999 Constant *MaskVal = ConstantVector::get(Mask);
1000 Value *V = Builder->CreateShuffleVector(TrueVal, FalseVal, MaskVal);
1001 return ReplaceInstUsesWith(SI, V);
1002 }
Nick Lewycky7e0e1662012-09-28 09:33:53 +00001003
1004 if (isa<ConstantAggregateZero>(CondVal)) {
1005 return ReplaceInstUsesWith(SI, FalseVal);
1006 }
Pete Cooper7971de42012-07-26 23:10:24 +00001007 }
1008
Chris Lattnerc6334b92010-01-05 06:03:12 +00001009 return 0;
1010}