1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains logic for simplifying instructions based on information
10 // about how they are used.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/IR/GetElementPtrTypeIterator.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/KnownBits.h"
20 #include "llvm/Transforms/InstCombine/InstCombiner.h"
21
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
24
25 #define DEBUG_TYPE "instcombine"
26
27 /// Check to see if the specified operand of the specified instruction is a
28 /// constant integer. If so, check to see if there are any bits set in the
29 /// constant that are not demanded. If so, shrink the constant and return true.
ShrinkDemandedConstant(Instruction * I,unsigned OpNo,const APInt & Demanded)30 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
31 const APInt &Demanded) {
32 assert(I && "No instruction?");
33 assert(OpNo < I->getNumOperands() && "Operand index too large");
34
35 // The operand must be a constant integer or splat integer.
36 Value *Op = I->getOperand(OpNo);
37 const APInt *C;
38 if (!match(Op, m_APInt(C)))
39 return false;
40
41 // If there are no bits set that aren't demanded, nothing to do.
42 if (C->isSubsetOf(Demanded))
43 return false;
44
45 // This instruction is producing bits that are not demanded. Shrink the RHS.
46 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
47
48 return true;
49 }
50
51
52
53 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
54 /// the instruction has any properties that allow us to simplify its operands.
SimplifyDemandedInstructionBits(Instruction & Inst)55 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) {
56 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
57 KnownBits Known(BitWidth);
58 APInt DemandedMask(APInt::getAllOnes(BitWidth));
59
60 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
61 0, &Inst);
62 if (!V) return false;
63 if (V == &Inst) return true;
64 replaceInstUsesWith(Inst, V);
65 return true;
66 }
67
68 /// This form of SimplifyDemandedBits simplifies the specified instruction
69 /// operand if possible, updating it in place. It returns true if it made any
70 /// change and false otherwise.
SimplifyDemandedBits(Instruction * I,unsigned OpNo,const APInt & DemandedMask,KnownBits & Known,unsigned Depth)71 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
72 const APInt &DemandedMask,
73 KnownBits &Known, unsigned Depth) {
74 Use &U = I->getOperandUse(OpNo);
75 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
76 Depth, I);
77 if (!NewVal) return false;
78 if (Instruction* OpInst = dyn_cast<Instruction>(U))
79 salvageDebugInfo(*OpInst);
80
81 replaceUse(U, NewVal);
82 return true;
83 }
84
85 /// This function attempts to replace V with a simpler value based on the
86 /// demanded bits. When this function is called, it is known that only the bits
87 /// set in DemandedMask of the result of V are ever used downstream.
88 /// Consequently, depending on the mask and V, it may be possible to replace V
89 /// with a constant or one of its operands. In such cases, this function does
90 /// the replacement and returns true. In all other cases, it returns false after
91 /// analyzing the expression and setting KnownOne and known to be one in the
92 /// expression. Known.Zero contains all the bits that are known to be zero in
93 /// the expression. These are provided to potentially allow the caller (which
94 /// might recursively be SimplifyDemandedBits itself) to simplify the
95 /// expression.
96 /// Known.One and Known.Zero always follow the invariant that:
97 /// Known.One & Known.Zero == 0.
98 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
99 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
100 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
101 /// be the same.
102 ///
103 /// This returns null if it did not change anything and it permits no
104 /// simplification. This returns V itself if it did some simplification of V's
105 /// operands based on the information about what bits are demanded. This returns
106 /// some other non-null value if it found out that V is equal to another value
107 /// in the context where the specified bits are demanded, but not for all users.
SimplifyDemandedUseBits(Value * V,APInt DemandedMask,KnownBits & Known,unsigned Depth,Instruction * CxtI)108 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
109 KnownBits &Known,
110 unsigned Depth,
111 Instruction *CxtI) {
112 assert(V != nullptr && "Null pointer of Value???");
113 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
114 uint32_t BitWidth = DemandedMask.getBitWidth();
115 Type *VTy = V->getType();
116 assert(
117 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
118 Known.getBitWidth() == BitWidth &&
119 "Value *V, DemandedMask and Known must have same BitWidth");
120
121 if (isa<Constant>(V)) {
122 computeKnownBits(V, Known, Depth, CxtI);
123 return nullptr;
124 }
125
126 Known.resetAll();
127 if (DemandedMask.isZero()) // Not demanding any bits from V.
128 return UndefValue::get(VTy);
129
130 if (Depth == MaxAnalysisRecursionDepth)
131 return nullptr;
132
133 Instruction *I = dyn_cast<Instruction>(V);
134 if (!I) {
135 computeKnownBits(V, Known, Depth, CxtI);
136 return nullptr; // Only analyze instructions.
137 }
138
139 // If there are multiple uses of this value and we aren't at the root, then
140 // we can't do any simplifications of the operands, because DemandedMask
141 // only reflects the bits demanded by *one* of the users.
142 if (Depth != 0 && !I->hasOneUse())
143 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
144
145 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
146
147 // If this is the root being simplified, allow it to have multiple uses,
148 // just set the DemandedMask to all bits so that we can try to simplify the
149 // operands. This allows visitTruncInst (for example) to simplify the
150 // operand of a trunc without duplicating all the logic below.
151 if (Depth == 0 && !V->hasOneUse())
152 DemandedMask.setAllBits();
153
154 // Update flags after simplifying an operand based on the fact that some high
155 // order bits are not demanded.
156 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
157 unsigned NLZ) {
158 if (NLZ > 0) {
159 // Disable the nsw and nuw flags here: We can no longer guarantee that
160 // we won't wrap after simplification. Removing the nsw/nuw flags is
161 // legal here because the top bit is not demanded.
162 I->setHasNoSignedWrap(false);
163 I->setHasNoUnsignedWrap(false);
164 }
165 return I;
166 };
167
168 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
169 // about the high bits of the operands.
170 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
171 unsigned NLZ = DemandedMask.countLeadingZeros();
172 // Right fill the mask of bits for the operands to demand the most
173 // significant bit and all those below it.
174 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
175 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
176 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
177 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
178 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
179 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
180 return true;
181 }
182 return false;
183 };
184
185 switch (I->getOpcode()) {
186 default:
187 computeKnownBits(I, Known, Depth, CxtI);
188 break;
189 case Instruction::And: {
190 // If either the LHS or the RHS are Zero, the result is zero.
191 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
192 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
193 Depth + 1))
194 return I;
195 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
196 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
197
198 Known = LHSKnown & RHSKnown;
199
200 // If the client is only demanding bits that we know, return the known
201 // constant.
202 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
203 return Constant::getIntegerValue(VTy, Known.One);
204
205 // If all of the demanded bits are known 1 on one side, return the other.
206 // These bits cannot contribute to the result of the 'and'.
207 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
208 return I->getOperand(0);
209 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
210 return I->getOperand(1);
211
212 // If the RHS is a constant, see if we can simplify it.
213 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
214 return I;
215
216 break;
217 }
218 case Instruction::Or: {
219 // If either the LHS or the RHS are One, the result is One.
220 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
221 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
222 Depth + 1))
223 return I;
224 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
225 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
226
227 Known = LHSKnown | RHSKnown;
228
229 // If the client is only demanding bits that we know, return the known
230 // constant.
231 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
232 return Constant::getIntegerValue(VTy, Known.One);
233
234 // If all of the demanded bits are known zero on one side, return the other.
235 // These bits cannot contribute to the result of the 'or'.
236 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
237 return I->getOperand(0);
238 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
239 return I->getOperand(1);
240
241 // If the RHS is a constant, see if we can simplify it.
242 if (ShrinkDemandedConstant(I, 1, DemandedMask))
243 return I;
244
245 break;
246 }
247 case Instruction::Xor: {
248 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
249 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
250 return I;
251 Value *LHS, *RHS;
252 if (DemandedMask == 1 &&
253 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
254 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
255 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
256 IRBuilderBase::InsertPointGuard Guard(Builder);
257 Builder.SetInsertPoint(I);
258 auto *Xor = Builder.CreateXor(LHS, RHS);
259 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
260 }
261
262 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
263 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
264
265 Known = LHSKnown ^ RHSKnown;
266
267 // If the client is only demanding bits that we know, return the known
268 // constant.
269 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
270 return Constant::getIntegerValue(VTy, Known.One);
271
272 // If all of the demanded bits are known zero on one side, return the other.
273 // These bits cannot contribute to the result of the 'xor'.
274 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
275 return I->getOperand(0);
276 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
277 return I->getOperand(1);
278
279 // If all of the demanded bits are known to be zero on one side or the
280 // other, turn this into an *inclusive* or.
281 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
282 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
283 Instruction *Or =
284 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
285 I->getName());
286 return InsertNewInstWith(Or, *I);
287 }
288
289 // If all of the demanded bits on one side are known, and all of the set
290 // bits on that side are also known to be set on the other side, turn this
291 // into an AND, as we know the bits will be cleared.
292 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
293 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
294 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
295 Constant *AndC = Constant::getIntegerValue(VTy,
296 ~RHSKnown.One & DemandedMask);
297 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
298 return InsertNewInstWith(And, *I);
299 }
300
301 // If the RHS is a constant, see if we can change it. Don't alter a -1
302 // constant because that's a canonical 'not' op, and that is better for
303 // combining, SCEV, and codegen.
304 const APInt *C;
305 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
306 if ((*C | ~DemandedMask).isAllOnes()) {
307 // Force bits to 1 to create a 'not' op.
308 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
309 return I;
310 }
311 // If we can't turn this into a 'not', try to shrink the constant.
312 if (ShrinkDemandedConstant(I, 1, DemandedMask))
313 return I;
314 }
315
316 // If our LHS is an 'and' and if it has one use, and if any of the bits we
317 // are flipping are known to be set, then the xor is just resetting those
318 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
319 // simplifying both of them.
320 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
321 ConstantInt *AndRHS, *XorRHS;
322 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
323 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
324 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
325 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
326 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
327
328 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
329 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
330 InsertNewInstWith(NewAnd, *I);
331
332 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
333 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
334 return InsertNewInstWith(NewXor, *I);
335 }
336 }
337 break;
338 }
339 case Instruction::Select: {
340 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
341 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
342 return I;
343 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
344 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
345
346 // If the operands are constants, see if we can simplify them.
347 // This is similar to ShrinkDemandedConstant, but for a select we want to
348 // try to keep the selected constants the same as icmp value constants, if
349 // we can. This helps not break apart (or helps put back together)
350 // canonical patterns like min and max.
351 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
352 const APInt &DemandedMask) {
353 const APInt *SelC;
354 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
355 return false;
356
357 // Get the constant out of the ICmp, if there is one.
358 // Only try this when exactly 1 operand is a constant (if both operands
359 // are constant, the icmp should eventually simplify). Otherwise, we may
360 // invert the transform that reduces set bits and infinite-loop.
361 Value *X;
362 const APInt *CmpC;
363 ICmpInst::Predicate Pred;
364 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
365 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
366 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
367
368 // If the constant is already the same as the ICmp, leave it as-is.
369 if (*CmpC == *SelC)
370 return false;
371 // If the constants are not already the same, but can be with the demand
372 // mask, use the constant value from the ICmp.
373 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
374 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
375 return true;
376 }
377 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
378 };
379 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
380 CanonicalizeSelectConstant(I, 2, DemandedMask))
381 return I;
382
383 // Only known if known in both the LHS and RHS.
384 Known = KnownBits::commonBits(LHSKnown, RHSKnown);
385 break;
386 }
387 case Instruction::Trunc: {
388 // If we do not demand the high bits of a right-shifted and truncated value,
389 // then we may be able to truncate it before the shift.
390 Value *X;
391 const APInt *C;
392 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
393 // The shift amount must be valid (not poison) in the narrow type, and
394 // it must not be greater than the high bits demanded of the result.
395 if (C->ult(VTy->getScalarSizeInBits()) &&
396 C->ule(DemandedMask.countLeadingZeros())) {
397 // trunc (lshr X, C) --> lshr (trunc X), C
398 IRBuilderBase::InsertPointGuard Guard(Builder);
399 Builder.SetInsertPoint(I);
400 Value *Trunc = Builder.CreateTrunc(X, VTy);
401 return Builder.CreateLShr(Trunc, C->getZExtValue());
402 }
403 }
404 }
405 [[fallthrough]];
406 case Instruction::ZExt: {
407 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
408
409 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
410 KnownBits InputKnown(SrcBitWidth);
411 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
412 return I;
413 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
414 Known = InputKnown.zextOrTrunc(BitWidth);
415 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
416 break;
417 }
418 case Instruction::BitCast:
419 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
420 return nullptr; // vector->int or fp->int?
421
422 if (auto *DstVTy = dyn_cast<VectorType>(VTy)) {
423 if (auto *SrcVTy = dyn_cast<VectorType>(I->getOperand(0)->getType())) {
424 if (isa<ScalableVectorType>(DstVTy) ||
425 isa<ScalableVectorType>(SrcVTy) ||
426 cast<FixedVectorType>(DstVTy)->getNumElements() !=
427 cast<FixedVectorType>(SrcVTy)->getNumElements())
428 // Don't touch a bitcast between vectors of different element counts.
429 return nullptr;
430 } else
431 // Don't touch a scalar-to-vector bitcast.
432 return nullptr;
433 } else if (I->getOperand(0)->getType()->isVectorTy())
434 // Don't touch a vector-to-scalar bitcast.
435 return nullptr;
436
437 if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
438 return I;
439 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
440 break;
441 case Instruction::SExt: {
442 // Compute the bits in the result that are not present in the input.
443 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
444
445 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
446
447 // If any of the sign extended bits are demanded, we know that the sign
448 // bit is demanded.
449 if (DemandedMask.getActiveBits() > SrcBitWidth)
450 InputDemandedBits.setBit(SrcBitWidth-1);
451
452 KnownBits InputKnown(SrcBitWidth);
453 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
454 return I;
455
456 // If the input sign bit is known zero, or if the NewBits are not demanded
457 // convert this into a zero extension.
458 if (InputKnown.isNonNegative() ||
459 DemandedMask.getActiveBits() <= SrcBitWidth) {
460 // Convert to ZExt cast.
461 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
462 return InsertNewInstWith(NewCast, *I);
463 }
464
465 // If the sign bit of the input is known set or clear, then we know the
466 // top bits of the result.
467 Known = InputKnown.sext(BitWidth);
468 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
469 break;
470 }
471 case Instruction::Add: {
472 if ((DemandedMask & 1) == 0) {
473 // If we do not need the low bit, try to convert bool math to logic:
474 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
475 Value *X, *Y;
476 if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
477 m_OneUse(m_SExt(m_Value(Y))))) &&
478 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
479 // Truth table for inputs and output signbits:
480 // X:0 | X:1
481 // ----------
482 // Y:0 | 0 | 0 |
483 // Y:1 | -1 | 0 |
484 // ----------
485 IRBuilderBase::InsertPointGuard Guard(Builder);
486 Builder.SetInsertPoint(I);
487 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
488 return Builder.CreateSExt(AndNot, VTy);
489 }
490
491 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
492 // TODO: Relax the one-use checks because we are removing an instruction?
493 if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
494 m_OneUse(m_SExt(m_Value(Y))))) &&
495 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
496 // Truth table for inputs and output signbits:
497 // X:0 | X:1
498 // -----------
499 // Y:0 | -1 | -1 |
500 // Y:1 | -1 | 0 |
501 // -----------
502 IRBuilderBase::InsertPointGuard Guard(Builder);
503 Builder.SetInsertPoint(I);
504 Value *Or = Builder.CreateOr(X, Y);
505 return Builder.CreateSExt(Or, VTy);
506 }
507 }
508
509 // Right fill the mask of bits for the operands to demand the most
510 // significant bit and all those below it.
511 unsigned NLZ = DemandedMask.countLeadingZeros();
512 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
513 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
514 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
515 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
516
517 // If low order bits are not demanded and known to be zero in one operand,
518 // then we don't need to demand them from the other operand, since they
519 // can't cause overflow into any bits that are demanded in the result.
520 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countTrailingOnes();
521 APInt DemandedFromLHS = DemandedFromOps;
522 DemandedFromLHS.clearLowBits(NTZ);
523 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
524 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
525 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
526
527 // If we are known to be adding zeros to every bit below
528 // the highest demanded bit, we just return the other side.
529 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
530 return I->getOperand(0);
531 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
532 return I->getOperand(1);
533
534 // Otherwise just compute the known bits of the result.
535 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
536 Known = KnownBits::computeForAddSub(true, NSW, LHSKnown, RHSKnown);
537 break;
538 }
539 case Instruction::Sub: {
540 // Right fill the mask of bits for the operands to demand the most
541 // significant bit and all those below it.
542 unsigned NLZ = DemandedMask.countLeadingZeros();
543 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
544 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
545 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
546 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
547
548 // If low order bits are not demanded and are known to be zero in RHS,
549 // then we don't need to demand them from LHS, since they can't cause a
550 // borrow from any bits that are demanded in the result.
551 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countTrailingOnes();
552 APInt DemandedFromLHS = DemandedFromOps;
553 DemandedFromLHS.clearLowBits(NTZ);
554 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
555 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
556 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
557
558 // If we are known to be subtracting zeros from every bit below
559 // the highest demanded bit, we just return the other side.
560 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
561 return I->getOperand(0);
562 // We can't do this with the LHS for subtraction, unless we are only
563 // demanding the LSB.
564 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
565 return I->getOperand(1);
566
567 // Otherwise just compute the known bits of the result.
568 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
569 Known = KnownBits::computeForAddSub(false, NSW, LHSKnown, RHSKnown);
570 break;
571 }
572 case Instruction::Mul: {
573 APInt DemandedFromOps;
574 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
575 return I;
576
577 if (DemandedMask.isPowerOf2()) {
578 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
579 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
580 // odd (has LSB set), then the left-shifted low bit of X is the answer.
581 unsigned CTZ = DemandedMask.countTrailingZeros();
582 const APInt *C;
583 if (match(I->getOperand(1), m_APInt(C)) &&
584 C->countTrailingZeros() == CTZ) {
585 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
586 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
587 return InsertNewInstWith(Shl, *I);
588 }
589 }
590 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
591 // X * X is odd iff X is odd.
592 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
593 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
594 Constant *One = ConstantInt::get(VTy, 1);
595 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
596 return InsertNewInstWith(And1, *I);
597 }
598
599 computeKnownBits(I, Known, Depth, CxtI);
600 break;
601 }
602 case Instruction::Shl: {
603 const APInt *SA;
604 if (match(I->getOperand(1), m_APInt(SA))) {
605 const APInt *ShrAmt;
606 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
607 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
608 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
609 DemandedMask, Known))
610 return R;
611
612 // TODO: If we only want bits that already match the signbit then we don't
613 // need to shift.
614
615 // If we can pre-shift a right-shifted constant to the left without
616 // losing any high bits amd we don't demand the low bits, then eliminate
617 // the left-shift:
618 // (C >> X) << LeftShiftAmtC --> (C << RightShiftAmtC) >> X
619 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
620 Value *X;
621 Constant *C;
622 if (DemandedMask.countTrailingZeros() >= ShiftAmt &&
623 match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
624 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
625 Constant *NewC = ConstantExpr::getShl(C, LeftShiftAmtC);
626 if (ConstantExpr::getLShr(NewC, LeftShiftAmtC) == C) {
627 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
628 return InsertNewInstWith(Lshr, *I);
629 }
630 }
631
632 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
633
634 // If the shift is NUW/NSW, then it does demand the high bits.
635 ShlOperator *IOp = cast<ShlOperator>(I);
636 if (IOp->hasNoSignedWrap())
637 DemandedMaskIn.setHighBits(ShiftAmt+1);
638 else if (IOp->hasNoUnsignedWrap())
639 DemandedMaskIn.setHighBits(ShiftAmt);
640
641 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
642 return I;
643 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
644
645 bool SignBitZero = Known.Zero.isSignBitSet();
646 bool SignBitOne = Known.One.isSignBitSet();
647 Known.Zero <<= ShiftAmt;
648 Known.One <<= ShiftAmt;
649 // low bits known zero.
650 if (ShiftAmt)
651 Known.Zero.setLowBits(ShiftAmt);
652
653 // If this shift has "nsw" keyword, then the result is either a poison
654 // value or has the same sign bit as the first operand.
655 if (IOp->hasNoSignedWrap()) {
656 if (SignBitZero)
657 Known.Zero.setSignBit();
658 else if (SignBitOne)
659 Known.One.setSignBit();
660 if (Known.hasConflict())
661 return UndefValue::get(VTy);
662 }
663 } else {
664 // This is a variable shift, so we can't shift the demand mask by a known
665 // amount. But if we are not demanding high bits, then we are not
666 // demanding those bits from the pre-shifted operand either.
667 if (unsigned CTLZ = DemandedMask.countLeadingZeros()) {
668 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
669 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
670 // We can't guarantee that nsw/nuw hold after simplifying the operand.
671 I->dropPoisonGeneratingFlags();
672 return I;
673 }
674 }
675 computeKnownBits(I, Known, Depth, CxtI);
676 }
677 break;
678 }
679 case Instruction::LShr: {
680 const APInt *SA;
681 if (match(I->getOperand(1), m_APInt(SA))) {
682 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
683
684 // If we are just demanding the shifted sign bit and below, then this can
685 // be treated as an ASHR in disguise.
686 if (DemandedMask.countLeadingZeros() >= ShiftAmt) {
687 // If we only want bits that already match the signbit then we don't
688 // need to shift.
689 unsigned NumHiDemandedBits =
690 BitWidth - DemandedMask.countTrailingZeros();
691 unsigned SignBits =
692 ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
693 if (SignBits >= NumHiDemandedBits)
694 return I->getOperand(0);
695
696 // If we can pre-shift a left-shifted constant to the right without
697 // losing any low bits (we already know we don't demand the high bits),
698 // then eliminate the right-shift:
699 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
700 Value *X;
701 Constant *C;
702 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
703 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
704 Constant *NewC = ConstantExpr::getLShr(C, RightShiftAmtC);
705 if (ConstantExpr::getShl(NewC, RightShiftAmtC) == C) {
706 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
707 return InsertNewInstWith(Shl, *I);
708 }
709 }
710 }
711
712 // Unsigned shift right.
713 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
714
715 // If the shift is exact, then it does demand the low bits (and knows that
716 // they are zero).
717 if (cast<LShrOperator>(I)->isExact())
718 DemandedMaskIn.setLowBits(ShiftAmt);
719
720 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
721 return I;
722 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
723 Known.Zero.lshrInPlace(ShiftAmt);
724 Known.One.lshrInPlace(ShiftAmt);
725 if (ShiftAmt)
726 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
727 } else {
728 computeKnownBits(I, Known, Depth, CxtI);
729 }
730 break;
731 }
732 case Instruction::AShr: {
733 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
734
735 // If we only want bits that already match the signbit then we don't need
736 // to shift.
737 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countTrailingZeros();
738 if (SignBits >= NumHiDemandedBits)
739 return I->getOperand(0);
740
741 // If this is an arithmetic shift right and only the low-bit is set, we can
742 // always convert this into a logical shr, even if the shift amount is
743 // variable. The low bit of the shift cannot be an input sign bit unless
744 // the shift amount is >= the size of the datatype, which is undefined.
745 if (DemandedMask.isOne()) {
746 // Perform the logical shift right.
747 Instruction *NewVal = BinaryOperator::CreateLShr(
748 I->getOperand(0), I->getOperand(1), I->getName());
749 return InsertNewInstWith(NewVal, *I);
750 }
751
752 const APInt *SA;
753 if (match(I->getOperand(1), m_APInt(SA))) {
754 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
755
756 // Signed shift right.
757 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
758 // If any of the high bits are demanded, we should set the sign bit as
759 // demanded.
760 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
761 DemandedMaskIn.setSignBit();
762
763 // If the shift is exact, then it does demand the low bits (and knows that
764 // they are zero).
765 if (cast<AShrOperator>(I)->isExact())
766 DemandedMaskIn.setLowBits(ShiftAmt);
767
768 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
769 return I;
770
771 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
772 // Compute the new bits that are at the top now plus sign bits.
773 APInt HighBits(APInt::getHighBitsSet(
774 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
775 Known.Zero.lshrInPlace(ShiftAmt);
776 Known.One.lshrInPlace(ShiftAmt);
777
778 // If the input sign bit is known to be zero, or if none of the top bits
779 // are demanded, turn this into an unsigned shift right.
780 assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
781 if (Known.Zero[BitWidth-ShiftAmt-1] ||
782 !DemandedMask.intersects(HighBits)) {
783 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
784 I->getOperand(1));
785 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
786 return InsertNewInstWith(LShr, *I);
787 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
788 Known.One |= HighBits;
789 }
790 } else {
791 computeKnownBits(I, Known, Depth, CxtI);
792 }
793 break;
794 }
795 case Instruction::UDiv: {
796 // UDiv doesn't demand low bits that are zero in the divisor.
797 const APInt *SA;
798 if (match(I->getOperand(1), m_APInt(SA))) {
799 // TODO: Take the demanded mask of the result into account.
800 unsigned RHSTrailingZeros = SA->countTrailingZeros();
801 APInt DemandedMaskIn =
802 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
803 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) {
804 // We can't guarantee that "exact" is still true after changing the
805 // the dividend.
806 I->dropPoisonGeneratingFlags();
807 return I;
808 }
809
810 // Increase high zero bits from the input.
811 Known.Zero.setHighBits(std::min(
812 BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
813 } else {
814 computeKnownBits(I, Known, Depth, CxtI);
815 }
816 break;
817 }
818 case Instruction::SRem: {
819 const APInt *Rem;
820 if (match(I->getOperand(1), m_APInt(Rem))) {
821 // X % -1 demands all the bits because we don't want to introduce
822 // INT_MIN % -1 (== undef) by accident.
823 if (Rem->isAllOnes())
824 break;
825 APInt RA = Rem->abs();
826 if (RA.isPowerOf2()) {
827 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
828 return I->getOperand(0);
829
830 APInt LowBits = RA - 1;
831 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
832 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
833 return I;
834
835 // The low bits of LHS are unchanged by the srem.
836 Known.Zero = LHSKnown.Zero & LowBits;
837 Known.One = LHSKnown.One & LowBits;
838
839 // If LHS is non-negative or has all low bits zero, then the upper bits
840 // are all zero.
841 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
842 Known.Zero |= ~LowBits;
843
844 // If LHS is negative and not all low bits are zero, then the upper bits
845 // are all one.
846 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
847 Known.One |= ~LowBits;
848
849 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
850 break;
851 }
852 }
853
854 // The sign bit is the LHS's sign bit, except when the result of the
855 // remainder is zero.
856 if (DemandedMask.isSignBitSet()) {
857 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
858 // If it's known zero, our sign bit is also zero.
859 if (LHSKnown.isNonNegative())
860 Known.makeNonNegative();
861 }
862 break;
863 }
864 case Instruction::URem: {
865 KnownBits Known2(BitWidth);
866 APInt AllOnes = APInt::getAllOnes(BitWidth);
867 if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
868 SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
869 return I;
870
871 unsigned Leaders = Known2.countMinLeadingZeros();
872 Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
873 break;
874 }
875 case Instruction::Call: {
876 bool KnownBitsComputed = false;
877 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
878 switch (II->getIntrinsicID()) {
879 case Intrinsic::abs: {
880 if (DemandedMask == 1)
881 return II->getArgOperand(0);
882 break;
883 }
884 case Intrinsic::ctpop: {
885 // Checking if the number of clear bits is odd (parity)? If the type has
886 // an even number of bits, that's the same as checking if the number of
887 // set bits is odd, so we can eliminate the 'not' op.
888 Value *X;
889 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
890 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
891 Function *Ctpop = Intrinsic::getDeclaration(
892 II->getModule(), Intrinsic::ctpop, VTy);
893 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I);
894 }
895 break;
896 }
897 case Intrinsic::bswap: {
898 // If the only bits demanded come from one byte of the bswap result,
899 // just shift the input byte into position to eliminate the bswap.
900 unsigned NLZ = DemandedMask.countLeadingZeros();
901 unsigned NTZ = DemandedMask.countTrailingZeros();
902
903 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
904 // we need all the bits down to bit 8. Likewise, round NLZ. If we
905 // have 14 leading zeros, round to 8.
906 NLZ = alignDown(NLZ, 8);
907 NTZ = alignDown(NTZ, 8);
908 // If we need exactly one byte, we can do this transformation.
909 if (BitWidth - NLZ - NTZ == 8) {
910 // Replace this with either a left or right shift to get the byte into
911 // the right place.
912 Instruction *NewVal;
913 if (NLZ > NTZ)
914 NewVal = BinaryOperator::CreateLShr(
915 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
916 else
917 NewVal = BinaryOperator::CreateShl(
918 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
919 NewVal->takeName(I);
920 return InsertNewInstWith(NewVal, *I);
921 }
922 break;
923 }
924 case Intrinsic::fshr:
925 case Intrinsic::fshl: {
926 const APInt *SA;
927 if (!match(I->getOperand(2), m_APInt(SA)))
928 break;
929
930 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
931 // defined, so no need to special-case zero shifts here.
932 uint64_t ShiftAmt = SA->urem(BitWidth);
933 if (II->getIntrinsicID() == Intrinsic::fshr)
934 ShiftAmt = BitWidth - ShiftAmt;
935
936 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
937 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
938 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
939 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
940 return I;
941
942 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
943 RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
944 Known.One = LHSKnown.One.shl(ShiftAmt) |
945 RHSKnown.One.lshr(BitWidth - ShiftAmt);
946 KnownBitsComputed = true;
947 break;
948 }
949 case Intrinsic::umax: {
950 // UMax(A, C) == A if ...
951 // The lowest non-zero bit of DemandMask is higher than the highest
952 // non-zero bit of C.
953 const APInt *C;
954 unsigned CTZ = DemandedMask.countTrailingZeros();
955 if (match(II->getArgOperand(1), m_APInt(C)) &&
956 CTZ >= C->getActiveBits())
957 return II->getArgOperand(0);
958 break;
959 }
960 case Intrinsic::umin: {
961 // UMin(A, C) == A if ...
962 // The lowest non-zero bit of DemandMask is higher than the highest
963 // non-one bit of C.
964 // This comes from using DeMorgans on the above umax example.
965 const APInt *C;
966 unsigned CTZ = DemandedMask.countTrailingZeros();
967 if (match(II->getArgOperand(1), m_APInt(C)) &&
968 CTZ >= C->getBitWidth() - C->countLeadingOnes())
969 return II->getArgOperand(0);
970 break;
971 }
972 default: {
973 // Handle target specific intrinsics
974 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
975 *II, DemandedMask, Known, KnownBitsComputed);
976 if (V)
977 return *V;
978 break;
979 }
980 }
981 }
982
983 if (!KnownBitsComputed)
984 computeKnownBits(V, Known, Depth, CxtI);
985 break;
986 }
987 }
988
989 // If the client is only demanding bits that we know, return the known
990 // constant.
991 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
992 return Constant::getIntegerValue(VTy, Known.One);
993 return nullptr;
994 }
995
996 /// Helper routine of SimplifyDemandedUseBits. It computes Known
997 /// bits. It also tries to handle simplifications that can be done based on
998 /// DemandedMask, but without modifying the Instruction.
SimplifyMultipleUseDemandedBits(Instruction * I,const APInt & DemandedMask,KnownBits & Known,unsigned Depth,Instruction * CxtI)999 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
1000 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
1001 Instruction *CxtI) {
1002 unsigned BitWidth = DemandedMask.getBitWidth();
1003 Type *ITy = I->getType();
1004
1005 KnownBits LHSKnown(BitWidth);
1006 KnownBits RHSKnown(BitWidth);
1007
1008 // Despite the fact that we can't simplify this instruction in all User's
1009 // context, we can at least compute the known bits, and we can
1010 // do simplifications that apply to *just* the one user if we know that
1011 // this instruction has a simpler value in that context.
1012 switch (I->getOpcode()) {
1013 case Instruction::And: {
1014 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1015 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1016 Known = LHSKnown & RHSKnown;
1017
1018 // If the client is only demanding bits that we know, return the known
1019 // constant.
1020 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1021 return Constant::getIntegerValue(ITy, Known.One);
1022
1023 // If all of the demanded bits are known 1 on one side, return the other.
1024 // These bits cannot contribute to the result of the 'and' in this context.
1025 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1026 return I->getOperand(0);
1027 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1028 return I->getOperand(1);
1029
1030 break;
1031 }
1032 case Instruction::Or: {
1033 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1034 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1035 Known = LHSKnown | RHSKnown;
1036
1037 // If the client is only demanding bits that we know, return the known
1038 // constant.
1039 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1040 return Constant::getIntegerValue(ITy, Known.One);
1041
1042 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1043 // only bits from X or Y are demanded.
1044 // If all of the demanded bits are known zero on one side, return the other.
1045 // These bits cannot contribute to the result of the 'or' in this context.
1046 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1047 return I->getOperand(0);
1048 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1049 return I->getOperand(1);
1050
1051 break;
1052 }
1053 case Instruction::Xor: {
1054 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1055 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1056 Known = LHSKnown ^ RHSKnown;
1057
1058 // If the client is only demanding bits that we know, return the known
1059 // constant.
1060 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1061 return Constant::getIntegerValue(ITy, Known.One);
1062
1063 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1064 // only bits from X or Y are demanded.
1065 // If all of the demanded bits are known zero on one side, return the other.
1066 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1067 return I->getOperand(0);
1068 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1069 return I->getOperand(1);
1070
1071 break;
1072 }
1073 case Instruction::Add: {
1074 unsigned NLZ = DemandedMask.countLeadingZeros();
1075 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1076
1077 // If an operand adds zeros to every bit below the highest demanded bit,
1078 // that operand doesn't change the result. Return the other side.
1079 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1080 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1081 return I->getOperand(0);
1082
1083 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1084 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1085 return I->getOperand(1);
1086
1087 break;
1088 }
1089 case Instruction::Sub: {
1090 unsigned NLZ = DemandedMask.countLeadingZeros();
1091 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1092
1093 // If an operand subtracts zeros from every bit below the highest demanded
1094 // bit, that operand doesn't change the result. Return the other side.
1095 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1096 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1097 return I->getOperand(0);
1098
1099 break;
1100 }
1101 case Instruction::AShr: {
1102 // Compute the Known bits to simplify things downstream.
1103 computeKnownBits(I, Known, Depth, CxtI);
1104
1105 // If this user is only demanding bits that we know, return the known
1106 // constant.
1107 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1108 return Constant::getIntegerValue(ITy, Known.One);
1109
1110 // If the right shift operand 0 is a result of a left shift by the same
1111 // amount, this is probably a zero/sign extension, which may be unnecessary,
1112 // if we do not demand any of the new sign bits. So, return the original
1113 // operand instead.
1114 const APInt *ShiftRC;
1115 const APInt *ShiftLC;
1116 Value *X;
1117 unsigned BitWidth = DemandedMask.getBitWidth();
1118 if (match(I,
1119 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1120 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1121 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1122 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1123 return X;
1124 }
1125
1126 break;
1127 }
1128 default:
1129 // Compute the Known bits to simplify things downstream.
1130 computeKnownBits(I, Known, Depth, CxtI);
1131
1132 // If this user is only demanding bits that we know, return the known
1133 // constant.
1134 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1135 return Constant::getIntegerValue(ITy, Known.One);
1136
1137 break;
1138 }
1139
1140 return nullptr;
1141 }
1142
1143 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1144 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1145 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1146 /// of "C2-C1".
1147 ///
1148 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1149 /// ..., bn}, without considering the specific value X is holding.
1150 /// This transformation is legal iff one of following conditions is hold:
1151 /// 1) All the bit in S are 0, in this case E1 == E2.
1152 /// 2) We don't care those bits in S, per the input DemandedMask.
1153 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1154 /// rest bits.
1155 ///
1156 /// Currently we only test condition 2).
1157 ///
1158 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1159 /// not successful.
simplifyShrShlDemandedBits(Instruction * Shr,const APInt & ShrOp1,Instruction * Shl,const APInt & ShlOp1,const APInt & DemandedMask,KnownBits & Known)1160 Value *InstCombinerImpl::simplifyShrShlDemandedBits(
1161 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1162 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1163 if (!ShlOp1 || !ShrOp1)
1164 return nullptr; // No-op.
1165
1166 Value *VarX = Shr->getOperand(0);
1167 Type *Ty = VarX->getType();
1168 unsigned BitWidth = Ty->getScalarSizeInBits();
1169 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1170 return nullptr; // Undef.
1171
1172 unsigned ShlAmt = ShlOp1.getZExtValue();
1173 unsigned ShrAmt = ShrOp1.getZExtValue();
1174
1175 Known.One.clearAllBits();
1176 Known.Zero.setLowBits(ShlAmt - 1);
1177 Known.Zero &= DemandedMask;
1178
1179 APInt BitMask1(APInt::getAllOnes(BitWidth));
1180 APInt BitMask2(APInt::getAllOnes(BitWidth));
1181
1182 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1183 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1184 (BitMask1.ashr(ShrAmt) << ShlAmt);
1185
1186 if (ShrAmt <= ShlAmt) {
1187 BitMask2 <<= (ShlAmt - ShrAmt);
1188 } else {
1189 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1190 BitMask2.ashr(ShrAmt - ShlAmt);
1191 }
1192
1193 // Check if condition-2 (see the comment to this function) is satified.
1194 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1195 if (ShrAmt == ShlAmt)
1196 return VarX;
1197
1198 if (!Shr->hasOneUse())
1199 return nullptr;
1200
1201 BinaryOperator *New;
1202 if (ShrAmt < ShlAmt) {
1203 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1204 New = BinaryOperator::CreateShl(VarX, Amt);
1205 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1206 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1207 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1208 } else {
1209 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1210 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1211 BinaryOperator::CreateAShr(VarX, Amt);
1212 if (cast<BinaryOperator>(Shr)->isExact())
1213 New->setIsExact(true);
1214 }
1215
1216 return InsertNewInstWith(New, *Shl);
1217 }
1218
1219 return nullptr;
1220 }
1221
1222 /// The specified value produces a vector with any number of elements.
1223 /// This method analyzes which elements of the operand are undef or poison and
1224 /// returns that information in UndefElts.
1225 ///
1226 /// DemandedElts contains the set of elements that are actually used by the
1227 /// caller, and by default (AllowMultipleUsers equals false) the value is
1228 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1229 /// to true, DemandedElts refers to the union of sets of elements that are
1230 /// used by all callers.
1231 ///
1232 /// If the information about demanded elements can be used to simplify the
1233 /// operation, the operation is simplified, then the resultant value is
1234 /// returned. This returns null if no change was made.
SimplifyDemandedVectorElts(Value * V,APInt DemandedElts,APInt & UndefElts,unsigned Depth,bool AllowMultipleUsers)1235 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
1236 APInt DemandedElts,
1237 APInt &UndefElts,
1238 unsigned Depth,
1239 bool AllowMultipleUsers) {
1240 // Cannot analyze scalable type. The number of vector elements is not a
1241 // compile-time constant.
1242 if (isa<ScalableVectorType>(V->getType()))
1243 return nullptr;
1244
1245 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1246 APInt EltMask(APInt::getAllOnes(VWidth));
1247 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1248
1249 if (match(V, m_Undef())) {
1250 // If the entire vector is undef or poison, just return this info.
1251 UndefElts = EltMask;
1252 return nullptr;
1253 }
1254
1255 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1256 UndefElts = EltMask;
1257 return PoisonValue::get(V->getType());
1258 }
1259
1260 UndefElts = 0;
1261
1262 if (auto *C = dyn_cast<Constant>(V)) {
1263 // Check if this is identity. If so, return 0 since we are not simplifying
1264 // anything.
1265 if (DemandedElts.isAllOnes())
1266 return nullptr;
1267
1268 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1269 Constant *Poison = PoisonValue::get(EltTy);
1270 SmallVector<Constant*, 16> Elts;
1271 for (unsigned i = 0; i != VWidth; ++i) {
1272 if (!DemandedElts[i]) { // If not demanded, set to poison.
1273 Elts.push_back(Poison);
1274 UndefElts.setBit(i);
1275 continue;
1276 }
1277
1278 Constant *Elt = C->getAggregateElement(i);
1279 if (!Elt) return nullptr;
1280
1281 Elts.push_back(Elt);
1282 if (isa<UndefValue>(Elt)) // Already undef or poison.
1283 UndefElts.setBit(i);
1284 }
1285
1286 // If we changed the constant, return it.
1287 Constant *NewCV = ConstantVector::get(Elts);
1288 return NewCV != C ? NewCV : nullptr;
1289 }
1290
1291 // Limit search depth.
1292 if (Depth == 10)
1293 return nullptr;
1294
1295 if (!AllowMultipleUsers) {
1296 // If multiple users are using the root value, proceed with
1297 // simplification conservatively assuming that all elements
1298 // are needed.
1299 if (!V->hasOneUse()) {
1300 // Quit if we find multiple users of a non-root value though.
1301 // They'll be handled when it's their turn to be visited by
1302 // the main instcombine process.
1303 if (Depth != 0)
1304 // TODO: Just compute the UndefElts information recursively.
1305 return nullptr;
1306
1307 // Conservatively assume that all elements are needed.
1308 DemandedElts = EltMask;
1309 }
1310 }
1311
1312 Instruction *I = dyn_cast<Instruction>(V);
1313 if (!I) return nullptr; // Only analyze instructions.
1314
1315 bool MadeChange = false;
1316 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1317 APInt Demanded, APInt &Undef) {
1318 auto *II = dyn_cast<IntrinsicInst>(Inst);
1319 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1320 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1321 replaceOperand(*Inst, OpNum, V);
1322 MadeChange = true;
1323 }
1324 };
1325
1326 APInt UndefElts2(VWidth, 0);
1327 APInt UndefElts3(VWidth, 0);
1328 switch (I->getOpcode()) {
1329 default: break;
1330
1331 case Instruction::GetElementPtr: {
1332 // The LangRef requires that struct geps have all constant indices. As
1333 // such, we can't convert any operand to partial undef.
1334 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1335 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1336 I != E; I++)
1337 if (I.isStruct())
1338 return true;
1339 return false;
1340 };
1341 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1342 break;
1343
1344 // Conservatively track the demanded elements back through any vector
1345 // operands we may have. We know there must be at least one, or we
1346 // wouldn't have a vector result to get here. Note that we intentionally
1347 // merge the undef bits here since gepping with either an poison base or
1348 // index results in poison.
1349 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1350 if (i == 0 ? match(I->getOperand(i), m_Undef())
1351 : match(I->getOperand(i), m_Poison())) {
1352 // If the entire vector is undefined, just return this info.
1353 UndefElts = EltMask;
1354 return nullptr;
1355 }
1356 if (I->getOperand(i)->getType()->isVectorTy()) {
1357 APInt UndefEltsOp(VWidth, 0);
1358 simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1359 // gep(x, undef) is not undef, so skip considering idx ops here
1360 // Note that we could propagate poison, but we can't distinguish between
1361 // undef & poison bits ATM
1362 if (i == 0)
1363 UndefElts |= UndefEltsOp;
1364 }
1365 }
1366
1367 break;
1368 }
1369 case Instruction::InsertElement: {
1370 // If this is a variable index, we don't know which element it overwrites.
1371 // demand exactly the same input as we produce.
1372 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1373 if (!Idx) {
1374 // Note that we can't propagate undef elt info, because we don't know
1375 // which elt is getting updated.
1376 simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
1377 break;
1378 }
1379
1380 // The element inserted overwrites whatever was there, so the input demanded
1381 // set is simpler than the output set.
1382 unsigned IdxNo = Idx->getZExtValue();
1383 APInt PreInsertDemandedElts = DemandedElts;
1384 if (IdxNo < VWidth)
1385 PreInsertDemandedElts.clearBit(IdxNo);
1386
1387 // If we only demand the element that is being inserted and that element
1388 // was extracted from the same index in another vector with the same type,
1389 // replace this insert with that other vector.
1390 // Note: This is attempted before the call to simplifyAndSetOp because that
1391 // may change UndefElts to a value that does not match with Vec.
1392 Value *Vec;
1393 if (PreInsertDemandedElts == 0 &&
1394 match(I->getOperand(1),
1395 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1396 Vec->getType() == I->getType()) {
1397 return Vec;
1398 }
1399
1400 simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
1401
1402 // If this is inserting an element that isn't demanded, remove this
1403 // insertelement.
1404 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1405 Worklist.push(I);
1406 return I->getOperand(0);
1407 }
1408
1409 // The inserted element is defined.
1410 UndefElts.clearBit(IdxNo);
1411 break;
1412 }
1413 case Instruction::ShuffleVector: {
1414 auto *Shuffle = cast<ShuffleVectorInst>(I);
1415 assert(Shuffle->getOperand(0)->getType() ==
1416 Shuffle->getOperand(1)->getType() &&
1417 "Expected shuffle operands to have same type");
1418 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1419 ->getNumElements();
1420 // Handle trivial case of a splat. Only check the first element of LHS
1421 // operand.
1422 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1423 DemandedElts.isAllOnes()) {
1424 if (!match(I->getOperand(1), m_Undef())) {
1425 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1426 MadeChange = true;
1427 }
1428 APInt LeftDemanded(OpWidth, 1);
1429 APInt LHSUndefElts(OpWidth, 0);
1430 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1431 if (LHSUndefElts[0])
1432 UndefElts = EltMask;
1433 else
1434 UndefElts.clearAllBits();
1435 break;
1436 }
1437
1438 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1439 for (unsigned i = 0; i < VWidth; i++) {
1440 if (DemandedElts[i]) {
1441 unsigned MaskVal = Shuffle->getMaskValue(i);
1442 if (MaskVal != -1u) {
1443 assert(MaskVal < OpWidth * 2 &&
1444 "shufflevector mask index out of range!");
1445 if (MaskVal < OpWidth)
1446 LeftDemanded.setBit(MaskVal);
1447 else
1448 RightDemanded.setBit(MaskVal - OpWidth);
1449 }
1450 }
1451 }
1452
1453 APInt LHSUndefElts(OpWidth, 0);
1454 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1455
1456 APInt RHSUndefElts(OpWidth, 0);
1457 simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
1458
1459 // If this shuffle does not change the vector length and the elements
1460 // demanded by this shuffle are an identity mask, then this shuffle is
1461 // unnecessary.
1462 //
1463 // We are assuming canonical form for the mask, so the source vector is
1464 // operand 0 and operand 1 is not used.
1465 //
1466 // Note that if an element is demanded and this shuffle mask is undefined
1467 // for that element, then the shuffle is not considered an identity
1468 // operation. The shuffle prevents poison from the operand vector from
1469 // leaking to the result by replacing poison with an undefined value.
1470 if (VWidth == OpWidth) {
1471 bool IsIdentityShuffle = true;
1472 for (unsigned i = 0; i < VWidth; i++) {
1473 unsigned MaskVal = Shuffle->getMaskValue(i);
1474 if (DemandedElts[i] && i != MaskVal) {
1475 IsIdentityShuffle = false;
1476 break;
1477 }
1478 }
1479 if (IsIdentityShuffle)
1480 return Shuffle->getOperand(0);
1481 }
1482
1483 bool NewUndefElts = false;
1484 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1485 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1486 bool LHSUniform = true;
1487 bool RHSUniform = true;
1488 for (unsigned i = 0; i < VWidth; i++) {
1489 unsigned MaskVal = Shuffle->getMaskValue(i);
1490 if (MaskVal == -1u) {
1491 UndefElts.setBit(i);
1492 } else if (!DemandedElts[i]) {
1493 NewUndefElts = true;
1494 UndefElts.setBit(i);
1495 } else if (MaskVal < OpWidth) {
1496 if (LHSUndefElts[MaskVal]) {
1497 NewUndefElts = true;
1498 UndefElts.setBit(i);
1499 } else {
1500 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1501 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1502 LHSUniform = LHSUniform && (MaskVal == i);
1503 }
1504 } else {
1505 if (RHSUndefElts[MaskVal - OpWidth]) {
1506 NewUndefElts = true;
1507 UndefElts.setBit(i);
1508 } else {
1509 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1510 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1511 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1512 }
1513 }
1514 }
1515
1516 // Try to transform shuffle with constant vector and single element from
1517 // this constant vector to single insertelement instruction.
1518 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1519 // insertelement V, C[ci], ci-n
1520 if (OpWidth ==
1521 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1522 Value *Op = nullptr;
1523 Constant *Value = nullptr;
1524 unsigned Idx = -1u;
1525
1526 // Find constant vector with the single element in shuffle (LHS or RHS).
1527 if (LHSIdx < OpWidth && RHSUniform) {
1528 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1529 Op = Shuffle->getOperand(1);
1530 Value = CV->getOperand(LHSValIdx);
1531 Idx = LHSIdx;
1532 }
1533 }
1534 if (RHSIdx < OpWidth && LHSUniform) {
1535 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1536 Op = Shuffle->getOperand(0);
1537 Value = CV->getOperand(RHSValIdx);
1538 Idx = RHSIdx;
1539 }
1540 }
1541 // Found constant vector with single element - convert to insertelement.
1542 if (Op && Value) {
1543 Instruction *New = InsertElementInst::Create(
1544 Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
1545 Shuffle->getName());
1546 InsertNewInstWith(New, *Shuffle);
1547 return New;
1548 }
1549 }
1550 if (NewUndefElts) {
1551 // Add additional discovered undefs.
1552 SmallVector<int, 16> Elts;
1553 for (unsigned i = 0; i < VWidth; ++i) {
1554 if (UndefElts[i])
1555 Elts.push_back(UndefMaskElem);
1556 else
1557 Elts.push_back(Shuffle->getMaskValue(i));
1558 }
1559 Shuffle->setShuffleMask(Elts);
1560 MadeChange = true;
1561 }
1562 break;
1563 }
1564 case Instruction::Select: {
1565 // If this is a vector select, try to transform the select condition based
1566 // on the current demanded elements.
1567 SelectInst *Sel = cast<SelectInst>(I);
1568 if (Sel->getCondition()->getType()->isVectorTy()) {
1569 // TODO: We are not doing anything with UndefElts based on this call.
1570 // It is overwritten below based on the other select operands. If an
1571 // element of the select condition is known undef, then we are free to
1572 // choose the output value from either arm of the select. If we know that
1573 // one of those values is undef, then the output can be undef.
1574 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1575 }
1576
1577 // Next, see if we can transform the arms of the select.
1578 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1579 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 // isNullValue() always returns false when called on a ConstantExpr.
1582 // Skip constant expressions to avoid propagating incorrect information.
1583 Constant *CElt = CV->getAggregateElement(i);
1584 if (isa<ConstantExpr>(CElt))
1585 continue;
1586 // TODO: If a select condition element is undef, we can demand from
1587 // either side. If one side is known undef, choosing that side would
1588 // propagate undef.
1589 if (CElt->isNullValue())
1590 DemandedLHS.clearBit(i);
1591 else
1592 DemandedRHS.clearBit(i);
1593 }
1594 }
1595
1596 simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
1597 simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
1598
1599 // Output elements are undefined if the element from each arm is undefined.
1600 // TODO: This can be improved. See comment in select condition handling.
1601 UndefElts = UndefElts2 & UndefElts3;
1602 break;
1603 }
1604 case Instruction::BitCast: {
1605 // Vector->vector casts only.
1606 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1607 if (!VTy) break;
1608 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1609 APInt InputDemandedElts(InVWidth, 0);
1610 UndefElts2 = APInt(InVWidth, 0);
1611 unsigned Ratio;
1612
1613 if (VWidth == InVWidth) {
1614 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1615 // elements as are demanded of us.
1616 Ratio = 1;
1617 InputDemandedElts = DemandedElts;
1618 } else if ((VWidth % InVWidth) == 0) {
1619 // If the number of elements in the output is a multiple of the number of
1620 // elements in the input then an input element is live if any of the
1621 // corresponding output elements are live.
1622 Ratio = VWidth / InVWidth;
1623 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1624 if (DemandedElts[OutIdx])
1625 InputDemandedElts.setBit(OutIdx / Ratio);
1626 } else if ((InVWidth % VWidth) == 0) {
1627 // If the number of elements in the input is a multiple of the number of
1628 // elements in the output then an input element is live if the
1629 // corresponding output element is live.
1630 Ratio = InVWidth / VWidth;
1631 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1632 if (DemandedElts[InIdx / Ratio])
1633 InputDemandedElts.setBit(InIdx);
1634 } else {
1635 // Unsupported so far.
1636 break;
1637 }
1638
1639 simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
1640
1641 if (VWidth == InVWidth) {
1642 UndefElts = UndefElts2;
1643 } else if ((VWidth % InVWidth) == 0) {
1644 // If the number of elements in the output is a multiple of the number of
1645 // elements in the input then an output element is undef if the
1646 // corresponding input element is undef.
1647 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1648 if (UndefElts2[OutIdx / Ratio])
1649 UndefElts.setBit(OutIdx);
1650 } else if ((InVWidth % VWidth) == 0) {
1651 // If the number of elements in the input is a multiple of the number of
1652 // elements in the output then an output element is undef if all of the
1653 // corresponding input elements are undef.
1654 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1655 APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1656 if (SubUndef.countPopulation() == Ratio)
1657 UndefElts.setBit(OutIdx);
1658 }
1659 } else {
1660 llvm_unreachable("Unimp");
1661 }
1662 break;
1663 }
1664 case Instruction::FPTrunc:
1665 case Instruction::FPExt:
1666 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1667 break;
1668
1669 case Instruction::Call: {
1670 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1671 if (!II) break;
1672 switch (II->getIntrinsicID()) {
1673 case Intrinsic::masked_gather: // fallthrough
1674 case Intrinsic::masked_load: {
1675 // Subtlety: If we load from a pointer, the pointer must be valid
1676 // regardless of whether the element is demanded. Doing otherwise risks
1677 // segfaults which didn't exist in the original program.
1678 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1679 DemandedPassThrough(DemandedElts);
1680 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1681 for (unsigned i = 0; i < VWidth; i++) {
1682 Constant *CElt = CV->getAggregateElement(i);
1683 if (CElt->isNullValue())
1684 DemandedPtrs.clearBit(i);
1685 else if (CElt->isAllOnesValue())
1686 DemandedPassThrough.clearBit(i);
1687 }
1688 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1689 simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
1690 simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
1691
1692 // Output elements are undefined if the element from both sources are.
1693 // TODO: can strengthen via mask as well.
1694 UndefElts = UndefElts2 & UndefElts3;
1695 break;
1696 }
1697 default: {
1698 // Handle target specific intrinsics
1699 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1700 *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
1701 simplifyAndSetOp);
1702 if (V)
1703 return *V;
1704 break;
1705 }
1706 } // switch on IntrinsicID
1707 break;
1708 } // case Call
1709 } // switch on Opcode
1710
1711 // TODO: We bail completely on integer div/rem and shifts because they have
1712 // UB/poison potential, but that should be refined.
1713 BinaryOperator *BO;
1714 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1715 simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
1716 simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
1717
1718 // Output elements are undefined if both are undefined. Consider things
1719 // like undef & 0. The result is known zero, not undef.
1720 UndefElts &= UndefElts2;
1721 }
1722
1723 // If we've proven all of the lanes undef, return an undef value.
1724 // TODO: Intersect w/demanded lanes
1725 if (UndefElts.isAllOnes())
1726 return UndefValue::get(I->getType());;
1727
1728 return MadeChange ? I : nullptr;
1729 }
1730