blob: caf9e6af7d460a1fa05e60b1bd3717b9d478d1ee [file] [log] [blame]
Chris Lattner1e7b7b52010-01-05 06:05:07 +00001//===- InstCombineSelect.cpp ----------------------------------------------===//
Chris Lattner8f771cb2010-01-05 06:03:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattner1e7b7b52010-01-05 06:05:07 +000010// This file implements the visitSelect function.
Chris Lattner8f771cb2010-01-05 06:03:12 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerc707fa92010-04-20 05:32:14 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chris Lattner8f771cb2010-01-05 06:03:12 +000018using namespace llvm;
19using namespace PatternMatch;
20
Chandler Carruth964daaa2014-04-22 02:55:47 +000021#define DEBUG_TYPE "instcombine"
22
Chris Lattner8f771cb2010-01-05 06:03:12 +000023/// 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.
26static SelectPatternFlavor
27MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
28 SelectInst *SI = dyn_cast<SelectInst>(V);
Craig Topperf40110f2014-04-25 05:29:35 +000029 if (!SI) return SPF_UNKNOWN;
Tobias Grosser411e6ee2011-01-07 21:33:13 +000030
Chris Lattner8f771cb2010-01-05 06:03:12 +000031 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +000032 if (!ICI) return SPF_UNKNOWN;
Tobias Grosser411e6ee2011-01-07 21:33:13 +000033
Chris Lattner8f771cb2010-01-05 06:03:12 +000034 LHS = ICI->getOperand(0);
35 RHS = ICI->getOperand(1);
Tobias Grosser411e6ee2011-01-07 21:33:13 +000036
37 // (icmp X, Y) ? X : Y
Chris Lattner8f771cb2010-01-05 06:03:12 +000038 if (SI->getTrueValue() == ICI->getOperand(0) &&
39 SI->getFalseValue() == ICI->getOperand(1)) {
40 switch (ICI->getPredicate()) {
41 default: return SPF_UNKNOWN; // Equality.
42 case ICmpInst::ICMP_UGT:
43 case ICmpInst::ICMP_UGE: return SPF_UMAX;
44 case ICmpInst::ICMP_SGT:
45 case ICmpInst::ICMP_SGE: return SPF_SMAX;
46 case ICmpInst::ICMP_ULT:
47 case ICmpInst::ICMP_ULE: return SPF_UMIN;
48 case ICmpInst::ICMP_SLT:
49 case ICmpInst::ICMP_SLE: return SPF_SMIN;
50 }
51 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +000052
53 // (icmp X, Y) ? Y : X
Chris Lattner8f771cb2010-01-05 06:03:12 +000054 if (SI->getTrueValue() == ICI->getOperand(1) &&
55 SI->getFalseValue() == ICI->getOperand(0)) {
56 switch (ICI->getPredicate()) {
57 default: return SPF_UNKNOWN; // Equality.
58 case ICmpInst::ICMP_UGT:
59 case ICmpInst::ICMP_UGE: return SPF_UMIN;
60 case ICmpInst::ICMP_SGT:
61 case ICmpInst::ICMP_SGE: return SPF_SMIN;
62 case ICmpInst::ICMP_ULT:
63 case ICmpInst::ICMP_ULE: return SPF_UMAX;
64 case ICmpInst::ICMP_SLT:
65 case ICmpInst::ICMP_SLE: return SPF_SMAX;
66 }
67 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +000068
Chris Lattner8f771cb2010-01-05 06:03:12 +000069 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
Tobias Grosser411e6ee2011-01-07 21:33:13 +000070
Chris Lattner8f771cb2010-01-05 06:03:12 +000071 return SPF_UNKNOWN;
72}
73
74
75/// GetSelectFoldableOperands - We want to turn code that looks like this:
76/// %C = or %A, %B
77/// %D = select %cond, %C, %A
78/// into:
79/// %C = select %cond, %B, 0
80/// %D = or %A, %C
81///
82/// Assuming that the specified instruction is an operand to the select, return
83/// a bitmask indicating which operands of this instruction are foldable if they
84/// equal the other incoming value of the select.
85///
86static unsigned GetSelectFoldableOperands(Instruction *I) {
87 switch (I->getOpcode()) {
88 case Instruction::Add:
89 case Instruction::Mul:
90 case Instruction::And:
91 case Instruction::Or:
92 case Instruction::Xor:
93 return 3; // Can fold through either operand.
94 case Instruction::Sub: // Can only fold on the amount subtracted.
95 case Instruction::Shl: // Can only fold on the shift amount.
96 case Instruction::LShr:
97 case Instruction::AShr:
98 return 1;
99 default:
100 return 0; // Cannot fold
101 }
102}
103
104/// GetSelectFoldableConstant - For the same transformation as the previous
105/// function, return the identity constant that goes into the select.
106static Constant *GetSelectFoldableConstant(Instruction *I) {
107 switch (I->getOpcode()) {
108 default: llvm_unreachable("This cannot happen!");
109 case Instruction::Add:
110 case Instruction::Sub:
111 case Instruction::Or:
112 case Instruction::Xor:
113 case Instruction::Shl:
114 case Instruction::LShr:
115 case Instruction::AShr:
116 return Constant::getNullValue(I->getType());
117 case Instruction::And:
118 return Constant::getAllOnesValue(I->getType());
119 case Instruction::Mul:
120 return ConstantInt::get(I->getType(), 1);
121 }
122}
123
124/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
125/// have the same opcode and only one use each. Try to simplify this.
126Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI) {
128 if (TI->getNumOperands() == 1) {
129 // If this is a non-volatile load or a cast from the same type,
130 // merge.
131 if (TI->isCast()) {
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000132 Type *FIOpndTy = FI->getOperand(0)->getType();
133 if (TI->getOperand(0)->getType() != FIOpndTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000134 return nullptr;
Nadav Rotem4e50efe2012-06-07 20:28:57 +0000135 // The select condition may be a vector. We may only change the operand
136 // type if the vector width remains the same (and matches the condition).
137 Type *CondTy = SI.getCondition()->getType();
Akira Hatanaka99866dd2013-03-28 01:28:02 +0000138 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
139 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +0000140 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000141 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000142 return nullptr; // unknown unary op.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000143 }
144
145 // Fold this by inserting a select from the input values.
Eli Friedman2fd66442011-05-18 18:10:28 +0000146 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
147 FI->getOperand(0), SI.getName()+".v");
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000148 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Chris Lattner8f771cb2010-01-05 06:03:12 +0000149 TI->getType());
150 }
151
152 // Only handle binary operators here.
153 if (!isa<BinaryOperator>(TI))
Craig Topperf40110f2014-04-25 05:29:35 +0000154 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000155
156 // Figure out if the operations have any operands in common.
157 Value *MatchOp, *OtherOpT, *OtherOpF;
158 bool MatchIsOpZero;
159 if (TI->getOperand(0) == FI->getOperand(0)) {
160 MatchOp = TI->getOperand(0);
161 OtherOpT = TI->getOperand(1);
162 OtherOpF = FI->getOperand(1);
163 MatchIsOpZero = true;
164 } else if (TI->getOperand(1) == FI->getOperand(1)) {
165 MatchOp = TI->getOperand(1);
166 OtherOpT = TI->getOperand(0);
167 OtherOpF = FI->getOperand(0);
168 MatchIsOpZero = false;
169 } else if (!TI->isCommutative()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000170 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000171 } else if (TI->getOperand(0) == FI->getOperand(1)) {
172 MatchOp = TI->getOperand(0);
173 OtherOpT = TI->getOperand(1);
174 OtherOpF = FI->getOperand(0);
175 MatchIsOpZero = true;
176 } else if (TI->getOperand(1) == FI->getOperand(0)) {
177 MatchOp = TI->getOperand(1);
178 OtherOpT = TI->getOperand(0);
179 OtherOpF = FI->getOperand(1);
180 MatchIsOpZero = true;
181 } else {
Craig Topperf40110f2014-04-25 05:29:35 +0000182 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000183 }
184
185 // If we reach here, they do have operations in common.
Eli Friedman2fd66442011-05-18 18:10:28 +0000186 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
187 OtherOpF, SI.getName()+".v");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000188
189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
190 if (MatchIsOpZero)
191 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
192 else
193 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
194 }
195 llvm_unreachable("Shouldn't get here");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000196}
197
198static bool isSelect01(Constant *C1, Constant *C2) {
199 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
200 if (!C1I)
201 return false;
202 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
203 if (!C2I)
204 return false;
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000205 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
206 return false;
207 return C1I->isOne() || C1I->isAllOnesValue() ||
208 C2I->isOne() || C2I->isAllOnesValue();
Chris Lattner8f771cb2010-01-05 06:03:12 +0000209}
210
211/// FoldSelectIntoOp - Try fold the select into one of the operands to
212/// facilitate further optimization.
213Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
214 Value *FalseVal) {
215 // See the comment above GetSelectFoldableOperands for a description of the
216 // transformation we are doing here.
217 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
218 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
219 !isa<Constant>(FalseVal)) {
220 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
221 unsigned OpToFold = 0;
222 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
223 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000224 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000225 OpToFold = 2;
226 }
227
228 if (OpToFold) {
229 Constant *C = GetSelectFoldableConstant(TVI);
230 Value *OOp = TVI->getOperand(2-OpToFold);
231 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000232 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000234 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000235 NewSel->takeName(TVI);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000236 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000237 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
238 FalseVal, NewSel);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000239 if (isa<PossiblyExactOperator>(BO))
240 BO->setIsExact(TVI_BO->isExact());
241 if (isa<OverflowingBinaryOperator>(BO)) {
242 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
243 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
244 }
245 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000246 }
247 }
248 }
249 }
250 }
251
252 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
253 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
254 !isa<Constant>(TrueVal)) {
255 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
256 unsigned OpToFold = 0;
257 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
258 OpToFold = 1;
Nick Lewycky85442282011-03-27 19:51:23 +0000259 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000260 OpToFold = 2;
261 }
262
263 if (OpToFold) {
264 Constant *C = GetSelectFoldableConstant(FVI);
265 Value *OOp = FVI->getOperand(2-OpToFold);
266 // Avoid creating select between 2 constants unless it's selecting
Benjamin Kramer8ef50012010-12-22 23:12:15 +0000267 // between 0, 1 and -1.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000268 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
Eli Friedman2fd66442011-05-18 18:10:28 +0000269 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000270 NewSel->takeName(FVI);
Nick Lewycky85442282011-03-27 19:51:23 +0000271 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
272 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
273 TrueVal, NewSel);
Nick Lewyckyebc2f3a2011-03-28 17:48:26 +0000274 if (isa<PossiblyExactOperator>(BO))
275 BO->setIsExact(FVI_BO->isExact());
276 if (isa<OverflowingBinaryOperator>(BO)) {
277 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
278 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
279 }
280 return BO;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000281 }
282 }
283 }
284 }
285 }
286
Craig Topperf40110f2014-04-25 05:29:35 +0000287 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000288}
289
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000290/// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
291/// replaced with RepOp.
292static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000293 const DataLayout *TD,
Chad Rosier43a33062011-12-02 01:26:24 +0000294 const TargetLibraryInfo *TLI) {
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000295 // Trivial replacement.
296 if (V == Op)
297 return RepOp;
298
299 Instruction *I = dyn_cast<Instruction>(V);
300 if (!I)
Craig Topperf40110f2014-04-25 05:29:35 +0000301 return nullptr;
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000302
303 // If this is a binary operator, try to simplify it with the replaced op.
304 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
305 if (B->getOperand(0) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000306 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000307 if (B->getOperand(1) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000308 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000309 }
310
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000311 // Same for CmpInsts.
312 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
313 if (C->getOperand(0) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000314 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
315 TLI);
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000316 if (C->getOperand(1) == Op)
Chad Rosier43a33062011-12-02 01:26:24 +0000317 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
318 TLI);
Benjamin Kramerfd53a272011-05-28 10:16:58 +0000319 }
320
321 // TODO: We could hand off more cases to instsimplify here.
322
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000323 // If all operands are constant after substituting Op for RepOp then we can
324 // constant fold the instruction.
325 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
326 // Build a list of all constant operands.
327 SmallVector<Constant*, 8> ConstOps;
328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
329 if (I->getOperand(i) == Op)
330 ConstOps.push_back(CRepOp);
331 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
332 ConstOps.push_back(COp);
333 else
334 break;
335 }
336
337 // All operands were constants, fold it.
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000338 if (ConstOps.size() == I->getNumOperands()) {
Benjamin Kramerf55b5922012-10-20 08:43:52 +0000339 if (CmpInst *C = dyn_cast<CmpInst>(I))
340 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
341 ConstOps[1], TD, TLI);
342
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000343 if (LoadInst *LI = dyn_cast<LoadInst>(I))
344 if (!LI->isVolatile())
345 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
346
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000347 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Chad Rosier43a33062011-12-02 01:26:24 +0000348 ConstOps, TD, TLI);
Nick Lewycky40a34dd2011-10-02 09:12:55 +0000349 }
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000350 }
351
Craig Topperf40110f2014-04-25 05:29:35 +0000352 return nullptr;
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000353}
354
David Majnemer8d048d02013-04-30 08:57:58 +0000355/// foldSelectICmpAndOr - We want to turn:
356/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
357/// into:
358/// (or (shl (and X, C1), C3), y)
359/// iff:
360/// C1 and C2 are both powers of 2
361/// where:
362/// C3 = Log(C2) - Log(C1)
363///
364/// This transform handles cases where:
365/// 1. The icmp predicate is inverted
366/// 2. The select operands are reversed
367/// 3. The magnitude of C2 and C1 are flipped
Dinesh Dwivedi43e127b2014-06-02 07:24:36 +0000368///
369/// This also tries to turn
370/// --- Single bit tests:
371/// if ((x & C) == 0) x |= C to x |= C
372/// if ((x & C) != 0) x ^= C to x &= ~C
373/// if ((x & C) == 0) x ^= C to x |= C
374/// if ((x & C) != 0) x &= ~C to x &= ~C
375/// if ((x & C) == 0) x &= ~C to nothing
376static Value *foldSelectICmpAndOr(SelectInst &SI, Value *TrueVal,
David Majnemer8d048d02013-04-30 08:57:58 +0000377 Value *FalseVal,
378 InstCombiner::BuilderTy *Builder) {
379 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Justin Bogner4a9ac8c2013-09-27 20:35:39 +0000380 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000381 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000382
383 Value *CmpLHS = IC->getOperand(0);
384 Value *CmpRHS = IC->getOperand(1);
385
386 if (!match(CmpRHS, m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000387 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000388
389 Value *X;
390 const APInt *C1;
391 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
Craig Topperf40110f2014-04-25 05:29:35 +0000392 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000393
394 const APInt *C2;
Dinesh Dwivedi43e127b2014-06-02 07:24:36 +0000395 if (match(TrueVal, m_Specific(X))) {
396 // if ((X & C) != 0) X ^= C becomes X &= ~C
397 if (match(FalseVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2)
398 return Builder->CreateAnd(X, ~(*C1));
399 // if ((X & C) != 0) X &= ~C becomes X &= ~C
400 if (match(FalseVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2))
401 return FalseVal;
402 } else if (match(FalseVal, m_Specific(X))) {
403 // if ((X & C) == 0) X ^= C becomes X |= C
404 if (match(TrueVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2)
405 return Builder->CreateOr(X, *C1);
406 // if ((X & C) == 0) X &= ~C becomes nothing
407 if (match(TrueVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2))
408 return X;
409 // if ((X & C) == 0) X |= C becomes X |= C
410 if (match(TrueVal, m_Or(m_Specific(X), m_APInt(C2))) && C1 == C2)
411 return TrueVal;
412 }
413
Dinesh Dwivedi83c11da2014-05-15 08:22:55 +0000414 bool OrOnTrueVal = false;
415 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
416 if (!OrOnFalseVal)
417 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
David Majnemer8d048d02013-04-30 08:57:58 +0000418
419 if (!OrOnFalseVal && !OrOnTrueVal)
Craig Topperf40110f2014-04-25 05:29:35 +0000420 return nullptr;
David Majnemer8d048d02013-04-30 08:57:58 +0000421
422 Value *V = CmpLHS;
423 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
424
425 unsigned C1Log = C1->logBase2();
426 unsigned C2Log = C2->logBase2();
427 if (C2Log > C1Log) {
428 V = Builder->CreateZExtOrTrunc(V, Y->getType());
429 V = Builder->CreateShl(V, C2Log - C1Log);
430 } else if (C1Log > C2Log) {
431 V = Builder->CreateLShr(V, C1Log - C2Log);
432 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemerd73f37b2013-04-30 10:36:33 +0000433 } else
434 V = Builder->CreateZExtOrTrunc(V, Y->getType());
David Majnemer8d048d02013-04-30 08:57:58 +0000435
436 ICmpInst::Predicate Pred = IC->getPredicate();
437 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
438 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
439 V = Builder->CreateXor(V, *C2);
440
441 return Builder->CreateOr(V, Y);
442}
443
Chris Lattner8f771cb2010-01-05 06:03:12 +0000444/// visitSelectInstWithICmp - Visit a SelectInst that has an
445/// ICmpInst as its first operand.
446///
447Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
448 ICmpInst *ICI) {
449 bool Changed = false;
450 ICmpInst::Predicate Pred = ICI->getPredicate();
451 Value *CmpLHS = ICI->getOperand(0);
452 Value *CmpRHS = ICI->getOperand(1);
453 Value *TrueVal = SI.getTrueValue();
454 Value *FalseVal = SI.getFalseValue();
455
456 // Check cases where the comparison is with a constant that
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000457 // can be adjusted to fit the min/max idiom. We may move or edit ICI
458 // here, so make sure the select is the only user.
Chris Lattner8f771cb2010-01-05 06:03:12 +0000459 if (ICI->hasOneUse())
460 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000461 // X < MIN ? T : F --> F
462 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
463 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
464 return ReplaceInstUsesWith(SI, FalseVal);
465 // X > MAX ? T : F --> F
466 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
467 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
468 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000469 switch (Pred) {
470 default: break;
471 case ICmpInst::ICMP_ULT:
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000472 case ICmpInst::ICMP_SLT:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000473 case ICmpInst::ICMP_UGT:
474 case ICmpInst::ICMP_SGT: {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000475 // These transformations only work for selects over integers.
Chris Lattner229907c2011-07-18 04:54:35 +0000476 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000477 if (!SelectTy)
478 break;
479
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000480 Constant *AdjustedRHS;
481 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
482 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
483 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
484 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
485
Chris Lattner8f771cb2010-01-05 06:03:12 +0000486 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000487 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Chris Lattner8f771cb2010-01-05 06:03:12 +0000488 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000489 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
490 ; // Nothing to do here. Values match without any sign/zero extension.
491
492 // Types do not match. Instead of calculating this with mixed types
493 // promote all to the larger type. This enables scalar evolution to
494 // analyze this expression.
495 else if (CmpRHS->getType()->getScalarSizeInBits()
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000496 < SelectTy->getBitWidth()) {
497 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000498
499 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
500 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
501 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
502 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
503 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
504 sextRHS == FalseVal) {
505 CmpLHS = TrueVal;
506 AdjustedRHS = sextRHS;
507 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
508 sextRHS == TrueVal) {
509 CmpLHS = FalseVal;
510 AdjustedRHS = sextRHS;
511 } else if (ICI->isUnsigned()) {
Frits van Bommel6a1fb8f2011-01-08 10:51:36 +0000512 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000513 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
514 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
515 // zext + signed compare cannot be changed:
516 // 0xff <s 0x00, but 0x00ff >s 0x0000
517 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
518 zextRHS == FalseVal) {
519 CmpLHS = TrueVal;
520 AdjustedRHS = zextRHS;
521 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
522 zextRHS == TrueVal) {
523 CmpLHS = FalseVal;
524 AdjustedRHS = zextRHS;
525 } else
526 break;
527 } else
528 break;
529 } else
530 break;
531
532 Pred = ICmpInst::getSwappedPredicate(Pred);
533 CmpRHS = AdjustedRHS;
534 std::swap(FalseVal, TrueVal);
535 ICI->setPredicate(Pred);
536 ICI->setOperand(0, CmpLHS);
537 ICI->setOperand(1, CmpRHS);
538 SI.setOperand(1, TrueVal);
539 SI.setOperand(2, FalseVal);
Tobias Grossercc21c4a2011-01-09 16:00:11 +0000540
541 // Move ICI instruction right before the select instruction. Otherwise
542 // the sext/zext value may be defined after the ICI instruction uses it.
543 ICI->moveBefore(&SI);
544
Tobias Grosserfc3d7f62011-01-07 21:33:14 +0000545 Changed = true;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000546 break;
547 }
548 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000549 }
550
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000551 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
552 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
553 // FIXME: Type and constness constraints could be lifted, but we have to
554 // watch code size carefully. We should consider xor instead of
555 // sub/add when we decide to do that.
Chris Lattner229907c2011-07-18 04:54:35 +0000556 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000557 if (TrueVal->getType() == Ty) {
558 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000559 ConstantInt *C1 = nullptr, *C2 = nullptr;
Benjamin Kramer2321e6a2010-07-08 11:39:10 +0000560 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
561 C1 = dyn_cast<ConstantInt>(TrueVal);
562 C2 = dyn_cast<ConstantInt>(FalseVal);
563 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
564 C1 = dyn_cast<ConstantInt>(FalseVal);
565 C2 = dyn_cast<ConstantInt>(TrueVal);
566 }
567 if (C1 && C2) {
568 // This shift results in either -1 or 0.
569 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
570
571 // Check if we can express the operation with a single or.
572 if (C2->isAllOnesValue())
573 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
574
575 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
576 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
577 }
578 }
579 }
580 }
581
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000582 // If we have an equality comparison then we know the value in one of the
583 // arms of the select. See if substituting this value into the arm and
584 // simplifying the result yields the same value as the other arm.
585 if (Pred == ICmpInst::ICMP_EQ) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000586 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
587 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000588 return ReplaceInstUsesWith(SI, FalseVal);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000589 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
590 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
Nick Lewycky99fb0912011-10-02 10:37:37 +0000591 return ReplaceInstUsesWith(SI, FalseVal);
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000592 } else if (Pred == ICmpInst::ICMP_NE) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000593 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
594 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000595 return ReplaceInstUsesWith(SI, TrueVal);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000596 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
597 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
Nick Lewycky99fb0912011-10-02 10:37:37 +0000598 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000599 }
Nick Lewycky83167df2011-03-27 07:30:57 +0000600
Benjamin Kramer749ef5f2011-05-27 13:00:16 +0000601 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
602
Benjamin Kramerb8743a92012-05-28 19:18:16 +0000603 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
Nick Lewycky83167df2011-03-27 07:30:57 +0000604 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
605 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
606 SI.setOperand(1, CmpRHS);
607 Changed = true;
608 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
609 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
610 SI.setOperand(2, CmpRHS);
611 Changed = true;
612 }
613 }
614
David Majnemer8d048d02013-04-30 08:57:58 +0000615 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
616 return ReplaceInstUsesWith(SI, V);
617
Craig Topperf40110f2014-04-25 05:29:35 +0000618 return Changed ? &SI : nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000619}
620
621
622/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
623/// PHI node (but the two may be in different blocks). See if the true/false
624/// values (V) are live in all of the predecessor blocks of the PHI. For
625/// example, cases like this cannot be mapped:
626///
627/// X = phi [ C1, BB1], [C2, BB2]
628/// Y = add
629/// Z = select X, Y, 0
630///
631/// because Y is not live in BB1/BB2.
632///
633static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
634 const SelectInst &SI) {
635 // If the value is a non-instruction value like a constant or argument, it
636 // can always be mapped.
637 const Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000638 if (!I) return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000639
Chris Lattner8f771cb2010-01-05 06:03:12 +0000640 // If V is a PHI node defined in the same block as the condition PHI, we can
641 // map the arguments.
642 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000643
Chris Lattner8f771cb2010-01-05 06:03:12 +0000644 if (const PHINode *VP = dyn_cast<PHINode>(I))
645 if (VP->getParent() == CondPHI->getParent())
646 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000647
Chris Lattner8f771cb2010-01-05 06:03:12 +0000648 // Otherwise, if the PHI and select are defined in the same block and if V is
649 // defined in a different block, then we can transform it.
650 if (SI.getParent() == CondPHI->getParent() &&
651 I->getParent() != CondPHI->getParent())
652 return true;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000653
Chris Lattner8f771cb2010-01-05 06:03:12 +0000654 // Otherwise we have a 'hard' case and we can't tell without doing more
655 // detailed dominator based analysis, punt.
656 return false;
657}
658
659/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000660/// SPF2(SPF1(A, B), C)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000661Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
662 SelectPatternFlavor SPF1,
663 Value *A, Value *B,
664 Instruction &Outer,
665 SelectPatternFlavor SPF2, Value *C) {
666 if (C == A || C == B) {
667 // MAX(MAX(A, B), B) -> MAX(A, B)
668 // MIN(MIN(a, b), a) -> MIN(a, b)
669 if (SPF1 == SPF2)
670 return ReplaceInstUsesWith(Outer, Inner);
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000671
Chris Lattner8f771cb2010-01-05 06:03:12 +0000672 // MAX(MIN(a, b), a) -> a
673 // MIN(MAX(a, b), a) -> a
674 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
675 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
676 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
677 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
678 return ReplaceInstUsesWith(Outer, C);
679 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000680
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000681 if (SPF1 == SPF2) {
682 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
683 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
684 APInt ACB = CB->getValue();
685 APInt ACC = CC->getValue();
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000686
687 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
688 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000689 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
690 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
691 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
692 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
693 return ReplaceInstUsesWith(Outer, Inner);
Dinesh Dwivedif82f16e2014-05-19 07:08:32 +0000694
695 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
696 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
697 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
698 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
699 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
700 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
701 Outer.replaceUsesOfWith(Inner, A);
702 return &Outer;
703 }
Dinesh Dwivedif675f422014-05-15 06:13:40 +0000704 }
705 }
706 }
Craig Topperf40110f2014-04-25 05:29:35 +0000707 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000708}
709
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000710/// foldSelectICmpAnd - If one of the constants is zero (we know they can't
711/// both be) and we have an icmp instruction with zero, and we have an 'and'
712/// with the non-constant value and a power of two we can turn the select
713/// into a shift on the result of the 'and'.
714static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
715 ConstantInt *FalseVal,
716 InstCombiner::BuilderTy *Builder) {
717 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
Benjamin Kramer4093f292013-06-29 21:17:04 +0000718 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000719 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000720
Benjamin Kramer51897bc2011-03-11 11:37:40 +0000721 if (!match(IC->getOperand(1), m_Zero()))
Craig Topperf40110f2014-04-25 05:29:35 +0000722 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000723
724 ConstantInt *AndRHS;
725 Value *LHS = IC->getOperand(0);
Benjamin Kramer4093f292013-06-29 21:17:04 +0000726 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
Craig Topperf40110f2014-04-25 05:29:35 +0000727 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000728
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000729 // If both select arms are non-zero see if we have a select of the form
730 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
731 // for 'x ? 2^n : 0' and fix the thing up at the end.
Craig Topperf40110f2014-04-25 05:29:35 +0000732 ConstantInt *Offset = nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000733 if (!TrueVal->isZero() && !FalseVal->isZero()) {
734 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
735 Offset = FalseVal;
736 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
737 Offset = TrueVal;
738 else
Craig Topperf40110f2014-04-25 05:29:35 +0000739 return nullptr;
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000740
741 // Adjust TrueVal and FalseVal to the offset.
742 TrueVal = ConstantInt::get(Builder->getContext(),
743 TrueVal->getValue() - Offset->getValue());
744 FalseVal = ConstantInt::get(Builder->getContext(),
745 FalseVal->getValue() - Offset->getValue());
746 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000747
748 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
749 if (!AndRHS->getValue().isPowerOf2() ||
750 (!TrueVal->getValue().isPowerOf2() &&
751 !FalseVal->getValue().isPowerOf2()))
Craig Topperf40110f2014-04-25 05:29:35 +0000752 return nullptr;
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000753
754 // Determine which shift is needed to transform result of the 'and' into the
755 // desired result.
756 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
757 unsigned ValZeros = ValC->getValue().logBase2();
758 unsigned AndZeros = AndRHS->getValue().logBase2();
759
Benjamin Kramer4093f292013-06-29 21:17:04 +0000760 // If types don't match we can still convert the select by introducing a zext
761 // or a trunc of the 'and'. The trunc case requires that all of the truncated
762 // bits are zero, we can figure that out by looking at the 'and' mask.
763 if (AndZeros >= ValC->getBitWidth())
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Benjamin Kramer4093f292013-06-29 21:17:04 +0000765
766 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000767 if (ValZeros > AndZeros)
768 V = Builder->CreateShl(V, ValZeros - AndZeros);
769 else if (ValZeros < AndZeros)
770 V = Builder->CreateLShr(V, AndZeros - ValZeros);
771
772 // Okay, now we know that everything is set up, we just don't know whether we
773 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
774 bool ShouldNotVal = !TrueVal->isZero();
775 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
776 if (ShouldNotVal)
777 V = Builder->CreateXor(V, ValC);
Benjamin Kramerc4169ce2010-12-11 10:49:22 +0000778
779 // Apply an offset if needed.
780 if (Offset)
781 V = Builder->CreateAdd(V, Offset);
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000782 return V;
783}
Chris Lattner8f771cb2010-01-05 06:03:12 +0000784
785Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
786 Value *CondVal = SI.getCondition();
787 Value *TrueVal = SI.getTrueValue();
788 Value *FalseVal = SI.getFalseValue();
789
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000790 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL))
Chris Lattnerc707fa92010-04-20 05:32:14 +0000791 return ReplaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000792
Duncan Sands9dff9be2010-02-15 16:12:20 +0000793 if (SI.getType()->isIntegerTy(1)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000794 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
795 if (C->getZExtValue()) {
796 // Change: A = select B, true, C --> A = or B, C
797 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000798 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000799 // Change: A = select B, false, C --> A = and !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000800 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000801 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000802 }
803 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000804 if (C->getZExtValue() == false) {
805 // Change: A = select B, C, false --> A = and B, C
806 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000807 }
Chris Lattnerc707fa92010-04-20 05:32:14 +0000808 // Change: A = select B, C, true --> A = or !B, C
Eli Friedmancde9c162011-05-18 17:31:55 +0000809 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
Chris Lattnerc707fa92010-04-20 05:32:14 +0000810 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000811 }
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000812
Chris Lattner8f771cb2010-01-05 06:03:12 +0000813 // select a, b, a -> a&b
814 // select a, a, b -> a|b
815 if (CondVal == TrueVal)
816 return BinaryOperator::CreateOr(CondVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000817 if (CondVal == FalseVal)
Chris Lattner8f771cb2010-01-05 06:03:12 +0000818 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Pete Cooperb33c2972011-12-15 00:56:45 +0000819
820 // select a, ~a, b -> (~a)&b
821 // select a, b, ~a -> (~a)|b
822 if (match(TrueVal, m_Not(m_Specific(CondVal))))
823 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
Jakub Staszak99317262013-04-19 01:18:04 +0000824 if (match(FalseVal, m_Not(m_Specific(CondVal))))
Pete Cooperb33c2972011-12-15 00:56:45 +0000825 return BinaryOperator::CreateOr(TrueVal, FalseVal);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000826 }
827
828 // Selecting between two integer constants?
829 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
830 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
831 // select C, 1, 0 -> zext C to int
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000832 if (FalseValC->isZero() && TrueValC->getValue() == 1)
833 return new ZExtInst(CondVal, SI.getType());
834
835 // select C, -1, 0 -> sext C to int
836 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
837 return new SExtInst(CondVal, SI.getType());
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000838
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000839 // select C, 0, 1 -> zext !C to int
840 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
841 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
842 return new ZExtInst(NotCond, SI.getType());
Chris Lattner8f771cb2010-01-05 06:03:12 +0000843 }
844
Chris Lattner1b35bbe2010-01-24 00:09:49 +0000845 // select C, 0, -1 -> sext !C to int
846 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
847 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
848 return new SExtInst(NotCond, SI.getType());
849 }
Benjamin Kramerc8b035d2010-12-11 09:42:59 +0000850
851 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
852 return ReplaceInstUsesWith(SI, V);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000853 }
854
855 // See if we are selecting two values based on a comparison of the two values.
856 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
857 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
858 // Transform (X == Y) ? X : Y -> Y
859 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000860 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000861 // consider X== -0, Y== +0.
862 // It becomes safe if either operand is a nonzero constant.
863 ConstantFP *CFPt, *CFPf;
864 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
865 !CFPt->getValueAPF().isZero()) ||
866 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
867 !CFPf->getValueAPF().isZero()))
868 return ReplaceInstUsesWith(SI, FalseVal);
869 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000870 // Transform (X une Y) ? X : Y -> X
871 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000872 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000873 // consider X== -0, Y== +0.
874 // It becomes safe if either operand is a nonzero constant.
875 ConstantFP *CFPt, *CFPf;
876 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
877 !CFPt->getValueAPF().isZero()) ||
878 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
879 !CFPf->getValueAPF().isZero()))
Chris Lattner8f771cb2010-01-05 06:03:12 +0000880 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000881 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000882 // NOTE: if we wanted to, this is where to detect MIN/MAX
883
884 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
885 // Transform (X == Y) ? Y : X -> X
886 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000887 // This is not safe in general for floating point:
Chris Lattner8f771cb2010-01-05 06:03:12 +0000888 // consider X== -0, Y== +0.
889 // It becomes safe if either operand is a nonzero constant.
890 ConstantFP *CFPt, *CFPf;
891 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
892 !CFPt->getValueAPF().isZero()) ||
893 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
894 !CFPf->getValueAPF().isZero()))
895 return ReplaceInstUsesWith(SI, FalseVal);
896 }
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000897 // Transform (X une Y) ? Y : X -> Y
898 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000899 // This is not safe in general for floating point:
Dan Gohmancd4c03e2010-02-23 17:17:57 +0000900 // consider X== -0, Y== +0.
901 // It becomes safe if either operand is a nonzero constant.
902 ConstantFP *CFPt, *CFPf;
903 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
904 !CFPt->getValueAPF().isZero()) ||
905 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
906 !CFPf->getValueAPF().isZero()))
907 return ReplaceInstUsesWith(SI, TrueVal);
908 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000909 // NOTE: if we wanted to, this is where to detect MIN/MAX
910 }
911 // NOTE: if we wanted to, this is where to detect ABS
912 }
913
914 // See if we are selecting two values based on a comparison of the two values.
915 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
916 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
917 return Result;
918
919 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
920 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
921 if (TI->hasOneUse() && FI->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000922 Instruction *AddOp = nullptr, *SubOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000923
924 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
925 if (TI->getOpcode() == FI->getOpcode())
926 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
927 return IV;
928
929 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
930 // even legal for FP.
931 if ((TI->getOpcode() == Instruction::Sub &&
932 FI->getOpcode() == Instruction::Add) ||
933 (TI->getOpcode() == Instruction::FSub &&
934 FI->getOpcode() == Instruction::FAdd)) {
935 AddOp = FI; SubOp = TI;
936 } else if ((FI->getOpcode() == Instruction::Sub &&
937 TI->getOpcode() == Instruction::Add) ||
938 (FI->getOpcode() == Instruction::FSub &&
939 TI->getOpcode() == Instruction::FAdd)) {
940 AddOp = TI; SubOp = FI;
941 }
942
943 if (AddOp) {
Craig Topperf40110f2014-04-25 05:29:35 +0000944 Value *OtherAddOp = nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +0000945 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
946 OtherAddOp = AddOp->getOperand(1);
947 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
948 OtherAddOp = AddOp->getOperand(0);
949 }
950
951 if (OtherAddOp) {
952 // So at this point we know we have (Y -> OtherAddOp):
953 // select C, (add X, Y), (sub X, Z)
954 Value *NegVal; // Compute -Z
Eli Friedman2c980fa2011-06-23 20:40:23 +0000955 if (SI.getType()->isFPOrFPVectorTy()) {
Eli Friedman0b43b9e2011-05-18 17:58:37 +0000956 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
Owen Anderson48b842e2014-01-18 00:48:14 +0000957 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
958 FastMathFlags Flags = AddOp->getFastMathFlags();
959 Flags &= SubOp->getFastMathFlags();
960 NegInst->setFastMathFlags(Flags);
961 }
Chris Lattner8f771cb2010-01-05 06:03:12 +0000962 } else {
Eli Friedman0b43b9e2011-05-18 17:58:37 +0000963 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
Chris Lattner8f771cb2010-01-05 06:03:12 +0000964 }
965
966 Value *NewTrueOp = OtherAddOp;
967 Value *NewFalseOp = NegVal;
968 if (AddOp != TI)
969 std::swap(NewTrueOp, NewFalseOp);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000970 Value *NewSel =
Eli Friedman0b43b9e2011-05-18 17:58:37 +0000971 Builder->CreateSelect(CondVal, NewTrueOp,
972 NewFalseOp, SI.getName() + ".p");
Chris Lattner8f771cb2010-01-05 06:03:12 +0000973
Owen Anderson48b842e2014-01-18 00:48:14 +0000974 if (SI.getType()->isFPOrFPVectorTy()) {
975 Instruction *RI =
976 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
977
978 FastMathFlags Flags = AddOp->getFastMathFlags();
979 Flags &= SubOp->getFastMathFlags();
980 RI->setFastMathFlags(Flags);
981 return RI;
982 } else
Dale Johannesen16bb87a2010-10-27 23:45:18 +0000983 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner8f771cb2010-01-05 06:03:12 +0000984 }
985 }
986 }
987
988 // See if we can fold the select into one of our operands.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000989 if (SI.getType()->isIntegerTy()) {
Chris Lattner8f771cb2010-01-05 06:03:12 +0000990 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
991 return FoldI;
Tobias Grosser411e6ee2011-01-07 21:33:13 +0000992
Chris Lattner8f771cb2010-01-05 06:03:12 +0000993 // MAX(MAX(a, b), a) -> MAX(a, b)
994 // MIN(MIN(a, b), a) -> MIN(a, b)
995 // MAX(MIN(a, b), a) -> a
996 // MIN(MAX(a, b), a) -> a
997 Value *LHS, *RHS, *LHS2, *RHS2;
998 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
999 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001000 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
Chris Lattner8f771cb2010-01-05 06:03:12 +00001001 SI, SPF, RHS))
1002 return R;
1003 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
1004 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1005 SI, SPF, LHS))
1006 return R;
1007 }
1008
1009 // TODO.
1010 // ABS(-X) -> ABS(X)
1011 // ABS(ABS(X)) -> ABS(X)
1012 }
1013
1014 // See if we can fold the select into a phi node if the condition is a select.
Tobias Grosser411e6ee2011-01-07 21:33:13 +00001015 if (isa<PHINode>(SI.getCondition()))
Chris Lattner8f771cb2010-01-05 06:03:12 +00001016 // The true/false values have to be live in the PHI predecessor's blocks.
1017 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1018 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1019 if (Instruction *NV = FoldOpIntoPhi(SI))
1020 return NV;
1021
Nick Lewyckyb074e322011-01-28 03:28:10 +00001022 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1023 if (TrueSI->getCondition() == CondVal) {
Nuno Lopes20c7eb32012-07-27 18:03:57 +00001024 if (SI.getTrueValue() == TrueSI->getTrueValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001025 return nullptr;
Nick Lewyckyb074e322011-01-28 03:28:10 +00001026 SI.setOperand(1, TrueSI->getTrueValue());
1027 return &SI;
1028 }
1029 }
1030 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1031 if (FalseSI->getCondition() == CondVal) {
Nuno Lopes20c7eb32012-07-27 18:03:57 +00001032 if (SI.getFalseValue() == FalseSI->getFalseValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001033 return nullptr;
Nick Lewyckyb074e322011-01-28 03:28:10 +00001034 SI.setOperand(2, FalseSI->getFalseValue());
1035 return &SI;
1036 }
1037 }
1038
Chris Lattner8f771cb2010-01-05 06:03:12 +00001039 if (BinaryOperator::isNot(CondVal)) {
1040 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1041 SI.setOperand(1, FalseVal);
1042 SI.setOperand(2, TrueVal);
1043 return &SI;
1044 }
Chris Lattner8f771cb2010-01-05 06:03:12 +00001045
Nadav Rotemc70ef4e2013-05-06 02:39:09 +00001046 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
Pete Cooperabc13af2012-07-26 23:10:24 +00001047 unsigned VWidth = VecTy->getNumElements();
1048 APInt UndefElts(VWidth, 0);
1049 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1050 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1051 if (V != &SI)
1052 return ReplaceInstUsesWith(SI, V);
1053 return &SI;
1054 }
Nick Lewycky7b4cd222012-09-27 08:33:56 +00001055
Nick Lewycky156999f2012-09-28 09:33:53 +00001056 if (isa<ConstantAggregateZero>(CondVal)) {
1057 return ReplaceInstUsesWith(SI, FalseVal);
1058 }
Pete Cooperabc13af2012-07-26 23:10:24 +00001059 }
1060
Craig Topperf40110f2014-04-25 05:29:35 +00001061 return nullptr;
Chris Lattner8f771cb2010-01-05 06:03:12 +00001062}