LLVM 19.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
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"
21
22using namespace llvm;
23using namespace llvm::PatternMatch;
24
25#define DEBUG_TYPE "instcombine"
26
27static cl::opt<bool>
28 VerifyKnownBits("instcombine-verify-known-bits",
29 cl::desc("Verify that computeKnownBits() and "
30 "SimplifyDemandedBits() are consistent"),
31 cl::Hidden, cl::init(false));
32
33/// Check to see if the specified operand of the specified instruction is a
34/// constant integer. If so, check to see if there are any bits set in the
35/// constant that are not demanded. If so, shrink the constant and return true.
36static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
37 const APInt &Demanded) {
38 assert(I && "No instruction?");
39 assert(OpNo < I->getNumOperands() && "Operand index too large");
40
41 // The operand must be a constant integer or splat integer.
42 Value *Op = I->getOperand(OpNo);
43 const APInt *C;
44 if (!match(Op, m_APInt(C)))
45 return false;
46
47 // If there are no bits set that aren't demanded, nothing to do.
48 if (C->isSubsetOf(Demanded))
49 return false;
50
51 // This instruction is producing bits that are not demanded. Shrink the RHS.
52 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
53
54 return true;
55}
56
57/// Returns the bitwidth of the given scalar or pointer type. For vector types,
58/// returns the element type's bitwidth.
59static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
60 if (unsigned BitWidth = Ty->getScalarSizeInBits())
61 return BitWidth;
62
63 return DL.getPointerTypeSizeInBits(Ty);
64}
65
66/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
67/// the instruction has any properties that allow us to simplify its operands.
69 KnownBits &Known) {
70 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
71 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
72 0, &Inst);
73 if (!V) return false;
74 if (V == &Inst) return true;
75 replaceInstUsesWith(Inst, V);
76 return true;
77}
78
79/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
80/// the instruction has any properties that allow us to simplify its operands.
82 KnownBits Known(getBitWidth(Inst.getType(), DL));
83 return SimplifyDemandedInstructionBits(Inst, Known);
84}
85
86/// This form of SimplifyDemandedBits simplifies the specified instruction
87/// operand if possible, updating it in place. It returns true if it made any
88/// change and false otherwise.
90 const APInt &DemandedMask,
91 KnownBits &Known, unsigned Depth) {
92 Use &U = I->getOperandUse(OpNo);
93 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
94 Depth, I);
95 if (!NewVal) return false;
96 if (Instruction* OpInst = dyn_cast<Instruction>(U))
97 salvageDebugInfo(*OpInst);
98
99 replaceUse(U, NewVal);
100 return true;
101}
102
103/// This function attempts to replace V with a simpler value based on the
104/// demanded bits. When this function is called, it is known that only the bits
105/// set in DemandedMask of the result of V are ever used downstream.
106/// Consequently, depending on the mask and V, it may be possible to replace V
107/// with a constant or one of its operands. In such cases, this function does
108/// the replacement and returns true. In all other cases, it returns false after
109/// analyzing the expression and setting KnownOne and known to be one in the
110/// expression. Known.Zero contains all the bits that are known to be zero in
111/// the expression. These are provided to potentially allow the caller (which
112/// might recursively be SimplifyDemandedBits itself) to simplify the
113/// expression.
114/// Known.One and Known.Zero always follow the invariant that:
115/// Known.One & Known.Zero == 0.
116/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
117/// are accurate even for bits not in DemandedMask. Note
118/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
119/// be the same.
120///
121/// This returns null if it did not change anything and it permits no
122/// simplification. This returns V itself if it did some simplification of V's
123/// operands based on the information about what bits are demanded. This returns
124/// some other non-null value if it found out that V is equal to another value
125/// in the context where the specified bits are demanded, but not for all users.
127 KnownBits &Known,
128 unsigned Depth,
129 Instruction *CxtI) {
130 assert(V != nullptr && "Null pointer of Value???");
131 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
132 uint32_t BitWidth = DemandedMask.getBitWidth();
133 Type *VTy = V->getType();
134 assert(
135 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
136 Known.getBitWidth() == BitWidth &&
137 "Value *V, DemandedMask and Known must have same BitWidth");
138
139 if (isa<Constant>(V)) {
140 computeKnownBits(V, Known, Depth, CxtI);
141 return nullptr;
142 }
143
144 Known.resetAll();
145 if (DemandedMask.isZero()) // Not demanding any bits from V.
146 return UndefValue::get(VTy);
147
149 return nullptr;
150
151 Instruction *I = dyn_cast<Instruction>(V);
152 if (!I) {
153 computeKnownBits(V, Known, Depth, CxtI);
154 return nullptr; // Only analyze instructions.
155 }
156
157 // If there are multiple uses of this value and we aren't at the root, then
158 // we can't do any simplifications of the operands, because DemandedMask
159 // only reflects the bits demanded by *one* of the users.
160 if (Depth != 0 && !I->hasOneUse())
161 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
162
163 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
164 // If this is the root being simplified, allow it to have multiple uses,
165 // just set the DemandedMask to all bits so that we can try to simplify the
166 // operands. This allows visitTruncInst (for example) to simplify the
167 // operand of a trunc without duplicating all the logic below.
168 if (Depth == 0 && !V->hasOneUse())
169 DemandedMask.setAllBits();
170
171 // Update flags after simplifying an operand based on the fact that some high
172 // order bits are not demanded.
173 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
174 unsigned NLZ) {
175 if (NLZ > 0) {
176 // Disable the nsw and nuw flags here: We can no longer guarantee that
177 // we won't wrap after simplification. Removing the nsw/nuw flags is
178 // legal here because the top bit is not demanded.
179 I->setHasNoSignedWrap(false);
180 I->setHasNoUnsignedWrap(false);
181 }
182 return I;
183 };
184
185 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
186 // about the high bits of the operands.
187 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
188 unsigned NLZ = DemandedMask.countl_zero();
189 // Right fill the mask of bits for the operands to demand the most
190 // significant bit and all those below it.
191 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
192 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
193 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
194 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
195 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
196 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
197 return true;
198 }
199 return false;
200 };
201
202 switch (I->getOpcode()) {
203 default:
204 computeKnownBits(I, Known, Depth, CxtI);
205 break;
206 case Instruction::And: {
207 // If either the LHS or the RHS are Zero, the result is zero.
208 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
209 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
210 Depth + 1))
211 return I;
212
213 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
215
216 // If the client is only demanding bits that we know, return the known
217 // constant.
218 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
219 return Constant::getIntegerValue(VTy, Known.One);
220
221 // If all of the demanded bits are known 1 on one side, return the other.
222 // These bits cannot contribute to the result of the 'and'.
223 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
224 return I->getOperand(0);
225 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
226 return I->getOperand(1);
227
228 // If the RHS is a constant, see if we can simplify it.
229 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
230 return I;
231
232 break;
233 }
234 case Instruction::Or: {
235 // If either the LHS or the RHS are One, the result is One.
236 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
237 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
238 Depth + 1)) {
239 // Disjoint flag may not longer hold.
240 I->dropPoisonGeneratingFlags();
241 return I;
242 }
243
244 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
246
247 // If the client is only demanding bits that we know, return the known
248 // constant.
249 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
250 return Constant::getIntegerValue(VTy, Known.One);
251
252 // If all of the demanded bits are known zero on one side, return the other.
253 // These bits cannot contribute to the result of the 'or'.
254 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
255 return I->getOperand(0);
256 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
257 return I->getOperand(1);
258
259 // If the RHS is a constant, see if we can simplify it.
260 if (ShrinkDemandedConstant(I, 1, DemandedMask))
261 return I;
262
263 // Infer disjoint flag if no common bits are set.
264 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
265 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
266 RHSCache(I->getOperand(1), RHSKnown);
267 if (haveNoCommonBitsSet(LHSCache, RHSCache, SQ.getWithInstruction(I))) {
268 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
269 return I;
270 }
271 }
272
273 break;
274 }
275 case Instruction::Xor: {
276 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
277 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
278 return I;
279 Value *LHS, *RHS;
280 if (DemandedMask == 1 &&
281 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
282 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
283 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
286 auto *Xor = Builder.CreateXor(LHS, RHS);
287 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
288 }
289
290 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
292
293 // If the client is only demanding bits that we know, return the known
294 // constant.
295 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
296 return Constant::getIntegerValue(VTy, Known.One);
297
298 // If all of the demanded bits are known zero on one side, return the other.
299 // These bits cannot contribute to the result of the 'xor'.
300 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
301 return I->getOperand(0);
302 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
303 return I->getOperand(1);
304
305 // If all of the demanded bits are known to be zero on one side or the
306 // other, turn this into an *inclusive* or.
307 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
308 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
309 Instruction *Or =
310 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
311 if (DemandedMask.isAllOnes())
312 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
313 Or->takeName(I);
314 return InsertNewInstWith(Or, I->getIterator());
315 }
316
317 // If all of the demanded bits on one side are known, and all of the set
318 // bits on that side are also known to be set on the other side, turn this
319 // into an AND, as we know the bits will be cleared.
320 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
321 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
322 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
324 ~RHSKnown.One & DemandedMask);
325 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
326 return InsertNewInstWith(And, I->getIterator());
327 }
328
329 // If the RHS is a constant, see if we can change it. Don't alter a -1
330 // constant because that's a canonical 'not' op, and that is better for
331 // combining, SCEV, and codegen.
332 const APInt *C;
333 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
334 if ((*C | ~DemandedMask).isAllOnes()) {
335 // Force bits to 1 to create a 'not' op.
336 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
337 return I;
338 }
339 // If we can't turn this into a 'not', try to shrink the constant.
340 if (ShrinkDemandedConstant(I, 1, DemandedMask))
341 return I;
342 }
343
344 // If our LHS is an 'and' and if it has one use, and if any of the bits we
345 // are flipping are known to be set, then the xor is just resetting those
346 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
347 // simplifying both of them.
348 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
349 ConstantInt *AndRHS, *XorRHS;
350 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
351 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
352 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
353 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
354 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
355
356 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
357 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
358 InsertNewInstWith(NewAnd, I->getIterator());
359
360 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
361 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
362 return InsertNewInstWith(NewXor, I->getIterator());
363 }
364 }
365 break;
366 }
367 case Instruction::Select: {
368 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
369 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
370 return I;
371
372 // If the operands are constants, see if we can simplify them.
373 // This is similar to ShrinkDemandedConstant, but for a select we want to
374 // try to keep the selected constants the same as icmp value constants, if
375 // we can. This helps not break apart (or helps put back together)
376 // canonical patterns like min and max.
377 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
378 const APInt &DemandedMask) {
379 const APInt *SelC;
380 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
381 return false;
382
383 // Get the constant out of the ICmp, if there is one.
384 // Only try this when exactly 1 operand is a constant (if both operands
385 // are constant, the icmp should eventually simplify). Otherwise, we may
386 // invert the transform that reduces set bits and infinite-loop.
387 Value *X;
388 const APInt *CmpC;
390 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
391 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
392 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
393
394 // If the constant is already the same as the ICmp, leave it as-is.
395 if (*CmpC == *SelC)
396 return false;
397 // If the constants are not already the same, but can be with the demand
398 // mask, use the constant value from the ICmp.
399 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
400 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
401 return true;
402 }
403 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
404 };
405 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
406 CanonicalizeSelectConstant(I, 2, DemandedMask))
407 return I;
408
409 // Only known if known in both the LHS and RHS.
410 Known = LHSKnown.intersectWith(RHSKnown);
411 break;
412 }
413 case Instruction::Trunc: {
414 // If we do not demand the high bits of a right-shifted and truncated value,
415 // then we may be able to truncate it before the shift.
416 Value *X;
417 const APInt *C;
418 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
419 // The shift amount must be valid (not poison) in the narrow type, and
420 // it must not be greater than the high bits demanded of the result.
421 if (C->ult(VTy->getScalarSizeInBits()) &&
422 C->ule(DemandedMask.countl_zero())) {
423 // trunc (lshr X, C) --> lshr (trunc X), C
426 Value *Trunc = Builder.CreateTrunc(X, VTy);
427 return Builder.CreateLShr(Trunc, C->getZExtValue());
428 }
429 }
430 }
431 [[fallthrough]];
432 case Instruction::ZExt: {
433 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
434
435 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
436 KnownBits InputKnown(SrcBitWidth);
437 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1)) {
438 // For zext nneg, we may have dropped the instruction which made the
439 // input non-negative.
440 I->dropPoisonGeneratingFlags();
441 return I;
442 }
443 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
444 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
445 !InputKnown.isNegative())
446 InputKnown.makeNonNegative();
447 Known = InputKnown.zextOrTrunc(BitWidth);
448
449 break;
450 }
451 case Instruction::SExt: {
452 // Compute the bits in the result that are not present in the input.
453 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
454
455 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
456
457 // If any of the sign extended bits are demanded, we know that the sign
458 // bit is demanded.
459 if (DemandedMask.getActiveBits() > SrcBitWidth)
460 InputDemandedBits.setBit(SrcBitWidth-1);
461
462 KnownBits InputKnown(SrcBitWidth);
463 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
464 return I;
465
466 // If the input sign bit is known zero, or if the NewBits are not demanded
467 // convert this into a zero extension.
468 if (InputKnown.isNonNegative() ||
469 DemandedMask.getActiveBits() <= SrcBitWidth) {
470 // Convert to ZExt cast.
471 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
472 NewCast->takeName(I);
473 return InsertNewInstWith(NewCast, I->getIterator());
474 }
475
476 // If the sign bit of the input is known set or clear, then we know the
477 // top bits of the result.
478 Known = InputKnown.sext(BitWidth);
479 break;
480 }
481 case Instruction::Add: {
482 if ((DemandedMask & 1) == 0) {
483 // If we do not need the low bit, try to convert bool math to logic:
484 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
485 Value *X, *Y;
487 m_OneUse(m_SExt(m_Value(Y))))) &&
488 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
489 // Truth table for inputs and output signbits:
490 // X:0 | X:1
491 // ----------
492 // Y:0 | 0 | 0 |
493 // Y:1 | -1 | 0 |
494 // ----------
498 return Builder.CreateSExt(AndNot, VTy);
499 }
500
501 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
502 // TODO: Relax the one-use checks because we are removing an instruction?
504 m_OneUse(m_SExt(m_Value(Y))))) &&
505 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
506 // Truth table for inputs and output signbits:
507 // X:0 | X:1
508 // -----------
509 // Y:0 | -1 | -1 |
510 // Y:1 | -1 | 0 |
511 // -----------
514 Value *Or = Builder.CreateOr(X, Y);
515 return Builder.CreateSExt(Or, VTy);
516 }
517 }
518
519 // Right fill the mask of bits for the operands to demand the most
520 // significant bit and all those below it.
521 unsigned NLZ = DemandedMask.countl_zero();
522 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
523 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
524 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
525 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
526
527 // If low order bits are not demanded and known to be zero in one operand,
528 // then we don't need to demand them from the other operand, since they
529 // can't cause overflow into any bits that are demanded in the result.
530 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
531 APInt DemandedFromLHS = DemandedFromOps;
532 DemandedFromLHS.clearLowBits(NTZ);
533 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
534 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
535 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
536
537 // If we are known to be adding zeros to every bit below
538 // the highest demanded bit, we just return the other side.
539 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
540 return I->getOperand(0);
541 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
542 return I->getOperand(1);
543
544 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
545 {
546 const APInt *C;
547 if (match(I->getOperand(1), m_APInt(C)) &&
548 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
551 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
552 }
553 }
554
555 // Otherwise just compute the known bits of the result.
556 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
557 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
558 Known = KnownBits::computeForAddSub(true, NSW, NUW, LHSKnown, RHSKnown);
559 break;
560 }
561 case Instruction::Sub: {
562 // Right fill the mask of bits for the operands to demand the most
563 // significant bit and all those below it.
564 unsigned NLZ = DemandedMask.countl_zero();
565 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
566 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
567 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
568 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
569
570 // If low order bits are not demanded and are known to be zero in RHS,
571 // then we don't need to demand them from LHS, since they can't cause a
572 // borrow from any bits that are demanded in the result.
573 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
574 APInt DemandedFromLHS = DemandedFromOps;
575 DemandedFromLHS.clearLowBits(NTZ);
576 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
577 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
578 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
579
580 // If we are known to be subtracting zeros from every bit below
581 // the highest demanded bit, we just return the other side.
582 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
583 return I->getOperand(0);
584 // We can't do this with the LHS for subtraction, unless we are only
585 // demanding the LSB.
586 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
587 return I->getOperand(1);
588
589 // Otherwise just compute the known bits of the result.
590 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
591 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
592 Known = KnownBits::computeForAddSub(false, NSW, NUW, LHSKnown, RHSKnown);
593 break;
594 }
595 case Instruction::Mul: {
596 APInt DemandedFromOps;
597 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
598 return I;
599
600 if (DemandedMask.isPowerOf2()) {
601 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
602 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
603 // odd (has LSB set), then the left-shifted low bit of X is the answer.
604 unsigned CTZ = DemandedMask.countr_zero();
605 const APInt *C;
606 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
607 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
608 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
609 return InsertNewInstWith(Shl, I->getIterator());
610 }
611 }
612 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
613 // X * X is odd iff X is odd.
614 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
615 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
616 Constant *One = ConstantInt::get(VTy, 1);
617 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
618 return InsertNewInstWith(And1, I->getIterator());
619 }
620
621 computeKnownBits(I, Known, Depth, CxtI);
622 break;
623 }
624 case Instruction::Shl: {
625 const APInt *SA;
626 if (match(I->getOperand(1), m_APInt(SA))) {
627 const APInt *ShrAmt;
628 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
629 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
630 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
631 DemandedMask, Known))
632 return R;
633
634 // Do not simplify if shl is part of funnel-shift pattern
635 if (I->hasOneUse()) {
636 auto *Inst = dyn_cast<Instruction>(I->user_back());
637 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
638 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
639 auto [IID, FShiftArgs] = *Opt;
640 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
641 FShiftArgs[0] == FShiftArgs[1])
642 return nullptr;
643 }
644 }
645 }
646
647 // We only want bits that already match the signbit then we don't
648 // need to shift.
649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
650 if (DemandedMask.countr_zero() >= ShiftAmt) {
651 if (I->hasNoSignedWrap()) {
652 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
653 unsigned SignBits =
654 ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
655 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
656 return I->getOperand(0);
657 }
658
659 // If we can pre-shift a right-shifted constant to the left without
660 // losing any high bits and we don't demand the low bits, then eliminate
661 // the left-shift:
662 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
663 Value *X;
664 Constant *C;
665 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
666 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
667 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
668 LeftShiftAmtC, DL);
669 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
670 LeftShiftAmtC, DL) == C) {
671 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
672 return InsertNewInstWith(Lshr, I->getIterator());
673 }
674 }
675 }
676
677 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
678
679 // If the shift is NUW/NSW, then it does demand the high bits.
680 ShlOperator *IOp = cast<ShlOperator>(I);
681 if (IOp->hasNoSignedWrap())
682 DemandedMaskIn.setHighBits(ShiftAmt+1);
683 else if (IOp->hasNoUnsignedWrap())
684 DemandedMaskIn.setHighBits(ShiftAmt);
685
686 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
687 return I;
688
689 Known = KnownBits::shl(Known,
691 /* NUW */ IOp->hasNoUnsignedWrap(),
692 /* NSW */ IOp->hasNoSignedWrap());
693 } else {
694 // This is a variable shift, so we can't shift the demand mask by a known
695 // amount. But if we are not demanding high bits, then we are not
696 // demanding those bits from the pre-shifted operand either.
697 if (unsigned CTLZ = DemandedMask.countl_zero()) {
698 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
699 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
700 // We can't guarantee that nsw/nuw hold after simplifying the operand.
701 I->dropPoisonGeneratingFlags();
702 return I;
703 }
704 }
705 computeKnownBits(I, Known, Depth, CxtI);
706 }
707 break;
708 }
709 case Instruction::LShr: {
710 const APInt *SA;
711 if (match(I->getOperand(1), m_APInt(SA))) {
712 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
713
714 // Do not simplify if lshr is part of funnel-shift pattern
715 if (I->hasOneUse()) {
716 auto *Inst = dyn_cast<Instruction>(I->user_back());
717 if (Inst && Inst->getOpcode() == BinaryOperator::Or) {
718 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
719 auto [IID, FShiftArgs] = *Opt;
720 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
721 FShiftArgs[0] == FShiftArgs[1])
722 return nullptr;
723 }
724 }
725 }
726
727 // If we are just demanding the shifted sign bit and below, then this can
728 // be treated as an ASHR in disguise.
729 if (DemandedMask.countl_zero() >= ShiftAmt) {
730 // If we only want bits that already match the signbit then we don't
731 // need to shift.
732 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
733 unsigned SignBits =
734 ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
735 if (SignBits >= NumHiDemandedBits)
736 return I->getOperand(0);
737
738 // If we can pre-shift a left-shifted constant to the right without
739 // losing any low bits (we already know we don't demand the high bits),
740 // then eliminate the right-shift:
741 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
742 Value *X;
743 Constant *C;
744 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
745 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
746 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
747 RightShiftAmtC, DL);
748 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
749 RightShiftAmtC, DL) == C) {
750 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
751 return InsertNewInstWith(Shl, I->getIterator());
752 }
753 }
754 }
755
756 // Unsigned shift right.
757 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
758 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) {
759 // exact flag may not longer hold.
760 I->dropPoisonGeneratingFlags();
761 return I;
762 }
763 Known.Zero.lshrInPlace(ShiftAmt);
764 Known.One.lshrInPlace(ShiftAmt);
765 if (ShiftAmt)
766 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
767 } else {
768 computeKnownBits(I, Known, Depth, CxtI);
769 }
770 break;
771 }
772 case Instruction::AShr: {
773 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
774
775 // If we only want bits that already match the signbit then we don't need
776 // to shift.
777 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
778 if (SignBits >= NumHiDemandedBits)
779 return I->getOperand(0);
780
781 // If this is an arithmetic shift right and only the low-bit is set, we can
782 // always convert this into a logical shr, even if the shift amount is
783 // variable. The low bit of the shift cannot be an input sign bit unless
784 // the shift amount is >= the size of the datatype, which is undefined.
785 if (DemandedMask.isOne()) {
786 // Perform the logical shift right.
787 Instruction *NewVal = BinaryOperator::CreateLShr(
788 I->getOperand(0), I->getOperand(1), I->getName());
789 return InsertNewInstWith(NewVal, I->getIterator());
790 }
791
792 const APInt *SA;
793 if (match(I->getOperand(1), m_APInt(SA))) {
794 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
795
796 // Signed shift right.
797 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
798 // If any of the high bits are demanded, we should set the sign bit as
799 // demanded.
800 if (DemandedMask.countl_zero() <= ShiftAmt)
801 DemandedMaskIn.setSignBit();
802
803 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) {
804 // exact flag may not longer hold.
805 I->dropPoisonGeneratingFlags();
806 return I;
807 }
808
809 // Compute the new bits that are at the top now plus sign bits.
811 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
812 Known.Zero.lshrInPlace(ShiftAmt);
813 Known.One.lshrInPlace(ShiftAmt);
814
815 // If the input sign bit is known to be zero, or if none of the top bits
816 // are demanded, turn this into an unsigned shift right.
817 assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
818 if (Known.Zero[BitWidth-ShiftAmt-1] ||
819 !DemandedMask.intersects(HighBits)) {
820 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
821 I->getOperand(1));
822 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
823 LShr->takeName(I);
824 return InsertNewInstWith(LShr, I->getIterator());
825 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
826 Known.One |= HighBits;
827 // SignBits may be out-of-sync with Known.countMinSignBits(). Mask out
828 // high bits of Known.Zero to avoid conflicts.
829 Known.Zero &= ~HighBits;
830 }
831 } else {
832 computeKnownBits(I, Known, Depth, CxtI);
833 }
834 break;
835 }
836 case Instruction::UDiv: {
837 // UDiv doesn't demand low bits that are zero in the divisor.
838 const APInt *SA;
839 if (match(I->getOperand(1), m_APInt(SA))) {
840 // TODO: Take the demanded mask of the result into account.
841 unsigned RHSTrailingZeros = SA->countr_zero();
842 APInt DemandedMaskIn =
843 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
844 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) {
845 // We can't guarantee that "exact" is still true after changing the
846 // the dividend.
847 I->dropPoisonGeneratingFlags();
848 return I;
849 }
850
851 Known = KnownBits::udiv(LHSKnown, KnownBits::makeConstant(*SA),
852 cast<BinaryOperator>(I)->isExact());
853 } else {
854 computeKnownBits(I, Known, Depth, CxtI);
855 }
856 break;
857 }
858 case Instruction::SRem: {
859 const APInt *Rem;
860 if (match(I->getOperand(1), m_APInt(Rem))) {
861 // X % -1 demands all the bits because we don't want to introduce
862 // INT_MIN % -1 (== undef) by accident.
863 if (Rem->isAllOnes())
864 break;
865 APInt RA = Rem->abs();
866 if (RA.isPowerOf2()) {
867 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
868 return I->getOperand(0);
869
870 APInt LowBits = RA - 1;
871 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
872 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
873 return I;
874
875 // The low bits of LHS are unchanged by the srem.
876 Known.Zero = LHSKnown.Zero & LowBits;
877 Known.One = LHSKnown.One & LowBits;
878
879 // If LHS is non-negative or has all low bits zero, then the upper bits
880 // are all zero.
881 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
882 Known.Zero |= ~LowBits;
883
884 // If LHS is negative and not all low bits are zero, then the upper bits
885 // are all one.
886 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
887 Known.One |= ~LowBits;
888
889 break;
890 }
891 }
892
893 computeKnownBits(I, Known, Depth, CxtI);
894 break;
895 }
896 case Instruction::URem: {
898 if (SimplifyDemandedBits(I, 0, AllOnes, LHSKnown, Depth + 1) ||
899 SimplifyDemandedBits(I, 1, AllOnes, RHSKnown, Depth + 1))
900 return I;
901
902 Known = KnownBits::urem(LHSKnown, RHSKnown);
903 break;
904 }
905 case Instruction::Call: {
906 bool KnownBitsComputed = false;
907 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
908 switch (II->getIntrinsicID()) {
909 case Intrinsic::abs: {
910 if (DemandedMask == 1)
911 return II->getArgOperand(0);
912 break;
913 }
914 case Intrinsic::ctpop: {
915 // Checking if the number of clear bits is odd (parity)? If the type has
916 // an even number of bits, that's the same as checking if the number of
917 // set bits is odd, so we can eliminate the 'not' op.
918 Value *X;
919 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
920 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
922 II->getModule(), Intrinsic::ctpop, VTy);
923 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
924 }
925 break;
926 }
927 case Intrinsic::bswap: {
928 // If the only bits demanded come from one byte of the bswap result,
929 // just shift the input byte into position to eliminate the bswap.
930 unsigned NLZ = DemandedMask.countl_zero();
931 unsigned NTZ = DemandedMask.countr_zero();
932
933 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
934 // we need all the bits down to bit 8. Likewise, round NLZ. If we
935 // have 14 leading zeros, round to 8.
936 NLZ = alignDown(NLZ, 8);
937 NTZ = alignDown(NTZ, 8);
938 // If we need exactly one byte, we can do this transformation.
939 if (BitWidth - NLZ - NTZ == 8) {
940 // Replace this with either a left or right shift to get the byte into
941 // the right place.
942 Instruction *NewVal;
943 if (NLZ > NTZ)
944 NewVal = BinaryOperator::CreateLShr(
945 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
946 else
947 NewVal = BinaryOperator::CreateShl(
948 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
949 NewVal->takeName(I);
950 return InsertNewInstWith(NewVal, I->getIterator());
951 }
952 break;
953 }
954 case Intrinsic::ptrmask: {
955 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
956 RHSKnown = KnownBits(MaskWidth);
957 // If either the LHS or the RHS are Zero, the result is zero.
958 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1) ||
960 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
961 RHSKnown, Depth + 1))
962 return I;
963
964 // TODO: Should be 1-extend
965 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
966
967 Known = LHSKnown & RHSKnown;
968 KnownBitsComputed = true;
969
970 // If the client is only demanding bits we know to be zero, return
971 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
972 // provenance, but making the mask zero will be easily optimizable in
973 // the backend.
974 if (DemandedMask.isSubsetOf(Known.Zero) &&
975 !match(I->getOperand(1), m_Zero()))
976 return replaceOperand(
977 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
978
979 // Mask in demanded space does nothing.
980 // NOTE: We may have attributes associated with the return value of the
981 // llvm.ptrmask intrinsic that will be lost when we just return the
982 // operand. We should try to preserve them.
983 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
984 return I->getOperand(0);
985
986 // If the RHS is a constant, see if we can simplify it.
988 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
989 return I;
990
991 // Combine:
992 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
993 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
994 // where only the low bits known to be zero in the pointer are changed
995 Value *InnerPtr;
996 uint64_t GEPIndex;
997 uint64_t PtrMaskImmediate;
998 if (match(I, m_Intrinsic<Intrinsic::ptrmask>(
999 m_PtrAdd(m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
1000 m_ConstantInt(PtrMaskImmediate)))) {
1001
1002 LHSKnown = computeKnownBits(InnerPtr, Depth + 1, I);
1003 if (!LHSKnown.isZero()) {
1004 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1005 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1006
1007 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1008 uint64_t MaskedLowBitsGEPIndex =
1009 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1010
1011 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1012
1013 if (MaskedGEPIndex != GEPIndex) {
1014 auto *GEP = cast<GetElementPtrInst>(II->getArgOperand(0));
1016 Type *GEPIndexType =
1017 DL.getIndexType(GEP->getPointerOperand()->getType());
1018 Value *MaskedGEP = Builder.CreateGEP(
1019 GEP->getSourceElementType(), InnerPtr,
1020 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1021 GEP->getName(), GEP->isInBounds());
1022
1023 replaceOperand(*I, 0, MaskedGEP);
1024 return I;
1025 }
1026 }
1027 }
1028
1029 break;
1030 }
1031
1032 case Intrinsic::fshr:
1033 case Intrinsic::fshl: {
1034 const APInt *SA;
1035 if (!match(I->getOperand(2), m_APInt(SA)))
1036 break;
1037
1038 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1039 // defined, so no need to special-case zero shifts here.
1040 uint64_t ShiftAmt = SA->urem(BitWidth);
1041 if (II->getIntrinsicID() == Intrinsic::fshr)
1042 ShiftAmt = BitWidth - ShiftAmt;
1043
1044 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1045 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1046 if (I->getOperand(0) != I->getOperand(1)) {
1047 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown,
1048 Depth + 1) ||
1049 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
1050 return I;
1051 } else { // fshl is a rotate
1052 // Avoid converting rotate into funnel shift.
1053 // Only simplify if one operand is constant.
1054 LHSKnown = computeKnownBits(I->getOperand(0), Depth + 1, I);
1055 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1056 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1057 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1058 return I;
1059 }
1060
1061 RHSKnown = computeKnownBits(I->getOperand(1), Depth + 1, I);
1062 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1063 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1064 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1065 return I;
1066 }
1067 }
1068
1069 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
1070 RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
1071 Known.One = LHSKnown.One.shl(ShiftAmt) |
1072 RHSKnown.One.lshr(BitWidth - ShiftAmt);
1073 KnownBitsComputed = true;
1074 break;
1075 }
1076 case Intrinsic::umax: {
1077 // UMax(A, C) == A if ...
1078 // The lowest non-zero bit of DemandMask is higher than the highest
1079 // non-zero bit of C.
1080 const APInt *C;
1081 unsigned CTZ = DemandedMask.countr_zero();
1082 if (match(II->getArgOperand(1), m_APInt(C)) &&
1083 CTZ >= C->getActiveBits())
1084 return II->getArgOperand(0);
1085 break;
1086 }
1087 case Intrinsic::umin: {
1088 // UMin(A, C) == A if ...
1089 // The lowest non-zero bit of DemandMask is higher than the highest
1090 // non-one bit of C.
1091 // This comes from using DeMorgans on the above umax example.
1092 const APInt *C;
1093 unsigned CTZ = DemandedMask.countr_zero();
1094 if (match(II->getArgOperand(1), m_APInt(C)) &&
1095 CTZ >= C->getBitWidth() - C->countl_one())
1096 return II->getArgOperand(0);
1097 break;
1098 }
1099 default: {
1100 // Handle target specific intrinsics
1101 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1102 *II, DemandedMask, Known, KnownBitsComputed);
1103 if (V)
1104 return *V;
1105 break;
1106 }
1107 }
1108 }
1109
1110 if (!KnownBitsComputed)
1111 computeKnownBits(V, Known, Depth, CxtI);
1112 break;
1113 }
1114 }
1115
1116 if (V->getType()->isPointerTy()) {
1117 Align Alignment = V->getPointerAlignment(DL);
1118 Known.Zero.setLowBits(Log2(Alignment));
1119 }
1120
1121 // If the client is only demanding bits that we know, return the known
1122 // constant. We can't directly simplify pointers as a constant because of
1123 // pointer provenance.
1124 // TODO: We could return `(inttoptr const)` for pointers.
1125 if (!V->getType()->isPointerTy() && DemandedMask.isSubsetOf(Known.Zero | Known.One))
1126 return Constant::getIntegerValue(VTy, Known.One);
1127
1128 if (VerifyKnownBits) {
1129 KnownBits ReferenceKnown = computeKnownBits(V, Depth, CxtI);
1130 if (Known != ReferenceKnown) {
1131 errs() << "Mismatched known bits for " << *V << " in "
1132 << I->getFunction()->getName() << "\n";
1133 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1134 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1135 std::abort();
1136 }
1137 }
1138
1139 return nullptr;
1140}
1141
1142/// Helper routine of SimplifyDemandedUseBits. It computes Known
1143/// bits. It also tries to handle simplifications that can be done based on
1144/// DemandedMask, but without modifying the Instruction.
1146 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
1147 Instruction *CxtI) {
1148 unsigned BitWidth = DemandedMask.getBitWidth();
1149 Type *ITy = I->getType();
1150
1151 KnownBits LHSKnown(BitWidth);
1152 KnownBits RHSKnown(BitWidth);
1153
1154 // Despite the fact that we can't simplify this instruction in all User's
1155 // context, we can at least compute the known bits, and we can
1156 // do simplifications that apply to *just* the one user if we know that
1157 // this instruction has a simpler value in that context.
1158 switch (I->getOpcode()) {
1159 case Instruction::And: {
1160 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1161 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1162 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1163 Depth, SQ.getWithInstruction(CxtI));
1165
1166 // If the client is only demanding bits that we know, return the known
1167 // constant.
1168 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1169 return Constant::getIntegerValue(ITy, Known.One);
1170
1171 // If all of the demanded bits are known 1 on one side, return the other.
1172 // These bits cannot contribute to the result of the 'and' in this context.
1173 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1174 return I->getOperand(0);
1175 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1176 return I->getOperand(1);
1177
1178 break;
1179 }
1180 case Instruction::Or: {
1181 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1182 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1183 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1184 Depth, SQ.getWithInstruction(CxtI));
1186
1187 // If the client is only demanding bits that we know, return the known
1188 // constant.
1189 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1190 return Constant::getIntegerValue(ITy, Known.One);
1191
1192 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1193 // only bits from X or Y are demanded.
1194 // If all of the demanded bits are known zero on one side, return the other.
1195 // These bits cannot contribute to the result of the 'or' in this context.
1196 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1197 return I->getOperand(0);
1198 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1199 return I->getOperand(1);
1200
1201 break;
1202 }
1203 case Instruction::Xor: {
1204 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1205 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1206 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1207 Depth, SQ.getWithInstruction(CxtI));
1209
1210 // If the client is only demanding bits that we know, return the known
1211 // constant.
1212 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1213 return Constant::getIntegerValue(ITy, Known.One);
1214
1215 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1216 // only bits from X or Y are demanded.
1217 // If all of the demanded bits are known zero on one side, return the other.
1218 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1219 return I->getOperand(0);
1220 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1221 return I->getOperand(1);
1222
1223 break;
1224 }
1225 case Instruction::Add: {
1226 unsigned NLZ = DemandedMask.countl_zero();
1227 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1228
1229 // If an operand adds zeros to every bit below the highest demanded bit,
1230 // that operand doesn't change the result. Return the other side.
1231 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1232 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1233 return I->getOperand(0);
1234
1235 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1236 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1237 return I->getOperand(1);
1238
1239 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1240 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1241 Known =
1242 KnownBits::computeForAddSub(/*Add=*/true, NSW, NUW, LHSKnown, RHSKnown);
1244 break;
1245 }
1246 case Instruction::Sub: {
1247 unsigned NLZ = DemandedMask.countl_zero();
1248 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1249
1250 // If an operand subtracts zeros from every bit below the highest demanded
1251 // bit, that operand doesn't change the result. Return the other side.
1252 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1253 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1254 return I->getOperand(0);
1255
1256 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1257 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1258 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1259 Known = KnownBits::computeForAddSub(/*Add=*/false, NSW, NUW, LHSKnown,
1260 RHSKnown);
1262 break;
1263 }
1264 case Instruction::AShr: {
1265 // Compute the Known bits to simplify things downstream.
1266 computeKnownBits(I, Known, Depth, CxtI);
1267
1268 // If this user is only demanding bits that we know, return the known
1269 // constant.
1270 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1271 return Constant::getIntegerValue(ITy, Known.One);
1272
1273 // If the right shift operand 0 is a result of a left shift by the same
1274 // amount, this is probably a zero/sign extension, which may be unnecessary,
1275 // if we do not demand any of the new sign bits. So, return the original
1276 // operand instead.
1277 const APInt *ShiftRC;
1278 const APInt *ShiftLC;
1279 Value *X;
1280 unsigned BitWidth = DemandedMask.getBitWidth();
1281 if (match(I,
1282 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1283 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1284 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1285 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1286 return X;
1287 }
1288
1289 break;
1290 }
1291 default:
1292 // Compute the Known bits to simplify things downstream.
1293 computeKnownBits(I, Known, Depth, CxtI);
1294
1295 // If this user is only demanding bits that we know, return the known
1296 // constant.
1297 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1298 return Constant::getIntegerValue(ITy, Known.One);
1299
1300 break;
1301 }
1302
1303 return nullptr;
1304}
1305
1306/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1307/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1308/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1309/// of "C2-C1".
1310///
1311/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1312/// ..., bn}, without considering the specific value X is holding.
1313/// This transformation is legal iff one of following conditions is hold:
1314/// 1) All the bit in S are 0, in this case E1 == E2.
1315/// 2) We don't care those bits in S, per the input DemandedMask.
1316/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1317/// rest bits.
1318///
1319/// Currently we only test condition 2).
1320///
1321/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1322/// not successful.
1324 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1325 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1326 if (!ShlOp1 || !ShrOp1)
1327 return nullptr; // No-op.
1328
1329 Value *VarX = Shr->getOperand(0);
1330 Type *Ty = VarX->getType();
1331 unsigned BitWidth = Ty->getScalarSizeInBits();
1332 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1333 return nullptr; // Undef.
1334
1335 unsigned ShlAmt = ShlOp1.getZExtValue();
1336 unsigned ShrAmt = ShrOp1.getZExtValue();
1337
1338 Known.One.clearAllBits();
1339 Known.Zero.setLowBits(ShlAmt - 1);
1340 Known.Zero &= DemandedMask;
1341
1342 APInt BitMask1(APInt::getAllOnes(BitWidth));
1343 APInt BitMask2(APInt::getAllOnes(BitWidth));
1344
1345 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1346 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1347 (BitMask1.ashr(ShrAmt) << ShlAmt);
1348
1349 if (ShrAmt <= ShlAmt) {
1350 BitMask2 <<= (ShlAmt - ShrAmt);
1351 } else {
1352 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1353 BitMask2.ashr(ShrAmt - ShlAmt);
1354 }
1355
1356 // Check if condition-2 (see the comment to this function) is satified.
1357 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1358 if (ShrAmt == ShlAmt)
1359 return VarX;
1360
1361 if (!Shr->hasOneUse())
1362 return nullptr;
1363
1364 BinaryOperator *New;
1365 if (ShrAmt < ShlAmt) {
1366 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1367 New = BinaryOperator::CreateShl(VarX, Amt);
1368 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1369 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1370 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1371 } else {
1372 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1373 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1374 BinaryOperator::CreateAShr(VarX, Amt);
1375 if (cast<BinaryOperator>(Shr)->isExact())
1376 New->setIsExact(true);
1377 }
1378
1379 return InsertNewInstWith(New, Shl->getIterator());
1380 }
1381
1382 return nullptr;
1383}
1384
1385/// The specified value produces a vector with any number of elements.
1386/// This method analyzes which elements of the operand are poison and
1387/// returns that information in PoisonElts.
1388///
1389/// DemandedElts contains the set of elements that are actually used by the
1390/// caller, and by default (AllowMultipleUsers equals false) the value is
1391/// simplified only if it has a single caller. If AllowMultipleUsers is set
1392/// to true, DemandedElts refers to the union of sets of elements that are
1393/// used by all callers.
1394///
1395/// If the information about demanded elements can be used to simplify the
1396/// operation, the operation is simplified, then the resultant value is
1397/// returned. This returns null if no change was made.
1399 APInt DemandedElts,
1400 APInt &PoisonElts,
1401 unsigned Depth,
1402 bool AllowMultipleUsers) {
1403 // Cannot analyze scalable type. The number of vector elements is not a
1404 // compile-time constant.
1405 if (isa<ScalableVectorType>(V->getType()))
1406 return nullptr;
1407
1408 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1409 APInt EltMask(APInt::getAllOnes(VWidth));
1410 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1411
1412 if (match(V, m_Poison())) {
1413 // If the entire vector is poison, just return this info.
1414 PoisonElts = EltMask;
1415 return nullptr;
1416 }
1417
1418 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1419 PoisonElts = EltMask;
1420 return PoisonValue::get(V->getType());
1421 }
1422
1423 PoisonElts = 0;
1424
1425 if (auto *C = dyn_cast<Constant>(V)) {
1426 // Check if this is identity. If so, return 0 since we are not simplifying
1427 // anything.
1428 if (DemandedElts.isAllOnes())
1429 return nullptr;
1430
1431 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1432 Constant *Poison = PoisonValue::get(EltTy);
1434 for (unsigned i = 0; i != VWidth; ++i) {
1435 if (!DemandedElts[i]) { // If not demanded, set to poison.
1436 Elts.push_back(Poison);
1437 PoisonElts.setBit(i);
1438 continue;
1439 }
1440
1441 Constant *Elt = C->getAggregateElement(i);
1442 if (!Elt) return nullptr;
1443
1444 Elts.push_back(Elt);
1445 if (isa<PoisonValue>(Elt)) // Already poison.
1446 PoisonElts.setBit(i);
1447 }
1448
1449 // If we changed the constant, return it.
1450 Constant *NewCV = ConstantVector::get(Elts);
1451 return NewCV != C ? NewCV : nullptr;
1452 }
1453
1454 // Limit search depth.
1455 if (Depth == 10)
1456 return nullptr;
1457
1458 if (!AllowMultipleUsers) {
1459 // If multiple users are using the root value, proceed with
1460 // simplification conservatively assuming that all elements
1461 // are needed.
1462 if (!V->hasOneUse()) {
1463 // Quit if we find multiple users of a non-root value though.
1464 // They'll be handled when it's their turn to be visited by
1465 // the main instcombine process.
1466 if (Depth != 0)
1467 // TODO: Just compute the PoisonElts information recursively.
1468 return nullptr;
1469
1470 // Conservatively assume that all elements are needed.
1471 DemandedElts = EltMask;
1472 }
1473 }
1474
1475 Instruction *I = dyn_cast<Instruction>(V);
1476 if (!I) return nullptr; // Only analyze instructions.
1477
1478 bool MadeChange = false;
1479 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1480 APInt Demanded, APInt &Undef) {
1481 auto *II = dyn_cast<IntrinsicInst>(Inst);
1482 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1483 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1484 replaceOperand(*Inst, OpNum, V);
1485 MadeChange = true;
1486 }
1487 };
1488
1489 APInt PoisonElts2(VWidth, 0);
1490 APInt PoisonElts3(VWidth, 0);
1491 switch (I->getOpcode()) {
1492 default: break;
1493
1494 case Instruction::GetElementPtr: {
1495 // The LangRef requires that struct geps have all constant indices. As
1496 // such, we can't convert any operand to partial undef.
1497 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1498 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1499 I != E; I++)
1500 if (I.isStruct())
1501 return true;
1502 return false;
1503 };
1504 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1505 break;
1506
1507 // Conservatively track the demanded elements back through any vector
1508 // operands we may have. We know there must be at least one, or we
1509 // wouldn't have a vector result to get here. Note that we intentionally
1510 // merge the undef bits here since gepping with either an poison base or
1511 // index results in poison.
1512 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1513 if (i == 0 ? match(I->getOperand(i), m_Undef())
1514 : match(I->getOperand(i), m_Poison())) {
1515 // If the entire vector is undefined, just return this info.
1516 PoisonElts = EltMask;
1517 return nullptr;
1518 }
1519 if (I->getOperand(i)->getType()->isVectorTy()) {
1520 APInt PoisonEltsOp(VWidth, 0);
1521 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1522 // gep(x, undef) is not undef, so skip considering idx ops here
1523 // Note that we could propagate poison, but we can't distinguish between
1524 // undef & poison bits ATM
1525 if (i == 0)
1526 PoisonElts |= PoisonEltsOp;
1527 }
1528 }
1529
1530 break;
1531 }
1532 case Instruction::InsertElement: {
1533 // If this is a variable index, we don't know which element it overwrites.
1534 // demand exactly the same input as we produce.
1535 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1536 if (!Idx) {
1537 // Note that we can't propagate undef elt info, because we don't know
1538 // which elt is getting updated.
1539 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1540 break;
1541 }
1542
1543 // The element inserted overwrites whatever was there, so the input demanded
1544 // set is simpler than the output set.
1545 unsigned IdxNo = Idx->getZExtValue();
1546 APInt PreInsertDemandedElts = DemandedElts;
1547 if (IdxNo < VWidth)
1548 PreInsertDemandedElts.clearBit(IdxNo);
1549
1550 // If we only demand the element that is being inserted and that element
1551 // was extracted from the same index in another vector with the same type,
1552 // replace this insert with that other vector.
1553 // Note: This is attempted before the call to simplifyAndSetOp because that
1554 // may change PoisonElts to a value that does not match with Vec.
1555 Value *Vec;
1556 if (PreInsertDemandedElts == 0 &&
1557 match(I->getOperand(1),
1558 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1559 Vec->getType() == I->getType()) {
1560 return Vec;
1561 }
1562
1563 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1564
1565 // If this is inserting an element that isn't demanded, remove this
1566 // insertelement.
1567 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1568 Worklist.push(I);
1569 return I->getOperand(0);
1570 }
1571
1572 // The inserted element is defined.
1573 PoisonElts.clearBit(IdxNo);
1574 break;
1575 }
1576 case Instruction::ShuffleVector: {
1577 auto *Shuffle = cast<ShuffleVectorInst>(I);
1578 assert(Shuffle->getOperand(0)->getType() ==
1579 Shuffle->getOperand(1)->getType() &&
1580 "Expected shuffle operands to have same type");
1581 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1582 ->getNumElements();
1583 // Handle trivial case of a splat. Only check the first element of LHS
1584 // operand.
1585 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1586 DemandedElts.isAllOnes()) {
1587 if (!isa<PoisonValue>(I->getOperand(1))) {
1588 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1589 MadeChange = true;
1590 }
1591 APInt LeftDemanded(OpWidth, 1);
1592 APInt LHSPoisonElts(OpWidth, 0);
1593 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1594 if (LHSPoisonElts[0])
1595 PoisonElts = EltMask;
1596 else
1597 PoisonElts.clearAllBits();
1598 break;
1599 }
1600
1601 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1602 for (unsigned i = 0; i < VWidth; i++) {
1603 if (DemandedElts[i]) {
1604 unsigned MaskVal = Shuffle->getMaskValue(i);
1605 if (MaskVal != -1u) {
1606 assert(MaskVal < OpWidth * 2 &&
1607 "shufflevector mask index out of range!");
1608 if (MaskVal < OpWidth)
1609 LeftDemanded.setBit(MaskVal);
1610 else
1611 RightDemanded.setBit(MaskVal - OpWidth);
1612 }
1613 }
1614 }
1615
1616 APInt LHSPoisonElts(OpWidth, 0);
1617 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1618
1619 APInt RHSPoisonElts(OpWidth, 0);
1620 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1621
1622 // If this shuffle does not change the vector length and the elements
1623 // demanded by this shuffle are an identity mask, then this shuffle is
1624 // unnecessary.
1625 //
1626 // We are assuming canonical form for the mask, so the source vector is
1627 // operand 0 and operand 1 is not used.
1628 //
1629 // Note that if an element is demanded and this shuffle mask is undefined
1630 // for that element, then the shuffle is not considered an identity
1631 // operation. The shuffle prevents poison from the operand vector from
1632 // leaking to the result by replacing poison with an undefined value.
1633 if (VWidth == OpWidth) {
1634 bool IsIdentityShuffle = true;
1635 for (unsigned i = 0; i < VWidth; i++) {
1636 unsigned MaskVal = Shuffle->getMaskValue(i);
1637 if (DemandedElts[i] && i != MaskVal) {
1638 IsIdentityShuffle = false;
1639 break;
1640 }
1641 }
1642 if (IsIdentityShuffle)
1643 return Shuffle->getOperand(0);
1644 }
1645
1646 bool NewPoisonElts = false;
1647 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1648 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1649 bool LHSUniform = true;
1650 bool RHSUniform = true;
1651 for (unsigned i = 0; i < VWidth; i++) {
1652 unsigned MaskVal = Shuffle->getMaskValue(i);
1653 if (MaskVal == -1u) {
1654 PoisonElts.setBit(i);
1655 } else if (!DemandedElts[i]) {
1656 NewPoisonElts = true;
1657 PoisonElts.setBit(i);
1658 } else if (MaskVal < OpWidth) {
1659 if (LHSPoisonElts[MaskVal]) {
1660 NewPoisonElts = true;
1661 PoisonElts.setBit(i);
1662 } else {
1663 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1664 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1665 LHSUniform = LHSUniform && (MaskVal == i);
1666 }
1667 } else {
1668 if (RHSPoisonElts[MaskVal - OpWidth]) {
1669 NewPoisonElts = true;
1670 PoisonElts.setBit(i);
1671 } else {
1672 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1673 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1674 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1675 }
1676 }
1677 }
1678
1679 // Try to transform shuffle with constant vector and single element from
1680 // this constant vector to single insertelement instruction.
1681 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1682 // insertelement V, C[ci], ci-n
1683 if (OpWidth ==
1684 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1685 Value *Op = nullptr;
1686 Constant *Value = nullptr;
1687 unsigned Idx = -1u;
1688
1689 // Find constant vector with the single element in shuffle (LHS or RHS).
1690 if (LHSIdx < OpWidth && RHSUniform) {
1691 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1692 Op = Shuffle->getOperand(1);
1693 Value = CV->getOperand(LHSValIdx);
1694 Idx = LHSIdx;
1695 }
1696 }
1697 if (RHSIdx < OpWidth && LHSUniform) {
1698 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1699 Op = Shuffle->getOperand(0);
1700 Value = CV->getOperand(RHSValIdx);
1701 Idx = RHSIdx;
1702 }
1703 }
1704 // Found constant vector with single element - convert to insertelement.
1705 if (Op && Value) {
1707 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1708 Shuffle->getName());
1709 InsertNewInstWith(New, Shuffle->getIterator());
1710 return New;
1711 }
1712 }
1713 if (NewPoisonElts) {
1714 // Add additional discovered undefs.
1716 for (unsigned i = 0; i < VWidth; ++i) {
1717 if (PoisonElts[i])
1719 else
1720 Elts.push_back(Shuffle->getMaskValue(i));
1721 }
1722 Shuffle->setShuffleMask(Elts);
1723 MadeChange = true;
1724 }
1725 break;
1726 }
1727 case Instruction::Select: {
1728 // If this is a vector select, try to transform the select condition based
1729 // on the current demanded elements.
1730 SelectInst *Sel = cast<SelectInst>(I);
1731 if (Sel->getCondition()->getType()->isVectorTy()) {
1732 // TODO: We are not doing anything with PoisonElts based on this call.
1733 // It is overwritten below based on the other select operands. If an
1734 // element of the select condition is known undef, then we are free to
1735 // choose the output value from either arm of the select. If we know that
1736 // one of those values is undef, then the output can be undef.
1737 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1738 }
1739
1740 // Next, see if we can transform the arms of the select.
1741 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1742 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1743 for (unsigned i = 0; i < VWidth; i++) {
1744 // isNullValue() always returns false when called on a ConstantExpr.
1745 // Skip constant expressions to avoid propagating incorrect information.
1746 Constant *CElt = CV->getAggregateElement(i);
1747 if (isa<ConstantExpr>(CElt))
1748 continue;
1749 // TODO: If a select condition element is undef, we can demand from
1750 // either side. If one side is known undef, choosing that side would
1751 // propagate undef.
1752 if (CElt->isNullValue())
1753 DemandedLHS.clearBit(i);
1754 else
1755 DemandedRHS.clearBit(i);
1756 }
1757 }
1758
1759 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1760 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1761
1762 // Output elements are undefined if the element from each arm is undefined.
1763 // TODO: This can be improved. See comment in select condition handling.
1764 PoisonElts = PoisonElts2 & PoisonElts3;
1765 break;
1766 }
1767 case Instruction::BitCast: {
1768 // Vector->vector casts only.
1769 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1770 if (!VTy) break;
1771 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1772 APInt InputDemandedElts(InVWidth, 0);
1773 PoisonElts2 = APInt(InVWidth, 0);
1774 unsigned Ratio;
1775
1776 if (VWidth == InVWidth) {
1777 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1778 // elements as are demanded of us.
1779 Ratio = 1;
1780 InputDemandedElts = DemandedElts;
1781 } else if ((VWidth % InVWidth) == 0) {
1782 // If the number of elements in the output is a multiple of the number of
1783 // elements in the input then an input element is live if any of the
1784 // corresponding output elements are live.
1785 Ratio = VWidth / InVWidth;
1786 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1787 if (DemandedElts[OutIdx])
1788 InputDemandedElts.setBit(OutIdx / Ratio);
1789 } else if ((InVWidth % VWidth) == 0) {
1790 // If the number of elements in the input is a multiple of the number of
1791 // elements in the output then an input element is live if the
1792 // corresponding output element is live.
1793 Ratio = InVWidth / VWidth;
1794 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1795 if (DemandedElts[InIdx / Ratio])
1796 InputDemandedElts.setBit(InIdx);
1797 } else {
1798 // Unsupported so far.
1799 break;
1800 }
1801
1802 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1803
1804 if (VWidth == InVWidth) {
1805 PoisonElts = PoisonElts2;
1806 } else if ((VWidth % InVWidth) == 0) {
1807 // If the number of elements in the output is a multiple of the number of
1808 // elements in the input then an output element is undef if the
1809 // corresponding input element is undef.
1810 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1811 if (PoisonElts2[OutIdx / Ratio])
1812 PoisonElts.setBit(OutIdx);
1813 } else if ((InVWidth % VWidth) == 0) {
1814 // If the number of elements in the input is a multiple of the number of
1815 // elements in the output then an output element is undef if all of the
1816 // corresponding input elements are undef.
1817 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1818 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1819 if (SubUndef.popcount() == Ratio)
1820 PoisonElts.setBit(OutIdx);
1821 }
1822 } else {
1823 llvm_unreachable("Unimp");
1824 }
1825 break;
1826 }
1827 case Instruction::FPTrunc:
1828 case Instruction::FPExt:
1829 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1830 break;
1831
1832 case Instruction::Call: {
1833 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1834 if (!II) break;
1835 switch (II->getIntrinsicID()) {
1836 case Intrinsic::masked_gather: // fallthrough
1837 case Intrinsic::masked_load: {
1838 // Subtlety: If we load from a pointer, the pointer must be valid
1839 // regardless of whether the element is demanded. Doing otherwise risks
1840 // segfaults which didn't exist in the original program.
1841 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1842 DemandedPassThrough(DemandedElts);
1843 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1844 for (unsigned i = 0; i < VWidth; i++) {
1845 Constant *CElt = CV->getAggregateElement(i);
1846 if (CElt->isNullValue())
1847 DemandedPtrs.clearBit(i);
1848 else if (CElt->isAllOnesValue())
1849 DemandedPassThrough.clearBit(i);
1850 }
1851 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1852 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1853 simplifyAndSetOp(II, 3, DemandedPassThrough, PoisonElts3);
1854
1855 // Output elements are undefined if the element from both sources are.
1856 // TODO: can strengthen via mask as well.
1857 PoisonElts = PoisonElts2 & PoisonElts3;
1858 break;
1859 }
1860 default: {
1861 // Handle target specific intrinsics
1862 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1863 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1864 simplifyAndSetOp);
1865 if (V)
1866 return *V;
1867 break;
1868 }
1869 } // switch on IntrinsicID
1870 break;
1871 } // case Call
1872 } // switch on Opcode
1873
1874 // TODO: We bail completely on integer div/rem and shifts because they have
1875 // UB/poison potential, but that should be refined.
1876 BinaryOperator *BO;
1877 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1878 Value *X = BO->getOperand(0);
1879 Value *Y = BO->getOperand(1);
1880
1881 // Look for an equivalent binop except that one operand has been shuffled.
1882 // If the demand for this binop only includes elements that are the same as
1883 // the other binop, then we may be able to replace this binop with a use of
1884 // the earlier one.
1885 //
1886 // Example:
1887 // %other_bo = bo (shuf X, {0}), Y
1888 // %this_extracted_bo = extelt (bo X, Y), 0
1889 // -->
1890 // %other_bo = bo (shuf X, {0}), Y
1891 // %this_extracted_bo = extelt %other_bo, 0
1892 //
1893 // TODO: Handle demand of an arbitrary single element or more than one
1894 // element instead of just element 0.
1895 // TODO: Unlike general demanded elements transforms, this should be safe
1896 // for any (div/rem/shift) opcode too.
1897 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
1898 BO->hasOneUse() ) {
1899
1900 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
1901 // Try to use shuffle-of-operand in place of an operand:
1902 // bo X, Y --> bo (shuf X), Y
1903 // bo X, Y --> bo X, (shuf Y)
1904 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
1905 Value *ShufOp = MatchShufAsOp0 ? X : Y;
1906 Value *OtherOp = MatchShufAsOp0 ? Y : X;
1907 for (User *U : OtherOp->users()) {
1908 ArrayRef<int> Mask;
1909 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
1910 if (BO->isCommutative()
1911 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1912 : MatchShufAsOp0
1913 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1914 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
1915 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
1916 if (DT.dominates(U, I))
1917 return U;
1918 }
1919 return nullptr;
1920 };
1921
1922 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true))
1923 return ShufBO;
1924 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ false))
1925 return ShufBO;
1926 }
1927
1928 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1929 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
1930
1931 // Output elements are undefined if both are undefined. Consider things
1932 // like undef & 0. The result is known zero, not undef.
1933 PoisonElts &= PoisonElts2;
1934 }
1935
1936 // If we've proven all of the lanes poison, return a poison value.
1937 // TODO: Intersect w/demanded lanes
1938 if (PoisonElts.isAllOnes())
1939 return PoisonValue::get(I->getType());
1940
1941 return MadeChange ? I : nullptr;
1942}
1943
1944/// For floating-point classes that resolve to a single bit pattern, return that
1945/// value.
1947 switch (Mask) {
1948 case fcPosZero:
1949 return ConstantFP::getZero(Ty);
1950 case fcNegZero:
1951 return ConstantFP::getZero(Ty, true);
1952 case fcPosInf:
1953 return ConstantFP::getInfinity(Ty);
1954 case fcNegInf:
1955 return ConstantFP::getInfinity(Ty, true);
1956 case fcNone:
1957 return PoisonValue::get(Ty);
1958 default:
1959 return nullptr;
1960 }
1961}
1962
1964 Value *V, const FPClassTest DemandedMask, KnownFPClass &Known,
1965 unsigned Depth, Instruction *CxtI) {
1966 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1967 Type *VTy = V->getType();
1968
1969 assert(Known == KnownFPClass() && "expected uninitialized state");
1970
1971 if (DemandedMask == fcNone)
1972 return isa<UndefValue>(V) ? nullptr : PoisonValue::get(VTy);
1973
1975 return nullptr;
1976
1977 Instruction *I = dyn_cast<Instruction>(V);
1978 if (!I) {
1979 // Handle constants and arguments
1980 Known = computeKnownFPClass(V, fcAllFlags, CxtI, Depth + 1);
1981 Value *FoldedToConst =
1982 getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
1983 return FoldedToConst == V ? nullptr : FoldedToConst;
1984 }
1985
1986 if (!I->hasOneUse())
1987 return nullptr;
1988
1989 // TODO: Should account for nofpclass/FastMathFlags on current instruction
1990 switch (I->getOpcode()) {
1991 case Instruction::FNeg: {
1992 if (SimplifyDemandedFPClass(I, 0, llvm::fneg(DemandedMask), Known,
1993 Depth + 1))
1994 return I;
1995 Known.fneg();
1996 break;
1997 }
1998 case Instruction::Call: {
1999 CallInst *CI = cast<CallInst>(I);
2000 switch (CI->getIntrinsicID()) {
2001 case Intrinsic::fabs:
2002 if (SimplifyDemandedFPClass(I, 0, llvm::inverse_fabs(DemandedMask), Known,
2003 Depth + 1))
2004 return I;
2005 Known.fabs();
2006 break;
2007 case Intrinsic::arithmetic_fence:
2008 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, Depth + 1))
2009 return I;
2010 break;
2011 case Intrinsic::copysign: {
2012 // Flip on more potentially demanded classes
2013 const FPClassTest DemandedMaskAnySign = llvm::unknown_sign(DemandedMask);
2014 if (SimplifyDemandedFPClass(I, 0, DemandedMaskAnySign, Known, Depth + 1))
2015 return I;
2016
2017 if ((DemandedMask & fcPositive) == fcNone) {
2018 // Roundabout way of replacing with fneg(fabs)
2019 I->setOperand(1, ConstantFP::get(VTy, -1.0));
2020 return I;
2021 }
2022
2023 if ((DemandedMask & fcNegative) == fcNone) {
2024 // Roundabout way of replacing with fabs
2025 I->setOperand(1, ConstantFP::getZero(VTy));
2026 return I;
2027 }
2028
2029 KnownFPClass KnownSign =
2030 computeKnownFPClass(I->getOperand(1), fcAllFlags, CxtI, Depth + 1);
2031 Known.copysign(KnownSign);
2032 break;
2033 }
2034 default:
2035 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2036 break;
2037 }
2038
2039 break;
2040 }
2041 case Instruction::Select: {
2042 KnownFPClass KnownLHS, KnownRHS;
2043 if (SimplifyDemandedFPClass(I, 2, DemandedMask, KnownRHS, Depth + 1) ||
2044 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownLHS, Depth + 1))
2045 return I;
2046
2047 if (KnownLHS.isKnownNever(DemandedMask))
2048 return I->getOperand(2);
2049 if (KnownRHS.isKnownNever(DemandedMask))
2050 return I->getOperand(1);
2051
2052 // TODO: Recognize clamping patterns
2053 Known = KnownLHS | KnownRHS;
2054 break;
2055 }
2056 default:
2057 Known = computeKnownFPClass(I, ~DemandedMask, CxtI, Depth + 1);
2058 break;
2059 }
2060
2061 return getFPClassConstant(VTy, DemandedMask & Known.KnownFPClasses);
2062}
2063
2065 FPClassTest DemandedMask,
2066 KnownFPClass &Known,
2067 unsigned Depth) {
2068 Use &U = I->getOperandUse(OpNo);
2069 Value *NewVal =
2070 SimplifyDemandedUseFPClass(U.get(), DemandedMask, Known, Depth, I);
2071 if (!NewVal)
2072 return false;
2073 if (Instruction *OpInst = dyn_cast<Instruction>(U))
2074 salvageDebugInfo(*OpInst);
2075
2076 replaceUse(U, NewVal);
2077 return true;
2078}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static Constant * getFPClassConstant(Type *Ty, FPClassTest Mask)
For floating-point classes that resolve to a single bit pattern, return that value.
static cl::opt< bool > VerifyKnownBits("instcombine-verify-known-bits", cl::desc("Verify that computeKnownBits() and " "SimplifyDemandedBits() are consistent"), cl::Hidden, cl::init(false))
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:77
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:213
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1386
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:208
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1499
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition: APInt.h:1371
unsigned popcount() const
Count the number of bits set.
Definition: APInt.h:1628
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition: APInt.cpp:1002
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1471
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:906
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition: APInt.h:1309
APInt abs() const
Get the absolute value.
Definition: APInt.h:1752
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:350
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:359
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition: APInt.cpp:1636
void setSignBit()
Set the sign bit to 1.
Definition: APInt.h:1319
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1447
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1090
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition: APInt.h:1228
void clearAllBits()
Set every bit to 0.
Definition: APInt.h:1376
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1597
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition: APInt.h:1556
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1396
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:454
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:806
void setAllBits()
Set every bit to 1.
Definition: APInt.h:1298
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:852
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1236
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition: APInt.h:419
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:285
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:275
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition: APInt.h:1368
bool isOne() const
Determine if this is a value of 1.
Definition: APInt.h:368
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:837
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:830
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1200
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
BinaryOps getOpcode() const
Definition: InstrTypes.h:513
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:601
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
static Constant * getInfinity(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1084
static Constant * getZero(Type *Ty, bool Negative=false)
Definition: Constants.cpp:1038
This is the shared class of boolean and integer constants.
Definition: Constants.h:81
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:146
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1399
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:400
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:417
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition: Constants.cpp:107
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:432
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Definition: DataLayout.cpp:905
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:974
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:913
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2033
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1437
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Definition: IRBuilder.h:1866
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1749
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1475
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2007
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1497
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1519
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, BasicBlock::iterator InsertBefore)
KnownFPClass computeKnownFPClass(Value *Val, FastMathFlags FMF, FPClassTest Interested=fcAllFlags, const Instruction *CtxI=nullptr, unsigned Depth=0) const
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Value * SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known, unsigned Depth, Instruction *CxtI)
Attempts to replace V with a simpler value based on the demanded bits.
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, Instruction *CxtI)
Helper routine of SimplifyDemandedUseBits.
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseFPClass(Value *V, FPClassTest DemandedMask, KnownFPClass &Known, unsigned Depth, Instruction *CxtI)
Attempts to replace V with a simpler value based on the demanded floating-point classes.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, unsigned Depth=0)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
SimplifyQuery SQ
Definition: InstCombiner.h:76
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
Definition: InstCombiner.h:418
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
Definition: InstCombiner.h:375
const DataLayout & DL
Definition: InstCombiner.h:75
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:452
std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:410
DominatorTree & DT
Definition: InstCombiner.h:74
std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
BuilderTy & Builder
Definition: InstCombiner.h:60
void push(Instruction *I)
Push the instruction onto the worklist stack.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:252
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
bool isShift() const
Definition: Instruction.h:259
bool isIntDivRem() const
Definition: Instruction.h:258
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition: Operator.h:110
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition: Operator.h:104
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1814
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:234
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static IntegerType * getInt64Ty(LLVMContext &C)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1795
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
iterator_range< user_iterator > users()
Definition: Value.h:421
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
Base class of all SIMD vector types.
Definition: DerivedTypes.h:403
This class represents zero extension of integer types.
self_iterator getIterator()
Definition: ilist_node.h:109
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1474
class_match< PoisonValue > m_Poison()
Match an arbitrary poison constant.
Definition: PatternMatch.h:160
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:972
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:875
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
match_combine_and< class_match< Constant >, match_unless< constantexpr_match > > m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
Definition: PatternMatch.h:854
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:612
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition: bit.h:307
void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition: Utils.cpp:1665
gep_type_iterator gep_type_end(const User *GEP)
void computeKnownBitsFromContext(const Value *V, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Merge bits known from context-dependent facts into Known.
KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const SimplifyQuery &SQ)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:48
FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
FPClassTest unknown_sign(FPClassTest Mask)
Return the test mask which returns true if the value could have the same set of classes,...
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the largest uint64_t less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:481
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition: KnownBits.h:290
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition: KnownBits.h:175
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:97
void makeNonNegative()
Make this value non-negative.
Definition: KnownBits.h:113
static KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
Definition: KnownBits.cpp:1042
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:40
void resetAll()
Resets the known state of all bits.
Definition: KnownBits.h:70
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition: KnownBits.h:300
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition: KnownBits.h:169
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition: KnownBits.h:185
static KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
Definition: KnownBits.cpp:1002
static KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition: KnownBits.cpp:51
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:94
static KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
Definition: KnownBits.cpp:285
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
void copysign(const KnownFPClass &Sign)
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96