1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains logic for simplifying instructions based on information
11 // about how they are used.
13 //===----------------------------------------------------------------------===//
15 #include "InstCombine.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
21 using namespace llvm::PatternMatch;
23 #define DEBUG_TYPE "instcombine"
25 /// ShrinkDemandedConstant - Check to see if the specified operand of the
26 /// specified instruction is a constant integer. If so, check to see if there
27 /// are any bits set in the constant that are not demanded. If so, shrink the
28 /// constant and return true.
29 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
31 assert(I && "No instruction?");
32 assert(OpNo < I->getNumOperands() && "Operand index too large");
34 // If the operand is not a constant integer, nothing to do.
35 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
36 if (!OpC) return false;
38 // If there are no bits set that aren't demanded, nothing to do.
39 Demanded = Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
40 if ((~Demanded & OpC->getValue()) == 0)
43 // This instruction is producing bits that are not demanded. Shrink the RHS.
44 Demanded &= OpC->getValue();
45 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
47 // If either 'nsw' or 'nuw' is set and the constant is negative,
48 // removing *any* bits from the constant could make overflow occur.
49 // Remove 'nsw' and 'nuw' from the instruction in this case.
50 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
51 assert(OBO->getOpcode() == Instruction::Add);
52 if (OBO->hasNoSignedWrap() || OBO->hasNoUnsignedWrap()) {
53 if (OpC->getValue().isNegative()) {
54 cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
55 cast<BinaryOperator>(OBO)->setHasNoUnsignedWrap(false);
65 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
66 /// SimplifyDemandedBits knows about. See if the instruction has any
67 /// properties that allow us to simplify its operands.
68 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
69 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
70 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
71 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
73 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
74 KnownZero, KnownOne, 0, &Inst);
76 if (V == &Inst) return true;
77 ReplaceInstUsesWith(Inst, V);
81 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
82 /// specified instruction operand if possible, updating it in place. It returns
83 /// true if it made any change and false otherwise.
84 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
85 APInt &KnownZero, APInt &KnownOne,
87 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
88 KnownZero, KnownOne, Depth,
89 dyn_cast<Instruction>(U.getUser()));
90 if (!NewVal) return false;
96 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
97 /// value based on the demanded bits. When this function is called, it is known
98 /// that only the bits set in DemandedMask of the result of V are ever used
99 /// downstream. Consequently, depending on the mask and V, it may be possible
100 /// to replace V with a constant or one of its operands. In such cases, this
101 /// function does the replacement and returns true. In all other cases, it
102 /// returns false after analyzing the expression and setting KnownOne and known
103 /// to be one in the expression. KnownZero contains all the bits that are known
104 /// to be zero in the expression. These are provided to potentially allow the
105 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
106 /// the expression. KnownOne and KnownZero always follow the invariant that
107 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
108 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
109 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
110 /// and KnownOne must all be the same.
112 /// This returns null if it did not change anything and it permits no
113 /// simplification. This returns V itself if it did some simplification of V's
114 /// operands based on the information about what bits are demanded. This returns
115 /// some other non-null value if it found out that V is equal to another value
116 /// in the context where the specified bits are demanded, but not for all users.
117 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
118 APInt &KnownZero, APInt &KnownOne,
121 assert(V != nullptr && "Null pointer of Value???");
122 assert(Depth <= 6 && "Limit Search Depth");
123 uint32_t BitWidth = DemandedMask.getBitWidth();
124 Type *VTy = V->getType();
125 assert((DL || !VTy->isPointerTy()) &&
126 "SimplifyDemandedBits needs to know bit widths!");
127 assert((!DL || DL->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
128 (!VTy->isIntOrIntVectorTy() ||
129 VTy->getScalarSizeInBits() == BitWidth) &&
130 KnownZero.getBitWidth() == BitWidth &&
131 KnownOne.getBitWidth() == BitWidth &&
132 "Value *V, DemandedMask, KnownZero and KnownOne "
133 "must have same BitWidth");
134 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
135 // We know all of the bits for a constant!
136 KnownOne = CI->getValue() & DemandedMask;
137 KnownZero = ~KnownOne & DemandedMask;
140 if (isa<ConstantPointerNull>(V)) {
141 // We know all of the bits for a constant!
142 KnownOne.clearAllBits();
143 KnownZero = DemandedMask;
147 KnownZero.clearAllBits();
148 KnownOne.clearAllBits();
149 if (DemandedMask == 0) { // Not demanding any bits from V.
150 if (isa<UndefValue>(V))
152 return UndefValue::get(VTy);
155 if (Depth == 6) // Limit search depth.
158 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
159 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
161 Instruction *I = dyn_cast<Instruction>(V);
163 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
164 return nullptr; // Only analyze instructions.
167 // If there are multiple uses of this value and we aren't at the root, then
168 // we can't do any simplifications of the operands, because DemandedMask
169 // only reflects the bits demanded by *one* of the users.
170 if (Depth != 0 && !I->hasOneUse()) {
171 // Despite the fact that we can't simplify this instruction in all User's
172 // context, we can at least compute the knownzero/knownone bits, and we can
173 // do simplifications that apply to *just* the one user if we know that
174 // this instruction has a simpler value in that context.
175 if (I->getOpcode() == Instruction::And) {
176 // If either the LHS or the RHS are Zero, the result is zero.
177 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
179 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
182 // If all of the demanded bits are known 1 on one side, return the other.
183 // These bits cannot contribute to the result of the 'and' in this
185 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
186 (DemandedMask & ~LHSKnownZero))
187 return I->getOperand(0);
188 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
189 (DemandedMask & ~RHSKnownZero))
190 return I->getOperand(1);
192 // If all of the demanded bits in the inputs are known zeros, return zero.
193 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
194 return Constant::getNullValue(VTy);
196 } else if (I->getOpcode() == Instruction::Or) {
197 // We can simplify (X|Y) -> X or Y in the user's context if we know that
198 // only bits from X or Y are demanded.
200 // If either the LHS or the RHS are One, the result is One.
201 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
203 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
206 // If all of the demanded bits are known zero on one side, return the
207 // other. These bits cannot contribute to the result of the 'or' in this
209 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
210 (DemandedMask & ~LHSKnownOne))
211 return I->getOperand(0);
212 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
213 (DemandedMask & ~RHSKnownOne))
214 return I->getOperand(1);
216 // If all of the potentially set bits on one side are known to be set on
217 // the other side, just use the 'other' side.
218 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
219 (DemandedMask & (~RHSKnownZero)))
220 return I->getOperand(0);
221 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
222 (DemandedMask & (~LHSKnownZero)))
223 return I->getOperand(1);
224 } else if (I->getOpcode() == Instruction::Xor) {
225 // We can simplify (X^Y) -> X or Y in the user's context if we know that
226 // only bits from X or Y are demanded.
228 computeKnownBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth+1,
230 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
233 // If all of the demanded bits are known zero on one side, return the
235 if ((DemandedMask & RHSKnownZero) == DemandedMask)
236 return I->getOperand(0);
237 if ((DemandedMask & LHSKnownZero) == DemandedMask)
238 return I->getOperand(1);
241 // Compute the KnownZero/KnownOne bits to simplify things downstream.
242 computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
246 // If this is the root being simplified, allow it to have multiple uses,
247 // just set the DemandedMask to all bits so that we can try to simplify the
248 // operands. This allows visitTruncInst (for example) to simplify the
249 // operand of a trunc without duplicating all the logic below.
250 if (Depth == 0 && !V->hasOneUse())
251 DemandedMask = APInt::getAllOnesValue(BitWidth);
253 switch (I->getOpcode()) {
255 computeKnownBits(I, KnownZero, KnownOne, Depth, CxtI);
257 case Instruction::And:
258 // If either the LHS or the RHS are Zero, the result is zero.
259 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
260 RHSKnownZero, RHSKnownOne, Depth+1) ||
261 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
262 LHSKnownZero, LHSKnownOne, Depth+1))
264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
265 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
267 // If all of the demanded bits are known 1 on one side, return the other.
268 // These bits cannot contribute to the result of the 'and'.
269 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
270 (DemandedMask & ~LHSKnownZero))
271 return I->getOperand(0);
272 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
273 (DemandedMask & ~RHSKnownZero))
274 return I->getOperand(1);
276 // If all of the demanded bits in the inputs are known zeros, return zero.
277 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
278 return Constant::getNullValue(VTy);
280 // If the RHS is a constant, see if we can simplify it.
281 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
284 // Output known-1 bits are only known if set in both the LHS & RHS.
285 KnownOne = RHSKnownOne & LHSKnownOne;
286 // Output known-0 are known to be clear if zero in either the LHS | RHS.
287 KnownZero = RHSKnownZero | LHSKnownZero;
289 case Instruction::Or:
290 // If either the LHS or the RHS are One, the result is One.
291 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
292 RHSKnownZero, RHSKnownOne, Depth+1) ||
293 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
294 LHSKnownZero, LHSKnownOne, Depth+1))
296 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
297 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
299 // If all of the demanded bits are known zero on one side, return the other.
300 // These bits cannot contribute to the result of the 'or'.
301 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
302 (DemandedMask & ~LHSKnownOne))
303 return I->getOperand(0);
304 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
305 (DemandedMask & ~RHSKnownOne))
306 return I->getOperand(1);
308 // If all of the potentially set bits on one side are known to be set on
309 // the other side, just use the 'other' side.
310 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
311 (DemandedMask & (~RHSKnownZero)))
312 return I->getOperand(0);
313 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
314 (DemandedMask & (~LHSKnownZero)))
315 return I->getOperand(1);
317 // If the RHS is a constant, see if we can simplify it.
318 if (ShrinkDemandedConstant(I, 1, DemandedMask))
321 // Output known-0 bits are only known if clear in both the LHS & RHS.
322 KnownZero = RHSKnownZero & LHSKnownZero;
323 // Output known-1 are known to be set if set in either the LHS | RHS.
324 KnownOne = RHSKnownOne | LHSKnownOne;
326 case Instruction::Xor: {
327 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
328 RHSKnownZero, RHSKnownOne, Depth+1) ||
329 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
330 LHSKnownZero, LHSKnownOne, Depth+1))
332 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
333 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
335 // If all of the demanded bits are known zero on one side, return the other.
336 // These bits cannot contribute to the result of the 'xor'.
337 if ((DemandedMask & RHSKnownZero) == DemandedMask)
338 return I->getOperand(0);
339 if ((DemandedMask & LHSKnownZero) == DemandedMask)
340 return I->getOperand(1);
342 // If all of the demanded bits are known to be zero on one side or the
343 // other, turn this into an *inclusive* or.
344 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
345 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
347 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
349 return InsertNewInstWith(Or, *I);
352 // If all of the demanded bits on one side are known, and all of the set
353 // bits on that side are also known to be set on the other side, turn this
354 // into an AND, as we know the bits will be cleared.
355 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
356 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
358 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
359 Constant *AndC = Constant::getIntegerValue(VTy,
360 ~RHSKnownOne & DemandedMask);
361 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
362 return InsertNewInstWith(And, *I);
366 // If the RHS is a constant, see if we can simplify it.
367 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
368 if (ShrinkDemandedConstant(I, 1, DemandedMask))
371 // If our LHS is an 'and' and if it has one use, and if any of the bits we
372 // are flipping are known to be set, then the xor is just resetting those
373 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
374 // simplifying both of them.
375 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
376 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
377 isa<ConstantInt>(I->getOperand(1)) &&
378 isa<ConstantInt>(LHSInst->getOperand(1)) &&
379 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
380 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
381 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
382 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
385 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
386 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
387 InsertNewInstWith(NewAnd, *I);
390 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
391 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
392 return InsertNewInstWith(NewXor, *I);
395 // Output known-0 bits are known if clear or set in both the LHS & RHS.
396 KnownZero= (RHSKnownZero & LHSKnownZero) | (RHSKnownOne & LHSKnownOne);
397 // Output known-1 are known to be set if set in only one of the LHS, RHS.
398 KnownOne = (RHSKnownZero & LHSKnownOne) | (RHSKnownOne & LHSKnownZero);
401 case Instruction::Select:
402 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
403 RHSKnownZero, RHSKnownOne, Depth+1) ||
404 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
405 LHSKnownZero, LHSKnownOne, Depth+1))
407 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
408 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
410 // If the operands are constants, see if we can simplify them.
411 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
412 ShrinkDemandedConstant(I, 2, DemandedMask))
415 // Only known if known in both the LHS and RHS.
416 KnownOne = RHSKnownOne & LHSKnownOne;
417 KnownZero = RHSKnownZero & LHSKnownZero;
419 case Instruction::Trunc: {
420 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
421 DemandedMask = DemandedMask.zext(truncBf);
422 KnownZero = KnownZero.zext(truncBf);
423 KnownOne = KnownOne.zext(truncBf);
424 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
425 KnownZero, KnownOne, Depth+1))
427 DemandedMask = DemandedMask.trunc(BitWidth);
428 KnownZero = KnownZero.trunc(BitWidth);
429 KnownOne = KnownOne.trunc(BitWidth);
430 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
433 case Instruction::BitCast:
434 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
435 return nullptr; // vector->int or fp->int?
437 if (VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
438 if (VectorType *SrcVTy =
439 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
440 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
441 // Don't touch a bitcast between vectors of different element counts.
444 // Don't touch a scalar-to-vector bitcast.
446 } else if (I->getOperand(0)->getType()->isVectorTy())
447 // Don't touch a vector-to-scalar bitcast.
450 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
451 KnownZero, KnownOne, Depth+1))
453 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
455 case Instruction::ZExt: {
456 // Compute the bits in the result that are not present in the input.
457 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
459 DemandedMask = DemandedMask.trunc(SrcBitWidth);
460 KnownZero = KnownZero.trunc(SrcBitWidth);
461 KnownOne = KnownOne.trunc(SrcBitWidth);
462 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
463 KnownZero, KnownOne, Depth+1))
465 DemandedMask = DemandedMask.zext(BitWidth);
466 KnownZero = KnownZero.zext(BitWidth);
467 KnownOne = KnownOne.zext(BitWidth);
468 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
469 // The top bits are known to be zero.
470 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
473 case Instruction::SExt: {
474 // Compute the bits in the result that are not present in the input.
475 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
477 APInt InputDemandedBits = DemandedMask &
478 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
480 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
481 // If any of the sign extended bits are demanded, we know that the sign
483 if ((NewBits & DemandedMask) != 0)
484 InputDemandedBits.setBit(SrcBitWidth-1);
486 InputDemandedBits = InputDemandedBits.trunc(SrcBitWidth);
487 KnownZero = KnownZero.trunc(SrcBitWidth);
488 KnownOne = KnownOne.trunc(SrcBitWidth);
489 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
490 KnownZero, KnownOne, Depth+1))
492 InputDemandedBits = InputDemandedBits.zext(BitWidth);
493 KnownZero = KnownZero.zext(BitWidth);
494 KnownOne = KnownOne.zext(BitWidth);
495 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
497 // If the sign bit of the input is known set or clear, then we know the
498 // top bits of the result.
500 // If the input sign bit is known zero, or if the NewBits are not demanded
501 // convert this into a zero extension.
502 if (KnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
503 // Convert to ZExt cast
504 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
505 return InsertNewInstWith(NewCast, *I);
506 } else if (KnownOne[SrcBitWidth-1]) { // Input sign bit known set
511 case Instruction::Add: {
512 // Figure out what the input bits are. If the top bits of the and result
513 // are not demanded, then the add doesn't demand them from its input
515 unsigned NLZ = DemandedMask.countLeadingZeros();
517 // If there is a constant on the RHS, there are a variety of xformations
519 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
520 // If null, this should be simplified elsewhere. Some of the xforms here
521 // won't work if the RHS is zero.
525 // If the top bit of the output is demanded, demand everything from the
526 // input. Otherwise, we demand all the input bits except NLZ top bits.
527 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
529 // Find information about known zero/one bits in the input.
530 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
531 LHSKnownZero, LHSKnownOne, Depth+1))
534 // If the RHS of the add has bits set that can't affect the input, reduce
536 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
539 // Avoid excess work.
540 if (LHSKnownZero == 0 && LHSKnownOne == 0)
543 // Turn it into OR if input bits are zero.
544 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
546 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
548 return InsertNewInstWith(Or, *I);
551 // We can say something about the output known-zero and known-one bits,
552 // depending on potential carries from the input constant and the
553 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
554 // bits set and the RHS constant is 0x01001, then we know we have a known
555 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
557 // To compute this, we first compute the potential carry bits. These are
558 // the bits which may be modified. I'm not aware of a better way to do
560 const APInt &RHSVal = RHS->getValue();
561 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
563 // Now that we know which bits have carries, compute the known-1/0 sets.
565 // Bits are known one if they are known zero in one operand and one in the
566 // other, and there is no input carry.
567 KnownOne = ((LHSKnownZero & RHSVal) |
568 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
570 // Bits are known zero if they are known zero in both operands and there
571 // is no input carry.
572 KnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
574 // If the high-bits of this ADD are not demanded, then it does not demand
575 // the high bits of its LHS or RHS.
576 if (DemandedMask[BitWidth-1] == 0) {
577 // Right fill the mask of bits for this ADD to demand the most
578 // significant bit and all those below it.
579 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
580 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
581 LHSKnownZero, LHSKnownOne, Depth+1) ||
582 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
583 LHSKnownZero, LHSKnownOne, Depth+1))
589 case Instruction::Sub:
590 // If the high-bits of this SUB are not demanded, then it does not demand
591 // the high bits of its LHS or RHS.
592 if (DemandedMask[BitWidth-1] == 0) {
593 // Right fill the mask of bits for this SUB to demand the most
594 // significant bit and all those below it.
595 uint32_t NLZ = DemandedMask.countLeadingZeros();
596 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
597 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
598 LHSKnownZero, LHSKnownOne, Depth+1) ||
599 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
600 LHSKnownZero, LHSKnownOne, Depth+1))
604 // Otherwise just hand the sub off to computeKnownBits to fill in
605 // the known zeros and ones.
606 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
608 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
610 if (ConstantInt *C0 = dyn_cast<ConstantInt>(I->getOperand(0))) {
611 APInt I0 = C0->getValue();
612 if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
613 Instruction *Xor = BinaryOperator::CreateXor(I->getOperand(1), C0);
614 return InsertNewInstWith(Xor, *I);
618 case Instruction::Shl:
619 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
621 Value *VarX; ConstantInt *C1;
622 if (match(I->getOperand(0), m_Shr(m_Value(VarX), m_ConstantInt(C1)))) {
623 Instruction *Shr = cast<Instruction>(I->getOperand(0));
624 Value *R = SimplifyShrShlDemandedBits(Shr, I, DemandedMask,
625 KnownZero, KnownOne);
631 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
632 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
634 // If the shift is NUW/NSW, then it does demand the high bits.
635 ShlOperator *IOp = cast<ShlOperator>(I);
636 if (IOp->hasNoSignedWrap())
637 DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt+1);
638 else if (IOp->hasNoUnsignedWrap())
639 DemandedMaskIn |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
641 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
642 KnownZero, KnownOne, Depth+1))
644 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
645 KnownZero <<= ShiftAmt;
646 KnownOne <<= ShiftAmt;
647 // low bits known zero.
649 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
652 case Instruction::LShr:
653 // For a logical shift right
654 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
655 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
657 // Unsigned shift right.
658 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
660 // If the shift is exact, then it does demand the low bits (and knows that
662 if (cast<LShrOperator>(I)->isExact())
663 DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
665 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
666 KnownZero, KnownOne, Depth+1))
668 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
669 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
670 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
672 // Compute the new bits that are at the top now.
673 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
674 KnownZero |= HighBits; // high bits known zero.
678 case Instruction::AShr:
679 // If this is an arithmetic shift right and only the low-bit is set, we can
680 // always convert this into a logical shr, even if the shift amount is
681 // variable. The low bit of the shift cannot be an input sign bit unless
682 // the shift amount is >= the size of the datatype, which is undefined.
683 if (DemandedMask == 1) {
684 // Perform the logical shift right.
685 Instruction *NewVal = BinaryOperator::CreateLShr(
686 I->getOperand(0), I->getOperand(1), I->getName());
687 return InsertNewInstWith(NewVal, *I);
690 // If the sign bit is the only bit demanded by this ashr, then there is no
691 // need to do it, the shift doesn't change the high bit.
692 if (DemandedMask.isSignBit())
693 return I->getOperand(0);
695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
696 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
698 // Signed shift right.
699 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
700 // If any of the "high bits" are demanded, we should set the sign bit as
702 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
703 DemandedMaskIn.setBit(BitWidth-1);
705 // If the shift is exact, then it does demand the low bits (and knows that
707 if (cast<AShrOperator>(I)->isExact())
708 DemandedMaskIn |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
710 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
711 KnownZero, KnownOne, Depth+1))
713 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
714 // Compute the new bits that are at the top now.
715 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
716 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
717 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
719 // Handle the sign bits.
720 APInt SignBit(APInt::getSignBit(BitWidth));
721 // Adjust to where it is now in the mask.
722 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
724 // If the input sign bit is known to be zero, or if none of the top bits
725 // are demanded, turn this into an unsigned shift right.
726 if (BitWidth <= ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||
727 (HighBits & ~DemandedMask) == HighBits) {
728 // Perform the logical shift right.
729 BinaryOperator *NewVal = BinaryOperator::CreateLShr(I->getOperand(0),
731 NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
732 return InsertNewInstWith(NewVal, *I);
733 } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
734 KnownOne |= HighBits;
738 case Instruction::SRem:
739 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
740 // X % -1 demands all the bits because we don't want to introduce
741 // INT_MIN % -1 (== undef) by accident.
742 if (Rem->isAllOnesValue())
744 APInt RA = Rem->getValue().abs();
745 if (RA.isPowerOf2()) {
746 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
747 return I->getOperand(0);
749 APInt LowBits = RA - 1;
750 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
751 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
752 LHSKnownZero, LHSKnownOne, Depth+1))
755 // The low bits of LHS are unchanged by the srem.
756 KnownZero = LHSKnownZero & LowBits;
757 KnownOne = LHSKnownOne & LowBits;
759 // If LHS is non-negative or has all low bits zero, then the upper bits
761 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
762 KnownZero |= ~LowBits;
764 // If LHS is negative and not all low bits are zero, then the upper bits
766 if (LHSKnownOne[BitWidth-1] && ((LHSKnownOne & LowBits) != 0))
767 KnownOne |= ~LowBits;
769 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
773 // The sign bit is the LHS's sign bit, except when the result of the
774 // remainder is zero.
775 if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
776 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
777 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth+1,
779 // If it's known zero, our sign bit is also zero.
780 if (LHSKnownZero.isNegative())
781 KnownZero.setBit(KnownZero.getBitWidth() - 1);
784 case Instruction::URem: {
785 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
786 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
787 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
788 KnownZero2, KnownOne2, Depth+1) ||
789 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
790 KnownZero2, KnownOne2, Depth+1))
793 unsigned Leaders = KnownZero2.countLeadingOnes();
794 Leaders = std::max(Leaders,
795 KnownZero2.countLeadingOnes());
796 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
799 case Instruction::Call:
800 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
801 switch (II->getIntrinsicID()) {
803 case Intrinsic::bswap: {
804 // If the only bits demanded come from one byte of the bswap result,
805 // just shift the input byte into position to eliminate the bswap.
806 unsigned NLZ = DemandedMask.countLeadingZeros();
807 unsigned NTZ = DemandedMask.countTrailingZeros();
809 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
810 // we need all the bits down to bit 8. Likewise, round NLZ. If we
811 // have 14 leading zeros, round to 8.
814 // If we need exactly one byte, we can do this transformation.
815 if (BitWidth-NLZ-NTZ == 8) {
816 unsigned ResultBit = NTZ;
817 unsigned InputBit = BitWidth-NTZ-8;
819 // Replace this with either a left or right shift to get the byte into
822 if (InputBit > ResultBit)
823 NewVal = BinaryOperator::CreateLShr(II->getArgOperand(0),
824 ConstantInt::get(I->getType(), InputBit-ResultBit));
826 NewVal = BinaryOperator::CreateShl(II->getArgOperand(0),
827 ConstantInt::get(I->getType(), ResultBit-InputBit));
829 return InsertNewInstWith(NewVal, *I);
832 // TODO: Could compute known zero/one bits based on the input.
835 case Intrinsic::x86_sse42_crc32_64_64:
836 KnownZero = APInt::getHighBitsSet(64, 32);
840 computeKnownBits(V, KnownZero, KnownOne, Depth, CxtI);
844 // If the client is only demanding bits that we know, return the known
846 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
847 return Constant::getIntegerValue(VTy, KnownOne);
851 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
852 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
853 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
856 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
857 /// ..., bn}, without considering the specific value X is holding.
858 /// This transformation is legal iff one of following conditions is hold:
859 /// 1) All the bit in S are 0, in this case E1 == E2.
860 /// 2) We don't care those bits in S, per the input DemandedMask.
861 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
864 /// Currently we only test condition 2).
866 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
868 Value *InstCombiner::SimplifyShrShlDemandedBits(Instruction *Shr,
869 Instruction *Shl, APInt DemandedMask, APInt &KnownZero, APInt &KnownOne) {
871 const APInt &ShlOp1 = cast<ConstantInt>(Shl->getOperand(1))->getValue();
872 const APInt &ShrOp1 = cast<ConstantInt>(Shr->getOperand(1))->getValue();
873 if (!ShlOp1 || !ShrOp1)
874 return nullptr; // Noop.
876 Value *VarX = Shr->getOperand(0);
877 Type *Ty = VarX->getType();
878 unsigned BitWidth = Ty->getIntegerBitWidth();
879 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
880 return nullptr; // Undef.
882 unsigned ShlAmt = ShlOp1.getZExtValue();
883 unsigned ShrAmt = ShrOp1.getZExtValue();
885 KnownOne.clearAllBits();
886 KnownZero = APInt::getBitsSet(KnownZero.getBitWidth(), 0, ShlAmt-1);
887 KnownZero &= DemandedMask;
889 APInt BitMask1(APInt::getAllOnesValue(BitWidth));
890 APInt BitMask2(APInt::getAllOnesValue(BitWidth));
892 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
893 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
894 (BitMask1.ashr(ShrAmt) << ShlAmt);
896 if (ShrAmt <= ShlAmt) {
897 BitMask2 <<= (ShlAmt - ShrAmt);
899 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
900 BitMask2.ashr(ShrAmt - ShlAmt);
903 // Check if condition-2 (see the comment to this function) is satified.
904 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
905 if (ShrAmt == ShlAmt)
908 if (!Shr->hasOneUse())
912 if (ShrAmt < ShlAmt) {
913 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
914 New = BinaryOperator::CreateShl(VarX, Amt);
915 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
916 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
917 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
919 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
920 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
921 BinaryOperator::CreateAShr(VarX, Amt);
922 if (cast<BinaryOperator>(Shr)->isExact())
923 New->setIsExact(true);
926 return InsertNewInstWith(New, *Shl);
932 /// SimplifyDemandedVectorElts - The specified value produces a vector with
933 /// any number of elements. DemandedElts contains the set of elements that are
934 /// actually used by the caller. This method analyzes which elements of the
935 /// operand are undef and returns that information in UndefElts.
937 /// If the information about demanded elements can be used to simplify the
938 /// operation, the operation is simplified, then the resultant value is
939 /// returned. This returns null if no change was made.
940 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
943 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
944 APInt EltMask(APInt::getAllOnesValue(VWidth));
945 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
947 if (isa<UndefValue>(V)) {
948 // If the entire vector is undefined, just return this info.
953 if (DemandedElts == 0) { // If nothing is demanded, provide undef.
955 return UndefValue::get(V->getType());
960 // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
961 if (Constant *C = dyn_cast<Constant>(V)) {
962 // Check if this is identity. If so, return 0 since we are not simplifying
964 if (DemandedElts.isAllOnesValue())
967 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
968 Constant *Undef = UndefValue::get(EltTy);
970 SmallVector<Constant*, 16> Elts;
971 for (unsigned i = 0; i != VWidth; ++i) {
972 if (!DemandedElts[i]) { // If not demanded, set to undef.
973 Elts.push_back(Undef);
978 Constant *Elt = C->getAggregateElement(i);
979 if (!Elt) return nullptr;
981 if (isa<UndefValue>(Elt)) { // Already undef.
982 Elts.push_back(Undef);
984 } else { // Otherwise, defined.
989 // If we changed the constant, return it.
990 Constant *NewCV = ConstantVector::get(Elts);
991 return NewCV != C ? NewCV : nullptr;
994 // Limit search depth.
998 // If multiple users are using the root value, proceed with
999 // simplification conservatively assuming that all elements
1001 if (!V->hasOneUse()) {
1002 // Quit if we find multiple users of a non-root value though.
1003 // They'll be handled when it's their turn to be visited by
1004 // the main instcombine process.
1006 // TODO: Just compute the UndefElts information recursively.
1009 // Conservatively assume that all elements are needed.
1010 DemandedElts = EltMask;
1013 Instruction *I = dyn_cast<Instruction>(V);
1014 if (!I) return nullptr; // Only analyze instructions.
1016 bool MadeChange = false;
1017 APInt UndefElts2(VWidth, 0);
1019 switch (I->getOpcode()) {
1022 case Instruction::InsertElement: {
1023 // If this is a variable index, we don't know which element it overwrites.
1024 // demand exactly the same input as we produce.
1025 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1027 // Note that we can't propagate undef elt info, because we don't know
1028 // which elt is getting updated.
1029 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1030 UndefElts2, Depth+1);
1031 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1035 // If this is inserting an element that isn't demanded, remove this
1037 unsigned IdxNo = Idx->getZExtValue();
1038 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1040 return I->getOperand(0);
1043 // Otherwise, the element inserted overwrites whatever was there, so the
1044 // input demanded set is simpler than the output set.
1045 APInt DemandedElts2 = DemandedElts;
1046 DemandedElts2.clearBit(IdxNo);
1047 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1048 UndefElts, Depth+1);
1049 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1051 // The inserted element is defined.
1052 UndefElts.clearBit(IdxNo);
1055 case Instruction::ShuffleVector: {
1056 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1057 uint64_t LHSVWidth =
1058 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1059 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1060 for (unsigned i = 0; i < VWidth; i++) {
1061 if (DemandedElts[i]) {
1062 unsigned MaskVal = Shuffle->getMaskValue(i);
1063 if (MaskVal != -1u) {
1064 assert(MaskVal < LHSVWidth * 2 &&
1065 "shufflevector mask index out of range!");
1066 if (MaskVal < LHSVWidth)
1067 LeftDemanded.setBit(MaskVal);
1069 RightDemanded.setBit(MaskVal - LHSVWidth);
1074 APInt UndefElts4(LHSVWidth, 0);
1075 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1076 UndefElts4, Depth+1);
1077 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1079 APInt UndefElts3(LHSVWidth, 0);
1080 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1081 UndefElts3, Depth+1);
1082 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1084 bool NewUndefElts = false;
1085 for (unsigned i = 0; i < VWidth; i++) {
1086 unsigned MaskVal = Shuffle->getMaskValue(i);
1087 if (MaskVal == -1u) {
1088 UndefElts.setBit(i);
1089 } else if (!DemandedElts[i]) {
1090 NewUndefElts = true;
1091 UndefElts.setBit(i);
1092 } else if (MaskVal < LHSVWidth) {
1093 if (UndefElts4[MaskVal]) {
1094 NewUndefElts = true;
1095 UndefElts.setBit(i);
1098 if (UndefElts3[MaskVal - LHSVWidth]) {
1099 NewUndefElts = true;
1100 UndefElts.setBit(i);
1106 // Add additional discovered undefs.
1107 SmallVector<Constant*, 16> Elts;
1108 for (unsigned i = 0; i < VWidth; ++i) {
1110 Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
1112 Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
1113 Shuffle->getMaskValue(i)));
1115 I->setOperand(2, ConstantVector::get(Elts));
1120 case Instruction::Select: {
1121 APInt LeftDemanded(DemandedElts), RightDemanded(DemandedElts);
1122 if (ConstantVector* CV = dyn_cast<ConstantVector>(I->getOperand(0))) {
1123 for (unsigned i = 0; i < VWidth; i++) {
1124 if (CV->getAggregateElement(i)->isNullValue())
1125 LeftDemanded.clearBit(i);
1127 RightDemanded.clearBit(i);
1131 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), LeftDemanded,
1132 UndefElts, Depth+1);
1133 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1135 TmpV = SimplifyDemandedVectorElts(I->getOperand(2), RightDemanded,
1136 UndefElts2, Depth+1);
1137 if (TmpV) { I->setOperand(2, TmpV); MadeChange = true; }
1139 // Output elements are undefined if both are undefined.
1140 UndefElts &= UndefElts2;
1143 case Instruction::BitCast: {
1144 // Vector->vector casts only.
1145 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1147 unsigned InVWidth = VTy->getNumElements();
1148 APInt InputDemandedElts(InVWidth, 0);
1151 if (VWidth == InVWidth) {
1152 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1153 // elements as are demanded of us.
1155 InputDemandedElts = DemandedElts;
1156 } else if (VWidth > InVWidth) {
1160 // If there are more elements in the result than there are in the source,
1161 // then an input element is live if any of the corresponding output
1162 // elements are live.
1163 Ratio = VWidth/InVWidth;
1164 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1165 if (DemandedElts[OutIdx])
1166 InputDemandedElts.setBit(OutIdx/Ratio);
1172 // If there are more elements in the source than there are in the result,
1173 // then an input element is live if the corresponding output element is
1175 Ratio = InVWidth/VWidth;
1176 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1177 if (DemandedElts[InIdx/Ratio])
1178 InputDemandedElts.setBit(InIdx);
1181 // div/rem demand all inputs, because they don't want divide by zero.
1182 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1183 UndefElts2, Depth+1);
1185 I->setOperand(0, TmpV);
1189 UndefElts = UndefElts2;
1190 if (VWidth > InVWidth) {
1191 llvm_unreachable("Unimp");
1192 // If there are more elements in the result than there are in the source,
1193 // then an output element is undef if the corresponding input element is
1195 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1196 if (UndefElts2[OutIdx/Ratio])
1197 UndefElts.setBit(OutIdx);
1198 } else if (VWidth < InVWidth) {
1199 llvm_unreachable("Unimp");
1200 // If there are more elements in the source than there are in the result,
1201 // then a result element is undef if all of the corresponding input
1202 // elements are undef.
1203 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1204 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1205 if (!UndefElts2[InIdx]) // Not undef?
1206 UndefElts.clearBit(InIdx/Ratio); // Clear undef bit.
1210 case Instruction::And:
1211 case Instruction::Or:
1212 case Instruction::Xor:
1213 case Instruction::Add:
1214 case Instruction::Sub:
1215 case Instruction::Mul:
1216 // div/rem demand all inputs, because they don't want divide by zero.
1217 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1218 UndefElts, Depth+1);
1219 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1220 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1221 UndefElts2, Depth+1);
1222 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1224 // Output elements are undefined if both are undefined. Consider things
1225 // like undef&0. The result is known zero, not undef.
1226 UndefElts &= UndefElts2;
1228 case Instruction::FPTrunc:
1229 case Instruction::FPExt:
1230 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1231 UndefElts, Depth+1);
1232 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1235 case Instruction::Call: {
1236 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1238 switch (II->getIntrinsicID()) {
1241 // Binary vector operations that work column-wise. A dest element is a
1242 // function of the corresponding input elements from the two inputs.
1243 case Intrinsic::x86_sse_sub_ss:
1244 case Intrinsic::x86_sse_mul_ss:
1245 case Intrinsic::x86_sse_min_ss:
1246 case Intrinsic::x86_sse_max_ss:
1247 case Intrinsic::x86_sse2_sub_sd:
1248 case Intrinsic::x86_sse2_mul_sd:
1249 case Intrinsic::x86_sse2_min_sd:
1250 case Intrinsic::x86_sse2_max_sd:
1251 TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), DemandedElts,
1252 UndefElts, Depth+1);
1253 if (TmpV) { II->setArgOperand(0, TmpV); MadeChange = true; }
1254 TmpV = SimplifyDemandedVectorElts(II->getArgOperand(1), DemandedElts,
1255 UndefElts2, Depth+1);
1256 if (TmpV) { II->setArgOperand(1, TmpV); MadeChange = true; }
1258 // If only the low elt is demanded and this is a scalarizable intrinsic,
1259 // scalarize it now.
1260 if (DemandedElts == 1) {
1261 switch (II->getIntrinsicID()) {
1263 case Intrinsic::x86_sse_sub_ss:
1264 case Intrinsic::x86_sse_mul_ss:
1265 case Intrinsic::x86_sse2_sub_sd:
1266 case Intrinsic::x86_sse2_mul_sd:
1267 // TODO: Lower MIN/MAX/ABS/etc
1268 Value *LHS = II->getArgOperand(0);
1269 Value *RHS = II->getArgOperand(1);
1270 // Extract the element as scalars.
1271 LHS = InsertNewInstWith(ExtractElementInst::Create(LHS,
1272 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1273 RHS = InsertNewInstWith(ExtractElementInst::Create(RHS,
1274 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
1276 switch (II->getIntrinsicID()) {
1277 default: llvm_unreachable("Case stmts out of sync!");
1278 case Intrinsic::x86_sse_sub_ss:
1279 case Intrinsic::x86_sse2_sub_sd:
1280 TmpV = InsertNewInstWith(BinaryOperator::CreateFSub(LHS, RHS,
1281 II->getName()), *II);
1283 case Intrinsic::x86_sse_mul_ss:
1284 case Intrinsic::x86_sse2_mul_sd:
1285 TmpV = InsertNewInstWith(BinaryOperator::CreateFMul(LHS, RHS,
1286 II->getName()), *II);
1291 InsertElementInst::Create(
1292 UndefValue::get(II->getType()), TmpV,
1293 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1295 InsertNewInstWith(New, *II);
1300 // Output elements are undefined if both are undefined. Consider things
1301 // like undef&0. The result is known zero, not undef.
1302 UndefElts &= UndefElts2;
1308 return MadeChange ? I : nullptr;