LLVM  16.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
1 //===- InstCombineCompares.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 implements the visitICmp and visitFCmp functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Support/KnownBits.h"
27 
28 using namespace llvm;
29 using namespace PatternMatch;
30 
31 #define DEBUG_TYPE "instcombine"
32 
33 // How many times is a select replaced by one of its operands?
34 STATISTIC(NumSel, "Number of select opts");
35 
36 
37 /// Compute Result = In1+In2, returning true if the result overflowed for this
38 /// type.
39 static bool addWithOverflow(APInt &Result, const APInt &In1,
40  const APInt &In2, bool IsSigned = false) {
41  bool Overflow;
42  if (IsSigned)
43  Result = In1.sadd_ov(In2, Overflow);
44  else
45  Result = In1.uadd_ov(In2, Overflow);
46 
47  return Overflow;
48 }
49 
50 /// Compute Result = In1-In2, returning true if the result overflowed for this
51 /// type.
52 static bool subWithOverflow(APInt &Result, const APInt &In1,
53  const APInt &In2, bool IsSigned = false) {
54  bool Overflow;
55  if (IsSigned)
56  Result = In1.ssub_ov(In2, Overflow);
57  else
58  Result = In1.usub_ov(In2, Overflow);
59 
60  return Overflow;
61 }
62 
63 /// Given an icmp instruction, return true if any use of this comparison is a
64 /// branch on sign bit comparison.
65 static bool hasBranchUse(ICmpInst &I) {
66  for (auto *U : I.users())
67  if (isa<BranchInst>(U))
68  return true;
69  return false;
70 }
71 
72 /// Returns true if the exploded icmp can be expressed as a signed comparison
73 /// to zero and updates the predicate accordingly.
74 /// The signedness of the comparison is preserved.
75 /// TODO: Refactor with decomposeBitTestICmp()?
76 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
77  if (!ICmpInst::isSigned(Pred))
78  return false;
79 
80  if (C.isZero())
81  return ICmpInst::isRelational(Pred);
82 
83  if (C.isOne()) {
84  if (Pred == ICmpInst::ICMP_SLT) {
85  Pred = ICmpInst::ICMP_SLE;
86  return true;
87  }
88  } else if (C.isAllOnes()) {
89  if (Pred == ICmpInst::ICMP_SGT) {
90  Pred = ICmpInst::ICMP_SGE;
91  return true;
92  }
93  }
94 
95  return false;
96 }
97 
98 /// This is called when we see this pattern:
99 /// cmp pred (load (gep GV, ...)), cmpcst
100 /// where GV is a global variable with a constant initializer. Try to simplify
101 /// this into some simple computation that does not need the load. For example
102 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
103 ///
104 /// If AndCst is non-null, then the loaded value is masked with that constant
105 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
108  ConstantInt *AndCst) {
109  if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
110  GV->getValueType() != GEP->getSourceElementType() ||
111  !GV->isConstant() || !GV->hasDefinitiveInitializer())
112  return nullptr;
113 
114  Constant *Init = GV->getInitializer();
115  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
116  return nullptr;
117 
118  uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
119  // Don't blow up on huge arrays.
120  if (ArrayElementCount > MaxArraySizeForCombine)
121  return nullptr;
122 
123  // There are many forms of this optimization we can handle, for now, just do
124  // the simple index into a single-dimensional array.
125  //
126  // Require: GEP GV, 0, i {{, constant indices}}
127  if (GEP->getNumOperands() < 3 ||
128  !isa<ConstantInt>(GEP->getOperand(1)) ||
129  !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
130  isa<Constant>(GEP->getOperand(2)))
131  return nullptr;
132 
133  // Check that indices after the variable are constants and in-range for the
134  // type they index. Collect the indices. This is typically for arrays of
135  // structs.
136  SmallVector<unsigned, 4> LaterIndices;
137 
138  Type *EltTy = Init->getType()->getArrayElementType();
139  for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
140  ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
141  if (!Idx) return nullptr; // Variable index.
142 
143  uint64_t IdxVal = Idx->getZExtValue();
144  if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
145 
146  if (StructType *STy = dyn_cast<StructType>(EltTy))
147  EltTy = STy->getElementType(IdxVal);
148  else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
149  if (IdxVal >= ATy->getNumElements()) return nullptr;
150  EltTy = ATy->getElementType();
151  } else {
152  return nullptr; // Unknown type.
153  }
154 
155  LaterIndices.push_back(IdxVal);
156  }
157 
158  enum { Overdefined = -3, Undefined = -2 };
159 
160  // Variables for our state machines.
161 
162  // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
163  // "i == 47 | i == 87", where 47 is the first index the condition is true for,
164  // and 87 is the second (and last) index. FirstTrueElement is -2 when
165  // undefined, otherwise set to the first true element. SecondTrueElement is
166  // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
167  int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
168 
169  // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
170  // form "i != 47 & i != 87". Same state transitions as for true elements.
171  int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
172 
173  /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
174  /// define a state machine that triggers for ranges of values that the index
175  /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
176  /// This is -2 when undefined, -3 when overdefined, and otherwise the last
177  /// index in the range (inclusive). We use -2 for undefined here because we
178  /// use relative comparisons and don't want 0-1 to match -1.
179  int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
180 
181  // MagicBitvector - This is a magic bitvector where we set a bit if the
182  // comparison is true for element 'i'. If there are 64 elements or less in
183  // the array, this will fully represent all the comparison results.
184  uint64_t MagicBitvector = 0;
185 
186  // Scan the array and see if one of our patterns matches.
187  Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
188  for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
189  Constant *Elt = Init->getAggregateElement(i);
190  if (!Elt) return nullptr;
191 
192  // If this is indexing an array of structures, get the structure element.
193  if (!LaterIndices.empty()) {
194  Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
195  if (!Elt)
196  return nullptr;
197  }
198 
199  // If the element is masked, handle it.
200  if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
201 
202  // Find out if the comparison would be true or false for the i'th element.
204  CompareRHS, DL, &TLI);
205  // If the result is undef for this element, ignore it.
206  if (isa<UndefValue>(C)) {
207  // Extend range state machines to cover this element in case there is an
208  // undef in the middle of the range.
209  if (TrueRangeEnd == (int)i-1)
210  TrueRangeEnd = i;
211  if (FalseRangeEnd == (int)i-1)
212  FalseRangeEnd = i;
213  continue;
214  }
215 
216  // If we can't compute the result for any of the elements, we have to give
217  // up evaluating the entire conditional.
218  if (!isa<ConstantInt>(C)) return nullptr;
219 
220  // Otherwise, we know if the comparison is true or false for this element,
221  // update our state machines.
222  bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
223 
224  // State machine for single/double/range index comparison.
225  if (IsTrueForElt) {
226  // Update the TrueElement state machine.
227  if (FirstTrueElement == Undefined)
228  FirstTrueElement = TrueRangeEnd = i; // First true element.
229  else {
230  // Update double-compare state machine.
231  if (SecondTrueElement == Undefined)
232  SecondTrueElement = i;
233  else
234  SecondTrueElement = Overdefined;
235 
236  // Update range state machine.
237  if (TrueRangeEnd == (int)i-1)
238  TrueRangeEnd = i;
239  else
240  TrueRangeEnd = Overdefined;
241  }
242  } else {
243  // Update the FalseElement state machine.
244  if (FirstFalseElement == Undefined)
245  FirstFalseElement = FalseRangeEnd = i; // First false element.
246  else {
247  // Update double-compare state machine.
248  if (SecondFalseElement == Undefined)
249  SecondFalseElement = i;
250  else
251  SecondFalseElement = Overdefined;
252 
253  // Update range state machine.
254  if (FalseRangeEnd == (int)i-1)
255  FalseRangeEnd = i;
256  else
257  FalseRangeEnd = Overdefined;
258  }
259  }
260 
261  // If this element is in range, update our magic bitvector.
262  if (i < 64 && IsTrueForElt)
263  MagicBitvector |= 1ULL << i;
264 
265  // If all of our states become overdefined, bail out early. Since the
266  // predicate is expensive, only check it every 8 elements. This is only
267  // really useful for really huge arrays.
268  if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
269  SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
270  FalseRangeEnd == Overdefined)
271  return nullptr;
272  }
273 
274  // Now that we've scanned the entire array, emit our new comparison(s). We
275  // order the state machines in complexity of the generated code.
276  Value *Idx = GEP->getOperand(2);
277 
278  // If the index is larger than the pointer size of the target, truncate the
279  // index down like the GEP would do implicitly. We don't have to do this for
280  // an inbounds GEP because the index can't be out of range.
281  if (!GEP->isInBounds()) {
282  Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
283  unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
284  if (Idx->getType()->getPrimitiveSizeInBits().getFixedSize() > PtrSize)
285  Idx = Builder.CreateTrunc(Idx, IntPtrTy);
286  }
287 
288  // If inbounds keyword is not present, Idx * ElementSize can overflow.
289  // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
290  // Then, there are two possible values for Idx to match offset 0:
291  // 0x00..00, 0x80..00.
292  // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
293  // comparison is false if Idx was 0x80..00.
294  // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
295  unsigned ElementSize =
296  DL.getTypeAllocSize(Init->getType()->getArrayElementType());
297  auto MaskIdx = [&](Value* Idx){
298  if (!GEP->isInBounds() && countTrailingZeros(ElementSize) != 0) {
299  Value *Mask = ConstantInt::get(Idx->getType(), -1);
300  Mask = Builder.CreateLShr(Mask, countTrailingZeros(ElementSize));
301  Idx = Builder.CreateAnd(Idx, Mask);
302  }
303  return Idx;
304  };
305 
306  // If the comparison is only true for one or two elements, emit direct
307  // comparisons.
308  if (SecondTrueElement != Overdefined) {
309  Idx = MaskIdx(Idx);
310  // None true -> false.
311  if (FirstTrueElement == Undefined)
312  return replaceInstUsesWith(ICI, Builder.getFalse());
313 
314  Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
315 
316  // True for one element -> 'i == 47'.
317  if (SecondTrueElement == Undefined)
318  return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
319 
320  // True for two elements -> 'i == 47 | i == 72'.
321  Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
322  Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
323  Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
324  return BinaryOperator::CreateOr(C1, C2);
325  }
326 
327  // If the comparison is only false for one or two elements, emit direct
328  // comparisons.
329  if (SecondFalseElement != Overdefined) {
330  Idx = MaskIdx(Idx);
331  // None false -> true.
332  if (FirstFalseElement == Undefined)
333  return replaceInstUsesWith(ICI, Builder.getTrue());
334 
335  Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
336 
337  // False for one element -> 'i != 47'.
338  if (SecondFalseElement == Undefined)
339  return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
340 
341  // False for two elements -> 'i != 47 & i != 72'.
342  Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
343  Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
344  Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
345  return BinaryOperator::CreateAnd(C1, C2);
346  }
347 
348  // If the comparison can be replaced with a range comparison for the elements
349  // where it is true, emit the range check.
350  if (TrueRangeEnd != Overdefined) {
351  assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
352  Idx = MaskIdx(Idx);
353 
354  // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
355  if (FirstTrueElement) {
356  Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
357  Idx = Builder.CreateAdd(Idx, Offs);
358  }
359 
360  Value *End = ConstantInt::get(Idx->getType(),
361  TrueRangeEnd-FirstTrueElement+1);
362  return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
363  }
364 
365  // False range check.
366  if (FalseRangeEnd != Overdefined) {
367  assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
368  Idx = MaskIdx(Idx);
369  // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
370  if (FirstFalseElement) {
371  Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
372  Idx = Builder.CreateAdd(Idx, Offs);
373  }
374 
375  Value *End = ConstantInt::get(Idx->getType(),
376  FalseRangeEnd-FirstFalseElement);
377  return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
378  }
379 
380  // If a magic bitvector captures the entire comparison state
381  // of this load, replace it with computation that does:
382  // ((magic_cst >> i) & 1) != 0
383  {
384  Type *Ty = nullptr;
385 
386  // Look for an appropriate type:
387  // - The type of Idx if the magic fits
388  // - The smallest fitting legal type
389  if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
390  Ty = Idx->getType();
391  else
392  Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
393 
394  if (Ty) {
395  Idx = MaskIdx(Idx);
396  Value *V = Builder.CreateIntCast(Idx, Ty, false);
397  V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
398  V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
399  return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
400  }
401  }
402 
403  return nullptr;
404 }
405 
406 /// Return a value that can be used to compare the *offset* implied by a GEP to
407 /// zero. For example, if we have &A[i], we want to return 'i' for
408 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales
409 /// are involved. The above expression would also be legal to codegen as
410 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32).
411 /// This latter form is less amenable to optimization though, and we are allowed
412 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
413 ///
414 /// If we can't emit an optimized form for this expression, this returns null.
415 ///
417  const DataLayout &DL) {
419 
420  // Check to see if this gep only has a single variable index. If so, and if
421  // any constant indices are a multiple of its scale, then we can compute this
422  // in terms of the scale of the variable index. For example, if the GEP
423  // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
424  // because the expression will cross zero at the same point.
425  unsigned i, e = GEP->getNumOperands();
426  int64_t Offset = 0;
427  for (i = 1; i != e; ++i, ++GTI) {
428  if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
429  // Compute the aggregate offset of constant indices.
430  if (CI->isZero()) continue;
431 
432  // Handle a struct index, which adds its field offset to the pointer.
433  if (StructType *STy = GTI.getStructTypeOrNull()) {
434  Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
435  } else {
436  uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
437  Offset += Size*CI->getSExtValue();
438  }
439  } else {
440  // Found our variable index.
441  break;
442  }
443  }
444 
445  // If there are no variable indices, we must have a constant offset, just
446  // evaluate it the general way.
447  if (i == e) return nullptr;
448 
449  Value *VariableIdx = GEP->getOperand(i);
450  // Determine the scale factor of the variable element. For example, this is
451  // 4 if the variable index is into an array of i32.
452  uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType());
453 
454  // Verify that there are no other variable indices. If so, emit the hard way.
455  for (++i, ++GTI; i != e; ++i, ++GTI) {
456  ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
457  if (!CI) return nullptr;
458 
459  // Compute the aggregate offset of constant indices.
460  if (CI->isZero()) continue;
461 
462  // Handle a struct index, which adds its field offset to the pointer.
463  if (StructType *STy = GTI.getStructTypeOrNull()) {
464  Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
465  } else {
466  uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType());
467  Offset += Size*CI->getSExtValue();
468  }
469  }
470 
471  // Okay, we know we have a single variable index, which must be a
472  // pointer/array/vector index. If there is no offset, life is simple, return
473  // the index.
474  Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType());
475  unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth();
476  if (Offset == 0) {
477  // Cast to intptrty in case a truncation occurs. If an extension is needed,
478  // we don't need to bother extending: the extension won't affect where the
479  // computation crosses zero.
480  if (VariableIdx->getType()->getPrimitiveSizeInBits().getFixedSize() >
481  IntPtrWidth) {
482  VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy);
483  }
484  return VariableIdx;
485  }
486 
487  // Otherwise, there is an index. The computation we will do will be modulo
488  // the pointer size.
489  Offset = SignExtend64(Offset, IntPtrWidth);
490  VariableScale = SignExtend64(VariableScale, IntPtrWidth);
491 
492  // To do this transformation, any constant index must be a multiple of the
493  // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
494  // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
495  // multiple of the variable scale.
496  int64_t NewOffs = Offset / (int64_t)VariableScale;
497  if (Offset != NewOffs*(int64_t)VariableScale)
498  return nullptr;
499 
500  // Okay, we can do this evaluation. Start by converting the index to intptr.
501  if (VariableIdx->getType() != IntPtrTy)
502  VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy,
503  true /*Signed*/);
504  Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
505  return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset");
506 }
507 
508 /// Returns true if we can rewrite Start as a GEP with pointer Base
509 /// and some integer offset. The nodes that need to be re-written
510 /// for this transformation will be added to Explored.
511 static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
512  const DataLayout &DL,
513  SetVector<Value *> &Explored) {
514  SmallVector<Value *, 16> WorkList(1, Start);
515  Explored.insert(Base);
516 
517  // The following traversal gives us an order which can be used
518  // when doing the final transformation. Since in the final
519  // transformation we create the PHI replacement instructions first,
520  // we don't have to get them in any particular order.
521  //
522  // However, for other instructions we will have to traverse the
523  // operands of an instruction first, which means that we have to
524  // do a post-order traversal.
525  while (!WorkList.empty()) {
527 
528  while (!WorkList.empty()) {
529  if (Explored.size() >= 100)
530  return false;
531 
532  Value *V = WorkList.back();
533 
534  if (Explored.contains(V)) {
535  WorkList.pop_back();
536  continue;
537  }
538 
539  if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
540  !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
541  // We've found some value that we can't explore which is different from
542  // the base. Therefore we can't do this transformation.
543  return false;
544 
545  if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
546  auto *CI = cast<CastInst>(V);
547  if (!CI->isNoopCast(DL))
548  return false;
549 
550  if (!Explored.contains(CI->getOperand(0)))
551  WorkList.push_back(CI->getOperand(0));
552  }
553 
554  if (auto *GEP = dyn_cast<GEPOperator>(V)) {
555  // We're limiting the GEP to having one index. This will preserve
556  // the original pointer type. We could handle more cases in the
557  // future.
558  if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
559  GEP->getSourceElementType() != ElemTy)
560  return false;
561 
562  if (!Explored.contains(GEP->getOperand(0)))
563  WorkList.push_back(GEP->getOperand(0));
564  }
565 
566  if (WorkList.back() == V) {
567  WorkList.pop_back();
568  // We've finished visiting this node, mark it as such.
569  Explored.insert(V);
570  }
571 
572  if (auto *PN = dyn_cast<PHINode>(V)) {
573  // We cannot transform PHIs on unsplittable basic blocks.
574  if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
575  return false;
576  Explored.insert(PN);
577  PHIs.insert(PN);
578  }
579  }
580 
581  // Explore the PHI nodes further.
582  for (auto *PN : PHIs)
583  for (Value *Op : PN->incoming_values())
584  if (!Explored.contains(Op))
585  WorkList.push_back(Op);
586  }
587 
588  // Make sure that we can do this. Since we can't insert GEPs in a basic
589  // block before a PHI node, we can't easily do this transformation if
590  // we have PHI node users of transformed instructions.
591  for (Value *Val : Explored) {
592  for (Value *Use : Val->uses()) {
593 
594  auto *PHI = dyn_cast<PHINode>(Use);
595  auto *Inst = dyn_cast<Instruction>(Val);
596 
597  if (Inst == Base || Inst == PHI || !Inst || !PHI ||
598  !Explored.contains(PHI))
599  continue;
600 
601  if (PHI->getParent() == Inst->getParent())
602  return false;
603  }
604  }
605  return true;
606 }
607 
608 // Sets the appropriate insert point on Builder where we can add
609 // a replacement Instruction for V (if that is possible).
611  bool Before = true) {
612  if (auto *PHI = dyn_cast<PHINode>(V)) {
613  Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
614  return;
615  }
616  if (auto *I = dyn_cast<Instruction>(V)) {
617  if (!Before)
618  I = &*std::next(I->getIterator());
619  Builder.SetInsertPoint(I);
620  return;
621  }
622  if (auto *A = dyn_cast<Argument>(V)) {
623  // Set the insertion point in the entry block.
624  BasicBlock &Entry = A->getParent()->getEntryBlock();
625  Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
626  return;
627  }
628  // Otherwise, this is a constant and we don't need to set a new
629  // insertion point.
630  assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
631 }
632 
633 /// Returns a re-written value of Start as an indexed GEP using Base as a
634 /// pointer.
635 static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
636  const DataLayout &DL,
637  SetVector<Value *> &Explored) {
638  // Perform all the substitutions. This is a bit tricky because we can
639  // have cycles in our use-def chains.
640  // 1. Create the PHI nodes without any incoming values.
641  // 2. Create all the other values.
642  // 3. Add the edges for the PHI nodes.
643  // 4. Emit GEPs to get the original pointers.
644  // 5. Remove the original instructions.
645  Type *IndexType = IntegerType::get(
646  Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
647 
649  NewInsts[Base] = ConstantInt::getNullValue(IndexType);
650 
651  // Create the new PHI nodes, without adding any incoming values.
652  for (Value *Val : Explored) {
653  if (Val == Base)
654  continue;
655  // Create empty phi nodes. This avoids cyclic dependencies when creating
656  // the remaining instructions.
657  if (auto *PHI = dyn_cast<PHINode>(Val))
658  NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
659  PHI->getName() + ".idx", PHI);
660  }
661  IRBuilder<> Builder(Base->getContext());
662 
663  // Create all the other instructions.
664  for (Value *Val : Explored) {
665 
666  if (NewInsts.find(Val) != NewInsts.end())
667  continue;
668 
669  if (auto *CI = dyn_cast<CastInst>(Val)) {
670  // Don't get rid of the intermediate variable here; the store can grow
671  // the map which will invalidate the reference to the input value.
672  Value *V = NewInsts[CI->getOperand(0)];
673  NewInsts[CI] = V;
674  continue;
675  }
676  if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
677  Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
678  : GEP->getOperand(1);
680  // Indices might need to be sign extended. GEPs will magically do
681  // this, but we need to do it ourselves here.
682  if (Index->getType()->getScalarSizeInBits() !=
683  NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
684  Index = Builder.CreateSExtOrTrunc(
685  Index, NewInsts[GEP->getOperand(0)]->getType(),
686  GEP->getOperand(0)->getName() + ".sext");
687  }
688 
689  auto *Op = NewInsts[GEP->getOperand(0)];
690  if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
691  NewInsts[GEP] = Index;
692  else
693  NewInsts[GEP] = Builder.CreateNSWAdd(
694  Op, Index, GEP->getOperand(0)->getName() + ".add");
695  continue;
696  }
697  if (isa<PHINode>(Val))
698  continue;
699 
700  llvm_unreachable("Unexpected instruction type");
701  }
702 
703  // Add the incoming values to the PHI nodes.
704  for (Value *Val : Explored) {
705  if (Val == Base)
706  continue;
707  // All the instructions have been created, we can now add edges to the
708  // phi nodes.
709  if (auto *PHI = dyn_cast<PHINode>(Val)) {
710  PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
711  for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
712  Value *NewIncoming = PHI->getIncomingValue(I);
713 
714  if (NewInsts.find(NewIncoming) != NewInsts.end())
715  NewIncoming = NewInsts[NewIncoming];
716 
717  NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
718  }
719  }
720  }
721 
722  PointerType *PtrTy =
723  ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
724  for (Value *Val : Explored) {
725  if (Val == Base)
726  continue;
727 
728  // Depending on the type, for external users we have to emit
729  // a GEP or a GEP + ptrtoint.
730  setInsertionPoint(Builder, Val, false);
731 
732  // Cast base to the expected type.
733  Value *NewVal = Builder.CreateBitOrPointerCast(
734  Base, PtrTy, Start->getName() + "to.ptr");
735  NewVal = Builder.CreateInBoundsGEP(
736  ElemTy, NewVal, makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr");
737  NewVal = Builder.CreateBitOrPointerCast(
738  NewVal, Val->getType(), Val->getName() + ".conv");
739  Val->replaceAllUsesWith(NewVal);
740  }
741 
742  return NewInsts[Start];
743 }
744 
745 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
746 /// the input Value as a constant indexed GEP. Returns a pair containing
747 /// the GEPs Pointer and Index.
748 static std::pair<Value *, Value *>
750  Type *IndexType = IntegerType::get(V->getContext(),
751  DL.getIndexTypeSizeInBits(V->getType()));
752 
754  while (true) {
755  if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
756  // We accept only inbouds GEPs here to exclude the possibility of
757  // overflow.
758  if (!GEP->isInBounds())
759  break;
760  if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
761  GEP->getSourceElementType() == ElemTy) {
762  V = GEP->getOperand(0);
763  Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
765  Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
766  continue;
767  }
768  break;
769  }
770  if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
771  if (!CI->isNoopCast(DL))
772  break;
773  V = CI->getOperand(0);
774  continue;
775  }
776  if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
777  if (!CI->isNoopCast(DL))
778  break;
779  V = CI->getOperand(0);
780  continue;
781  }
782  break;
783  }
784  return {V, Index};
785 }
786 
787 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
788 /// We can look through PHIs, GEPs and casts in order to determine a common base
789 /// between GEPLHS and RHS.
792  const DataLayout &DL) {
793  // FIXME: Support vector of pointers.
794  if (GEPLHS->getType()->isVectorTy())
795  return nullptr;
796 
797  if (!GEPLHS->hasAllConstantIndices())
798  return nullptr;
799 
800  Type *ElemTy = GEPLHS->getSourceElementType();
801  Value *PtrBase, *Index;
802  std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
803 
804  // The set of nodes that will take part in this transformation.
805  SetVector<Value *> Nodes;
806 
807  if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
808  return nullptr;
809 
810  // We know we can re-write this as
811  // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
812  // Since we've only looked through inbouds GEPs we know that we
813  // can't have overflow on either side. We can therefore re-write
814  // this as:
815  // OFFSET1 cmp OFFSET2
816  Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes);
817 
818  // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
819  // GEP having PtrBase as the pointer base, and has returned in NewRHS the
820  // offset. Since Index is the offset of LHS to the base pointer, we will now
821  // compare the offsets instead of comparing the pointers.
822  return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
823 }
824 
825 /// Fold comparisons between a GEP instruction and something else. At this point
826 /// we know that the GEP is on the LHS of the comparison.
829  Instruction &I) {
830  // Don't transform signed compares of GEPs into index compares. Even if the
831  // GEP is inbounds, the final add of the base pointer can have signed overflow
832  // and would change the result of the icmp.
833  // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
834  // the maximum signed value for the pointer type.
836  return nullptr;
837 
838  // Look through bitcasts and addrspacecasts. We do not however want to remove
839  // 0 GEPs.
840  if (!isa<GetElementPtrInst>(RHS))
842 
843  Value *PtrBase = GEPLHS->getOperand(0);
844  // FIXME: Support vector pointer GEPs.
845  if (PtrBase == RHS && GEPLHS->isInBounds() &&
846  !GEPLHS->getType()->isVectorTy()) {
847  // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
848  // This transformation (ignoring the base and scales) is valid because we
849  // know pointers can't overflow since the gep is inbounds. See if we can
850  // output an optimized form.
851  Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL);
852 
853  // If not, synthesize the offset the hard way.
854  if (!Offset)
855  Offset = EmitGEPOffset(GEPLHS);
856  return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
857  Constant::getNullValue(Offset->getType()));
858  }
859 
860  if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
861  isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
862  !NullPointerIsDefined(I.getFunction(),
864  // For most address spaces, an allocation can't be placed at null, but null
865  // itself is treated as a 0 size allocation in the in bounds rules. Thus,
866  // the only valid inbounds address derived from null, is null itself.
867  // Thus, we have four cases to consider:
868  // 1) Base == nullptr, Offset == 0 -> inbounds, null
869  // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
870  // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
871  // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
872  //
873  // (Note if we're indexing a type of size 0, that simply collapses into one
874  // of the buckets above.)
875  //
876  // In general, we're allowed to make values less poison (i.e. remove
877  // sources of full UB), so in this case, we just select between the two
878  // non-poison cases (1 and 4 above).
879  //
880  // For vectors, we apply the same reasoning on a per-lane basis.
881  auto *Base = GEPLHS->getPointerOperand();
882  if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
883  auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
884  Base = Builder.CreateVectorSplat(EC, Base);
885  }
886  return new ICmpInst(Cond, Base,
888  cast<Constant>(RHS), Base->getType()));
889  } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
890  // If the base pointers are different, but the indices are the same, just
891  // compare the base pointer.
892  if (PtrBase != GEPRHS->getOperand(0)) {
893  bool IndicesTheSame =
894  GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
895  GEPLHS->getPointerOperand()->getType() ==
896  GEPRHS->getPointerOperand()->getType() &&
897  GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
898  if (IndicesTheSame)
899  for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
900  if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
901  IndicesTheSame = false;
902  break;
903  }
904 
905  // If all indices are the same, just compare the base pointers.
906  Type *BaseType = GEPLHS->getOperand(0)->getType();
907  if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
908  return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
909 
910  // If we're comparing GEPs with two base pointers that only differ in type
911  // and both GEPs have only constant indices or just one use, then fold
912  // the compare with the adjusted indices.
913  // FIXME: Support vector of pointers.
914  if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
915  (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
916  (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
917  PtrBase->stripPointerCasts() ==
918  GEPRHS->getOperand(0)->stripPointerCasts() &&
919  !GEPLHS->getType()->isVectorTy()) {
920  Value *LOffset = EmitGEPOffset(GEPLHS);
921  Value *ROffset = EmitGEPOffset(GEPRHS);
922 
923  // If we looked through an addrspacecast between different sized address
924  // spaces, the LHS and RHS pointers are different sized
925  // integers. Truncate to the smaller one.
926  Type *LHSIndexTy = LOffset->getType();
927  Type *RHSIndexTy = ROffset->getType();
928  if (LHSIndexTy != RHSIndexTy) {
929  if (LHSIndexTy->getPrimitiveSizeInBits().getFixedSize() <
930  RHSIndexTy->getPrimitiveSizeInBits().getFixedSize()) {
931  ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
932  } else
933  LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
934  }
935 
936  Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
937  LOffset, ROffset);
938  return replaceInstUsesWith(I, Cmp);
939  }
940 
941  // Otherwise, the base pointers are different and the indices are
942  // different. Try convert this to an indexed compare by looking through
943  // PHIs/casts.
944  return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
945  }
946 
947  // If one of the GEPs has all zero indices, recurse.
948  // FIXME: Handle vector of pointers.
949  if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
950  return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
952 
953  // If the other GEP has all zero indices, recurse.
954  // FIXME: Handle vector of pointers.
955  if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
956  return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
957 
958  bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
959  if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
960  GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
961  // If the GEPs only differ by one index, compare it.
962  unsigned NumDifferences = 0; // Keep track of # differences.
963  unsigned DiffOperand = 0; // The operand that differs.
964  for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
965  if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
966  Type *LHSType = GEPLHS->getOperand(i)->getType();
967  Type *RHSType = GEPRHS->getOperand(i)->getType();
968  // FIXME: Better support for vector of pointers.
969  if (LHSType->getPrimitiveSizeInBits() !=
970  RHSType->getPrimitiveSizeInBits() ||
971  (GEPLHS->getType()->isVectorTy() &&
972  (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
973  // Irreconcilable differences.
974  NumDifferences = 2;
975  break;
976  }
977 
978  if (NumDifferences++) break;
979  DiffOperand = i;
980  }
981 
982  if (NumDifferences == 0) // SAME GEP?
983  return replaceInstUsesWith(I, // No comparison is needed here.
985 
986  else if (NumDifferences == 1 && GEPsInBounds) {
987  Value *LHSV = GEPLHS->getOperand(DiffOperand);
988  Value *RHSV = GEPRHS->getOperand(DiffOperand);
989  // Make sure we do a signed comparison here.
990  return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
991  }
992  }
993 
994  // Only lower this if the icmp is the only user of the GEP or if we expect
995  // the result to fold to a constant!
996  if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
997  (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
998  // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
999  Value *L = EmitGEPOffset(GEPLHS);
1000  Value *R = EmitGEPOffset(GEPRHS);
1001  return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
1002  }
1003  }
1004 
1005  // Try convert this to an indexed compare by looking through PHIs/casts as a
1006  // last resort.
1007  return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
1008 }
1009 
1011  const AllocaInst *Alloca) {
1012  assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
1013 
1014  // It would be tempting to fold away comparisons between allocas and any
1015  // pointer not based on that alloca (e.g. an argument). However, even
1016  // though such pointers cannot alias, they can still compare equal.
1017  //
1018  // But LLVM doesn't specify where allocas get their memory, so if the alloca
1019  // doesn't escape we can argue that it's impossible to guess its value, and we
1020  // can therefore act as if any such guesses are wrong.
1021  //
1022  // The code below checks that the alloca doesn't escape, and that it's only
1023  // used in a comparison once (the current instruction). The
1024  // single-comparison-use condition ensures that we're trivially folding all
1025  // comparisons against the alloca consistently, and avoids the risk of
1026  // erroneously folding a comparison of the pointer with itself.
1027 
1028  unsigned MaxIter = 32; // Break cycles and bound to constant-time.
1029 
1031  for (const Use &U : Alloca->uses()) {
1032  if (Worklist.size() >= MaxIter)
1033  return nullptr;
1034  Worklist.push_back(&U);
1035  }
1036 
1037  unsigned NumCmps = 0;
1038  while (!Worklist.empty()) {
1039  assert(Worklist.size() <= MaxIter);
1040  const Use *U = Worklist.pop_back_val();
1041  const Value *V = U->getUser();
1042  --MaxIter;
1043 
1044  if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
1045  isa<SelectInst>(V)) {
1046  // Track the uses.
1047  } else if (isa<LoadInst>(V)) {
1048  // Loading from the pointer doesn't escape it.
1049  continue;
1050  } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
1051  // Storing *to* the pointer is fine, but storing the pointer escapes it.
1052  if (SI->getValueOperand() == U->get())
1053  return nullptr;
1054  continue;
1055  } else if (isa<ICmpInst>(V)) {
1056  if (NumCmps++)
1057  return nullptr; // Found more than one cmp.
1058  continue;
1059  } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
1060  switch (Intrin->getIntrinsicID()) {
1061  // These intrinsics don't escape or compare the pointer. Memset is safe
1062  // because we don't allow ptrtoint. Memcpy and memmove are safe because
1063  // we don't allow stores, so src cannot point to V.
1064  case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
1065  case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
1066  continue;
1067  default:
1068  return nullptr;
1069  }
1070  } else {
1071  return nullptr;
1072  }
1073  for (const Use &U : V->uses()) {
1074  if (Worklist.size() >= MaxIter)
1075  return nullptr;
1076  Worklist.push_back(&U);
1077  }
1078  }
1079 
1080  auto *Res = ConstantInt::get(ICI.getType(),
1082  return replaceInstUsesWith(ICI, Res);
1083 }
1084 
1085 /// Fold "icmp pred (X+C), X".
1087  ICmpInst::Predicate Pred) {
1088  // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
1089  // so the values can never be equal. Similarly for all other "or equals"
1090  // operators.
1091  assert(!!C && "C should not be zero!");
1092 
1093  // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
1094  // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
1095  // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
1096  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1097  Constant *R = ConstantInt::get(X->getType(),
1098  APInt::getMaxValue(C.getBitWidth()) - C);
1099  return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
1100  }
1101 
1102  // (X+1) >u X --> X <u (0-1) --> X != 255
1103  // (X+2) >u X --> X <u (0-2) --> X <u 254
1104  // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
1105  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
1106  return new ICmpInst(ICmpInst::ICMP_ULT, X,
1107  ConstantInt::get(X->getType(), -C));
1108 
1109  APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1110 
1111  // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1112  // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1113  // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1114  // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1115  // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1116  // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1117  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1118  return new ICmpInst(ICmpInst::ICMP_SGT, X,
1119  ConstantInt::get(X->getType(), SMax - C));
1120 
1121  // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1122  // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1123  // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1124  // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1125  // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1126  // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1127 
1128  assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1129  return new ICmpInst(ICmpInst::ICMP_SLT, X,
1130  ConstantInt::get(X->getType(), SMax - (C - 1)));
1131 }
1132 
1133 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1134 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
1135 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
1137  const APInt &AP1,
1138  const APInt &AP2) {
1139  assert(I.isEquality() && "Cannot fold icmp gt/lt");
1140 
1141  auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1142  if (I.getPredicate() == I.ICMP_NE)
1143  Pred = CmpInst::getInversePredicate(Pred);
1144  return new ICmpInst(Pred, LHS, RHS);
1145  };
1146 
1147  // Don't bother doing any work for cases which InstSimplify handles.
1148  if (AP2.isZero())
1149  return nullptr;
1150 
1151  bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1152  if (IsAShr) {
1153  if (AP2.isAllOnes())
1154  return nullptr;
1155  if (AP2.isNegative() != AP1.isNegative())
1156  return nullptr;
1157  if (AP2.sgt(AP1))
1158  return nullptr;
1159  }
1160 
1161  if (!AP1)
1162  // 'A' must be large enough to shift out the highest set bit.
1163  return getICmp(I.ICMP_UGT, A,
1164  ConstantInt::get(A->getType(), AP2.logBase2()));
1165 
1166  if (AP1 == AP2)
1167  return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1168 
1169  int Shift;
1170  if (IsAShr && AP1.isNegative())
1171  Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1172  else
1173  Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1174 
1175  if (Shift > 0) {
1176  if (IsAShr && AP1 == AP2.ashr(Shift)) {
1177  // There are multiple solutions if we are comparing against -1 and the LHS
1178  // of the ashr is not a power of two.
1179  if (AP1.isAllOnes() && !AP2.isPowerOf2())
1180  return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1181  return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1182  } else if (AP1 == AP2.lshr(Shift)) {
1183  return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1184  }
1185  }
1186 
1187  // Shifting const2 will never be equal to const1.
1188  // FIXME: This should always be handled by InstSimplify?
1189  auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1190  return replaceInstUsesWith(I, TorF);
1191 }
1192 
1193 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1194 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1196  const APInt &AP1,
1197  const APInt &AP2) {
1198  assert(I.isEquality() && "Cannot fold icmp gt/lt");
1199 
1200  auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1201  if (I.getPredicate() == I.ICMP_NE)
1202  Pred = CmpInst::getInversePredicate(Pred);
1203  return new ICmpInst(Pred, LHS, RHS);
1204  };
1205 
1206  // Don't bother doing any work for cases which InstSimplify handles.
1207  if (AP2.isZero())
1208  return nullptr;
1209 
1210  unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1211 
1212  if (!AP1 && AP2TrailingZeros != 0)
1213  return getICmp(
1214  I.ICMP_UGE, A,
1215  ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1216 
1217  if (AP1 == AP2)
1218  return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1219 
1220  // Get the distance between the lowest bits that are set.
1221  int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1222 
1223  if (Shift > 0 && AP2.shl(Shift) == AP1)
1224  return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1225 
1226  // Shifting const2 will never be equal to const1.
1227  // FIXME: This should always be handled by InstSimplify?
1228  auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1229  return replaceInstUsesWith(I, TorF);
1230 }
1231 
1232 /// The caller has matched a pattern of the form:
1233 /// I = icmp ugt (add (add A, B), CI2), CI1
1234 /// If this is of the form:
1235 /// sum = a + b
1236 /// if (sum+128 >u 255)
1237 /// Then replace it with llvm.sadd.with.overflow.i8.
1238 ///
1240  ConstantInt *CI2, ConstantInt *CI1,
1241  InstCombinerImpl &IC) {
1242  // The transformation we're trying to do here is to transform this into an
1243  // llvm.sadd.with.overflow. To do this, we have to replace the original add
1244  // with a narrower add, and discard the add-with-constant that is part of the
1245  // range check (if we can't eliminate it, this isn't profitable).
1246 
1247  // In order to eliminate the add-with-constant, the compare can be its only
1248  // use.
1249  Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1250  if (!AddWithCst->hasOneUse())
1251  return nullptr;
1252 
1253  // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1254  if (!CI2->getValue().isPowerOf2())
1255  return nullptr;
1256  unsigned NewWidth = CI2->getValue().countTrailingZeros();
1257  if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1258  return nullptr;
1259 
1260  // The width of the new add formed is 1 more than the bias.
1261  ++NewWidth;
1262 
1263  // Check to see that CI1 is an all-ones value with NewWidth bits.
1264  if (CI1->getBitWidth() == NewWidth ||
1265  CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1266  return nullptr;
1267 
1268  // This is only really a signed overflow check if the inputs have been
1269  // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1270  // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1271  if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1272  IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1273  return nullptr;
1274 
1275  // In order to replace the original add with a narrower
1276  // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1277  // and truncates that discard the high bits of the add. Verify that this is
1278  // the case.
1279  Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1280  for (User *U : OrigAdd->users()) {
1281  if (U == AddWithCst)
1282  continue;
1283 
1284  // Only accept truncates for now. We would really like a nice recursive
1285  // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1286  // chain to see which bits of a value are actually demanded. If the
1287  // original add had another add which was then immediately truncated, we
1288  // could still do the transformation.
1289  TruncInst *TI = dyn_cast<TruncInst>(U);
1290  if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1291  return nullptr;
1292  }
1293 
1294  // If the pattern matches, truncate the inputs to the narrower type and
1295  // use the sadd_with_overflow intrinsic to efficiently compute both the
1296  // result and the overflow bit.
1297  Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1299  I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1300 
1302 
1303  // Put the new code above the original add, in case there are any uses of the
1304  // add between the add and the compare.
1305  Builder.SetInsertPoint(OrigAdd);
1306 
1307  Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1308  Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1309  CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1310  Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1311  Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1312 
1313  // The inner add was the result of the narrow add, zero extended to the
1314  // wider type. Replace it with the result computed by the intrinsic.
1315  IC.replaceInstUsesWith(*OrigAdd, ZExt);
1316  IC.eraseInstFromFunction(*OrigAdd);
1317 
1318  // The original icmp gets replaced with the overflow value.
1319  return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1320 }
1321 
1322 /// If we have:
1323 /// icmp eq/ne (urem/srem %x, %y), 0
1324 /// iff %y is a power-of-two, we can replace this with a bit test:
1325 /// icmp eq/ne (and %x, (add %y, -1)), 0
1327  // This fold is only valid for equality predicates.
1328  if (!I.isEquality())
1329  return nullptr;
1330  ICmpInst::Predicate Pred;
1331  Value *X, *Y, *Zero;
1332  if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1333  m_CombineAnd(m_Zero(), m_Value(Zero)))))
1334  return nullptr;
1335  if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1336  return nullptr;
1337  // This may increase instruction count, we don't enforce that Y is a constant.
1338  Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1339  Value *Masked = Builder.CreateAnd(X, Mask);
1340  return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1341 }
1342 
1343 /// Fold equality-comparison between zero and any (maybe truncated) right-shift
1344 /// by one-less-than-bitwidth into a sign test on the original value.
1346  Instruction *Val;
1347  ICmpInst::Predicate Pred;
1348  if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1349  return nullptr;
1350 
1351  Value *X;
1352  Type *XTy;
1353 
1354  Constant *C;
1355  if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1356  XTy = X->getType();
1357  unsigned XBitWidth = XTy->getScalarSizeInBits();
1358  if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1359  APInt(XBitWidth, XBitWidth - 1))))
1360  return nullptr;
1361  } else if (isa<BinaryOperator>(Val) &&
1362  (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1363  cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1364  /*AnalyzeForSignBitExtraction=*/true))) {
1365  XTy = X->getType();
1366  } else
1367  return nullptr;
1368 
1369  return ICmpInst::Create(Instruction::ICmp,
1373 }
1374 
1375 // Handle icmp pred X, 0
1377  CmpInst::Predicate Pred = Cmp.getPredicate();
1378  if (!match(Cmp.getOperand(1), m_Zero()))
1379  return nullptr;
1380 
1381  // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1382  if (Pred == ICmpInst::ICMP_SGT) {
1383  Value *A, *B;
1384  if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1385  if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1386  return new ICmpInst(Pred, B, Cmp.getOperand(1));
1387  if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1388  return new ICmpInst(Pred, A, Cmp.getOperand(1));
1389  }
1390  }
1391 
1392  if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1393  return New;
1394 
1395  // Given:
1396  // icmp eq/ne (urem %x, %y), 0
1397  // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1398  // icmp eq/ne %x, 0
1399  Value *X, *Y;
1400  if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1401  ICmpInst::isEquality(Pred)) {
1402  KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1403  KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1404  if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1405  return new ICmpInst(Pred, X, Cmp.getOperand(1));
1406  }
1407 
1408  return nullptr;
1409 }
1410 
1411 /// Fold icmp Pred X, C.
1412 /// TODO: This code structure does not make sense. The saturating add fold
1413 /// should be moved to some other helper and extended as noted below (it is also
1414 /// possible that code has been made unnecessary - do we canonicalize IR to
1415 /// overflow/saturating intrinsics or not?).
1417  // Match the following pattern, which is a common idiom when writing
1418  // overflow-safe integer arithmetic functions. The source performs an addition
1419  // in wider type and explicitly checks for overflow using comparisons against
1420  // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1421  //
1422  // TODO: This could probably be generalized to handle other overflow-safe
1423  // operations if we worked out the formulas to compute the appropriate magic
1424  // constants.
1425  //
1426  // sum = a + b
1427  // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1428  CmpInst::Predicate Pred = Cmp.getPredicate();
1429  Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1430  Value *A, *B;
1431  ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1432  if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1433  match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1434  if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1435  return Res;
1436 
1437  // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1438  Constant *C = dyn_cast<Constant>(Op1);
1439  if (!C)
1440  return nullptr;
1441 
1442  if (auto *Phi = dyn_cast<PHINode>(Op0))
1443  if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1444  Type *Ty = Cmp.getType();
1445  Builder.SetInsertPoint(Phi);
1446  PHINode *NewPhi =
1447  Builder.CreatePHI(Ty, Phi->getNumOperands());
1448  for (BasicBlock *Predecessor : predecessors(Phi->getParent())) {
1449  auto *Input =
1450  cast<Constant>(Phi->getIncomingValueForBlock(Predecessor));
1451  auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C);
1452  NewPhi->addIncoming(BoolInput, Predecessor);
1453  }
1454  NewPhi->takeName(&Cmp);
1455  return replaceInstUsesWith(Cmp, NewPhi);
1456  }
1457 
1458  return nullptr;
1459 }
1460 
1461 /// Canonicalize icmp instructions based on dominating conditions.
1463  // This is a cheap/incomplete check for dominance - just match a single
1464  // predecessor with a conditional branch.
1465  BasicBlock *CmpBB = Cmp.getParent();
1466  BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1467  if (!DomBB)
1468  return nullptr;
1469 
1470  Value *DomCond;
1471  BasicBlock *TrueBB, *FalseBB;
1472  if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1473  return nullptr;
1474 
1475  assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1476  "Predecessor block does not point to successor?");
1477 
1478  // The branch should get simplified. Don't bother simplifying this condition.
1479  if (TrueBB == FalseBB)
1480  return nullptr;
1481 
1482  // Try to simplify this compare to T/F based on the dominating condition.
1483  Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1484  if (Imp)
1485  return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1486 
1487  CmpInst::Predicate Pred = Cmp.getPredicate();
1488  Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1489  ICmpInst::Predicate DomPred;
1490  const APInt *C, *DomC;
1491  if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1492  match(Y, m_APInt(C))) {
1493  // We have 2 compares of a variable with constants. Calculate the constant
1494  // ranges of those compares to see if we can transform the 2nd compare:
1495  // DomBB:
1496  // DomCond = icmp DomPred X, DomC
1497  // br DomCond, CmpBB, FalseBB
1498  // CmpBB:
1499  // Cmp = icmp Pred X, C
1501  ConstantRange DominatingCR =
1502  (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1504  CmpInst::getInversePredicate(DomPred), *DomC);
1505  ConstantRange Intersection = DominatingCR.intersectWith(CR);
1506  ConstantRange Difference = DominatingCR.difference(CR);
1507  if (Intersection.isEmptySet())
1508  return replaceInstUsesWith(Cmp, Builder.getFalse());
1509  if (Difference.isEmptySet())
1510  return replaceInstUsesWith(Cmp, Builder.getTrue());
1511 
1512  // Canonicalizing a sign bit comparison that gets used in a branch,
1513  // pessimizes codegen by generating branch on zero instruction instead
1514  // of a test and branch. So we avoid canonicalizing in such situations
1515  // because test and branch instruction has better branch displacement
1516  // than compare and branch instruction.
1517  bool UnusedBit;
1518  bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1519  if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1520  return nullptr;
1521 
1522  // Avoid an infinite loop with min/max canonicalization.
1523  // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1524  if (Cmp.hasOneUse() &&
1525  match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1526  return nullptr;
1527 
1528  if (const APInt *EqC = Intersection.getSingleElement())
1529  return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1530  if (const APInt *NeC = Difference.getSingleElement())
1531  return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1532  }
1533 
1534  return nullptr;
1535 }
1536 
1537 /// Fold icmp (trunc X), C.
1539  TruncInst *Trunc,
1540  const APInt &C) {
1541  ICmpInst::Predicate Pred = Cmp.getPredicate();
1542  Value *X = Trunc->getOperand(0);
1543  if (C.isOne() && C.getBitWidth() > 1) {
1544  // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1545  Value *V = nullptr;
1546  if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1547  return new ICmpInst(ICmpInst::ICMP_SLT, V,
1548  ConstantInt::get(V->getType(), 1));
1549  }
1550 
1551  Type *SrcTy = X->getType();
1552  unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1553  SrcBits = SrcTy->getScalarSizeInBits();
1554 
1555  // TODO: Handle any shifted constant by subtracting trailing zeros.
1556  // TODO: Handle non-equality predicates.
1557  Value *Y;
1558  if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1559  // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1560  // (trunc (1 << Y) to iN) != 0 --> Y u< N
1561  if (C.isZero()) {
1562  auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1563  return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1564  }
1565  // (trunc (1 << Y) to iN) == 2**C --> Y == C
1566  // (trunc (1 << Y) to iN) != 2**C --> Y != C
1567  if (C.isPowerOf2())
1568  return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1569  }
1570 
1571  if (Cmp.isEquality() && Trunc->hasOneUse()) {
1572  // Canonicalize to a mask and wider compare if the wide type is suitable:
1573  // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1574  if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1575  Constant *Mask =
1576  ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1577  Value *And = Builder.CreateAnd(X, Mask);
1578  Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1579  return new ICmpInst(Pred, And, WideC);
1580  }
1581 
1582  // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1583  // of the high bits truncated out of x are known.
1584  KnownBits Known = computeKnownBits(X, 0, &Cmp);
1585 
1586  // If all the high bits are known, we can do this xform.
1587  if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1588  // Pull in the high bits from known-ones set.
1589  APInt NewRHS = C.zext(SrcBits);
1590  NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1591  return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1592  }
1593  }
1594 
1595  // Look through truncated right-shift of the sign-bit for a sign-bit check:
1596  // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1597  // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1598  Value *ShOp;
1599  const APInt *ShAmtC;
1600  bool TrueIfSigned;
1601  if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1602  match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1603  DstBits == SrcBits - ShAmtC->getZExtValue()) {
1604  return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1606  : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1608  }
1609 
1610  return nullptr;
1611 }
1612 
1613 /// Fold icmp (xor X, Y), C.
1615  BinaryOperator *Xor,
1616  const APInt &C) {
1617  if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1618  return I;
1619 
1620  Value *X = Xor->getOperand(0);
1621  Value *Y = Xor->getOperand(1);
1622  const APInt *XorC;
1623  if (!match(Y, m_APInt(XorC)))
1624  return nullptr;
1625 
1626  // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1627  // fold the xor.
1628  ICmpInst::Predicate Pred = Cmp.getPredicate();
1629  bool TrueIfSigned = false;
1630  if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1631 
1632  // If the sign bit of the XorCst is not set, there is no change to
1633  // the operation, just stop using the Xor.
1634  if (!XorC->isNegative())
1635  return replaceOperand(Cmp, 0, X);
1636 
1637  // Emit the opposite comparison.
1638  if (TrueIfSigned)
1639  return new ICmpInst(ICmpInst::ICMP_SGT, X,
1640  ConstantInt::getAllOnesValue(X->getType()));
1641  else
1642  return new ICmpInst(ICmpInst::ICMP_SLT, X,
1643  ConstantInt::getNullValue(X->getType()));
1644  }
1645 
1646  if (Xor->hasOneUse()) {
1647  // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1648  if (!Cmp.isEquality() && XorC->isSignMask()) {
1649  Pred = Cmp.getFlippedSignednessPredicate();
1650  return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1651  }
1652 
1653  // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1654  if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1655  Pred = Cmp.getFlippedSignednessPredicate();
1656  Pred = Cmp.getSwappedPredicate(Pred);
1657  return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1658  }
1659  }
1660 
1661  // Mask constant magic can eliminate an 'xor' with unsigned compares.
1662  if (Pred == ICmpInst::ICMP_UGT) {
1663  // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1664  if (*XorC == ~C && (C + 1).isPowerOf2())
1665  return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1666  // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1667  if (*XorC == C && (C + 1).isPowerOf2())
1668  return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1669  }
1670  if (Pred == ICmpInst::ICMP_ULT) {
1671  // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1672  if (*XorC == -C && C.isPowerOf2())
1673  return new ICmpInst(ICmpInst::ICMP_UGT, X,
1674  ConstantInt::get(X->getType(), ~C));
1675  // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1676  if (*XorC == C && (-C).isPowerOf2())
1677  return new ICmpInst(ICmpInst::ICMP_UGT, X,
1678  ConstantInt::get(X->getType(), ~C));
1679  }
1680  return nullptr;
1681 }
1682 
1683 /// For power-of-2 C:
1684 /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1685 /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1687  BinaryOperator *Xor,
1688  const APInt &C) {
1689  CmpInst::Predicate Pred = Cmp.getPredicate();
1690  APInt PowerOf2;
1691  if (Pred == ICmpInst::ICMP_ULT)
1692  PowerOf2 = C;
1693  else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1694  PowerOf2 = C + 1;
1695  else
1696  return nullptr;
1697  if (!PowerOf2.isPowerOf2())
1698  return nullptr;
1699  Value *X;
1700  const APInt *ShiftC;
1701  if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
1702  m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1703  return nullptr;
1704  uint64_t Shift = ShiftC->getLimitedValue();
1705  Type *XType = X->getType();
1706  if (Shift == 0 || PowerOf2.isMinSignedValue())
1707  return nullptr;
1708  Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1709  APInt Bound =
1710  Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1711  return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1712 }
1713 
1714 /// Fold icmp (and (sh X, Y), C2), C1.
1716  BinaryOperator *And,
1717  const APInt &C1,
1718  const APInt &C2) {
1719  BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1720  if (!Shift || !Shift->isShift())
1721  return nullptr;
1722 
1723  // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1724  // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1725  // code produced by the clang front-end, for bitfield access.
1726  // This seemingly simple opportunity to fold away a shift turns out to be
1727  // rather complicated. See PR17827 for details.
1728  unsigned ShiftOpcode = Shift->getOpcode();
1729  bool IsShl = ShiftOpcode == Instruction::Shl;
1730  const APInt *C3;
1731  if (match(Shift->getOperand(1), m_APInt(C3))) {
1732  APInt NewAndCst, NewCmpCst;
1733  bool AnyCmpCstBitsShiftedOut;
1734  if (ShiftOpcode == Instruction::Shl) {
1735  // For a left shift, we can fold if the comparison is not signed. We can
1736  // also fold a signed comparison if the mask value and comparison value
1737  // are not negative. These constraints may not be obvious, but we can
1738  // prove that they are correct using an SMT solver.
1739  if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1740  return nullptr;
1741 
1742  NewCmpCst = C1.lshr(*C3);
1743  NewAndCst = C2.lshr(*C3);
1744  AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1745  } else if (ShiftOpcode == Instruction::LShr) {
1746  // For a logical right shift, we can fold if the comparison is not signed.
1747  // We can also fold a signed comparison if the shifted mask value and the
1748  // shifted comparison value are not negative. These constraints may not be
1749  // obvious, but we can prove that they are correct using an SMT solver.
1750  NewCmpCst = C1.shl(*C3);
1751  NewAndCst = C2.shl(*C3);
1752  AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1753  if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1754  return nullptr;
1755  } else {
1756  // For an arithmetic shift, check that both constants don't use (in a
1757  // signed sense) the top bits being shifted out.
1758  assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1759  NewCmpCst = C1.shl(*C3);
1760  NewAndCst = C2.shl(*C3);
1761  AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1762  if (NewAndCst.ashr(*C3) != C2)
1763  return nullptr;
1764  }
1765 
1766  if (AnyCmpCstBitsShiftedOut) {
1767  // If we shifted bits out, the fold is not going to work out. As a
1768  // special case, check to see if this means that the result is always
1769  // true or false now.
1770  if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1771  return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1772  if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1773  return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1774  } else {
1775  Value *NewAnd = Builder.CreateAnd(
1776  Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1777  return new ICmpInst(Cmp.getPredicate(),
1778  NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1779  }
1780  }
1781 
1782  // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1783  // preferable because it allows the C2 << Y expression to be hoisted out of a
1784  // loop if Y is invariant and X is not.
1785  if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1786  !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1787  // Compute C2 << Y.
1788  Value *NewShift =
1789  IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1790  : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1791 
1792  // Compute X & (C2 << Y).
1793  Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1794  return replaceOperand(Cmp, 0, NewAnd);
1795  }
1796 
1797  return nullptr;
1798 }
1799 
1800 /// Fold icmp (and X, C2), C1.
1802  BinaryOperator *And,
1803  const APInt &C1) {
1804  bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1805 
1806  // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1807  // TODO: We canonicalize to the longer form for scalars because we have
1808  // better analysis/folds for icmp, and codegen may be better with icmp.
1809  if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1810  match(And->getOperand(1), m_One()))
1811  return new TruncInst(And->getOperand(0), Cmp.getType());
1812 
1813  const APInt *C2;
1814  Value *X;
1815  if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1816  return nullptr;
1817 
1818  // Don't perform the following transforms if the AND has multiple uses
1819  if (!And->hasOneUse())
1820  return nullptr;
1821 
1822  if (Cmp.isEquality() && C1.isZero()) {
1823  // Restrict this fold to single-use 'and' (PR10267).
1824  // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1825  if (C2->isSignMask()) {
1826  Constant *Zero = Constant::getNullValue(X->getType());
1827  auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1828  return new ICmpInst(NewPred, X, Zero);
1829  }
1830 
1831  APInt NewC2 = *C2;
1832  KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1833  // Set high zeros of C2 to allow matching negated power-of-2.
1834  NewC2 = *C2 + APInt::getHighBitsSet(C2->getBitWidth(),
1835  Know.countMinLeadingZeros());
1836 
1837  // Restrict this fold only for single-use 'and' (PR10267).
1838  // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1839  if (NewC2.isNegatedPowerOf2()) {
1840  Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1841  auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1842  return new ICmpInst(NewPred, X, NegBOC);
1843  }
1844  }
1845 
1846  // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1847  // the input width without changing the value produced, eliminate the cast:
1848  //
1849  // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1850  //
1851  // We can do this transformation if the constants do not have their sign bits
1852  // set or if it is an equality comparison. Extending a relational comparison
1853  // when we're checking the sign bit would not work.
1854  Value *W;
1855  if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1856  (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1857  // TODO: Is this a good transform for vectors? Wider types may reduce
1858  // throughput. Should this transform be limited (even for scalars) by using
1859  // shouldChangeType()?
1860  if (!Cmp.getType()->isVectorTy()) {
1861  Type *WideType = W->getType();
1862  unsigned WideScalarBits = WideType->getScalarSizeInBits();
1863  Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1864  Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1865  Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1866  return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1867  }
1868  }
1869 
1870  if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1871  return I;
1872 
1873  // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1874  // (icmp pred (and A, (or (shl 1, B), 1), 0))
1875  //
1876  // iff pred isn't signed
1877  if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1878  match(And->getOperand(1), m_One())) {
1879  Constant *One = cast<Constant>(And->getOperand(1));
1880  Value *Or = And->getOperand(0);
1881  Value *A, *B, *LShr;
1882  if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1883  match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1884  unsigned UsesRemoved = 0;
1885  if (And->hasOneUse())
1886  ++UsesRemoved;
1887  if (Or->hasOneUse())
1888  ++UsesRemoved;
1889  if (LShr->hasOneUse())
1890  ++UsesRemoved;
1891 
1892  // Compute A & ((1 << B) | 1)
1893  Value *NewOr = nullptr;
1894  if (auto *C = dyn_cast<Constant>(B)) {
1895  if (UsesRemoved >= 1)
1896  NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1897  } else {
1898  if (UsesRemoved >= 3)
1899  NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1900  /*HasNUW=*/true),
1901  One, Or->getName());
1902  }
1903  if (NewOr) {
1904  Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1905  return replaceOperand(Cmp, 0, NewAnd);
1906  }
1907  }
1908  }
1909 
1910  return nullptr;
1911 }
1912 
1913 /// Fold icmp (and X, Y), C.
1915  BinaryOperator *And,
1916  const APInt &C) {
1917  if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1918  return I;
1919 
1920  const ICmpInst::Predicate Pred = Cmp.getPredicate();
1921  bool TrueIfNeg;
1922  if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1923  // ((X - 1) & ~X) < 0 --> X == 0
1924  // ((X - 1) & ~X) >= 0 --> X != 0
1925  Value *X;
1926  if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1927  match(And->getOperand(1), m_Not(m_Specific(X)))) {
1928  auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1929  return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1930  }
1931  }
1932 
1933  // TODO: These all require that Y is constant too, so refactor with the above.
1934 
1935  // Try to optimize things like "A[i] & 42 == 0" to index computations.
1936  Value *X = And->getOperand(0);
1937  Value *Y = And->getOperand(1);
1938  if (auto *C2 = dyn_cast<ConstantInt>(Y))
1939  if (auto *LI = dyn_cast<LoadInst>(X))
1940  if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1941  if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1942  if (Instruction *Res =
1943  foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1944  return Res;
1945 
1946  if (!Cmp.isEquality())
1947  return nullptr;
1948 
1949  // X & -C == -C -> X > u ~C
1950  // X & -C != -C -> X <= u ~C
1951  // iff C is a power of 2
1952  if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1953  auto NewPred =
1955  return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1956  }
1957 
1958  // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1959  // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1960  // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1961  // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1963  X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1964  Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1965  if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1966  Value *And = Builder.CreateAnd(TruncY, X);
1968  }
1969  return BinaryOperator::CreateAnd(TruncY, X);
1970  }
1971 
1972  return nullptr;
1973 }
1974 
1975 /// Fold icmp (or X, Y), C.
1977  BinaryOperator *Or,
1978  const APInt &C) {
1979  ICmpInst::Predicate Pred = Cmp.getPredicate();
1980  if (C.isOne()) {
1981  // icmp slt signum(V) 1 --> icmp slt V, 1
1982  Value *V = nullptr;
1983  if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1984  return new ICmpInst(ICmpInst::ICMP_SLT, V,
1985  ConstantInt::get(V->getType(), 1));
1986  }
1987 
1988  Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1989  const APInt *MaskC;
1990  if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
1991  if (*MaskC == C && (C + 1).isPowerOf2()) {
1992  // X | C == C --> X <=u C
1993  // X | C != C --> X >u C
1994  // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1996  return new ICmpInst(Pred, OrOp0, OrOp1);
1997  }
1998 
1999  // More general: canonicalize 'equality with set bits mask' to
2000  // 'equality with clear bits mask'.
2001  // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2002  // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2003  if (Or->hasOneUse()) {
2004  Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2005  Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2006  return new ICmpInst(Pred, And, NewC);
2007  }
2008  }
2009 
2010  // (X | (X-1)) s< 0 --> X s< 1
2011  // (X | (X-1)) s> -1 --> X s> 0
2012  Value *X;
2013  bool TrueIfSigned;
2014  if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2016  auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2017  Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2018  return new ICmpInst(NewPred, X, NewC);
2019  }
2020 
2021  if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2022  return nullptr;
2023 
2024  Value *P, *Q;
2025  if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
2026  // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2027  // -> and (icmp eq P, null), (icmp eq Q, null).
2028  Value *CmpP =
2029  Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2030  Value *CmpQ =
2031  Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2032  auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2033  return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2034  }
2035 
2036  // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
2037  // a shorter form that has more potential to be folded even further.
2038  Value *X1, *X2, *X3, *X4;
2039  if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
2040  match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
2041  // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
2042  // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
2043  Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
2044  Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
2045  auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2046  return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
2047  }
2048 
2049  return nullptr;
2050 }
2051 
2052 /// Fold icmp (mul X, Y), C.
2054  BinaryOperator *Mul,
2055  const APInt &C) {
2056  ICmpInst::Predicate Pred = Cmp.getPredicate();
2057  Type *MulTy = Mul->getType();
2058  Value *X = Mul->getOperand(0);
2059 
2060  // If there's no overflow:
2061  // X * X == 0 --> X == 0
2062  // X * X != 0 --> X != 0
2063  if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
2065  return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2066 
2067  const APInt *MulC;
2068  if (!match(Mul->getOperand(1), m_APInt(MulC)))
2069  return nullptr;
2070 
2071  // If this is a test of the sign bit and the multiply is sign-preserving with
2072  // a constant operand, use the multiply LHS operand instead:
2073  // (X * +MulC) < 0 --> X < 0
2074  // (X * -MulC) < 0 --> X > 0
2075  if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2076  if (MulC->isNegative())
2077  Pred = ICmpInst::getSwappedPredicate(Pred);
2078  return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2079  }
2080 
2081  if (MulC->isZero() || (!Mul->hasNoSignedWrap() && !Mul->hasNoUnsignedWrap()))
2082  return nullptr;
2083 
2084  // If the multiply does not wrap, try to divide the compare constant by the
2085  // multiplication factor.
2086  if (Cmp.isEquality()) {
2087  // (mul nsw X, MulC) == C --> X == C /s MulC
2088  if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2089  Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2090  return new ICmpInst(Pred, X, NewC);
2091  }
2092  // (mul nuw X, MulC) == C --> X == C /u MulC
2093  if (Mul->hasNoUnsignedWrap() && C.urem(*MulC).isZero()) {
2094  Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2095  return new ICmpInst(Pred, X, NewC);
2096  }
2097  }
2098 
2099  // With a matching no-overflow guarantee, fold the constants:
2100  // (X * MulC) < C --> X < (C / MulC)
2101  // (X * MulC) > C --> X > (C / MulC)
2102  // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2103  Constant *NewC = nullptr;
2104  if (Mul->hasNoSignedWrap()) {
2105  // MININT / -1 --> overflow.
2106  if (C.isMinSignedValue() && MulC->isAllOnes())
2107  return nullptr;
2108  if (MulC->isNegative())
2109  Pred = ICmpInst::getSwappedPredicate(Pred);
2110 
2111  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE)
2112  NewC = ConstantInt::get(
2113  MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
2114  if (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT)
2115  NewC = ConstantInt::get(
2117  } else {
2118  assert(Mul->hasNoUnsignedWrap() && "Expected mul nuw");
2119  if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)
2120  NewC = ConstantInt::get(
2121  MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
2122  if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)
2123  NewC = ConstantInt::get(
2125  }
2126 
2127  return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2128 }
2129 
2130 /// Fold icmp (shl 1, Y), C.
2132  const APInt &C) {
2133  Value *Y;
2134  if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2135  return nullptr;
2136 
2137  Type *ShiftType = Shl->getType();
2138  unsigned TypeBits = C.getBitWidth();
2139  bool CIsPowerOf2 = C.isPowerOf2();
2140  ICmpInst::Predicate Pred = Cmp.getPredicate();
2141  if (Cmp.isUnsigned()) {
2142  // (1 << Y) pred C -> Y pred Log2(C)
2143  if (!CIsPowerOf2) {
2144  // (1 << Y) < 30 -> Y <= 4
2145  // (1 << Y) <= 30 -> Y <= 4
2146  // (1 << Y) >= 30 -> Y > 4
2147  // (1 << Y) > 30 -> Y > 4
2148  if (Pred == ICmpInst::ICMP_ULT)
2149  Pred = ICmpInst::ICMP_ULE;
2150  else if (Pred == ICmpInst::ICMP_UGE)
2151  Pred = ICmpInst::ICMP_UGT;
2152  }
2153 
2154  // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31
2155  // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31
2156  unsigned CLog2 = C.logBase2();
2157  if (CLog2 == TypeBits - 1) {
2158  if (Pred == ICmpInst::ICMP_UGE)
2159  Pred = ICmpInst::ICMP_EQ;
2160  else if (Pred == ICmpInst::ICMP_ULT)
2161  Pred = ICmpInst::ICMP_NE;
2162  }
2163  return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2164  } else if (Cmp.isSigned()) {
2165  Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2166  if (C.isAllOnes()) {
2167  // (1 << Y) <= -1 -> Y == 31
2168  if (Pred == ICmpInst::ICMP_SLE)
2169  return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2170 
2171  // (1 << Y) > -1 -> Y != 31
2172  if (Pred == ICmpInst::ICMP_SGT)
2173  return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2174  } else if (!C) {
2175  // (1 << Y) < 0 -> Y == 31
2176  // (1 << Y) <= 0 -> Y == 31
2177  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
2178  return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2179 
2180  // (1 << Y) >= 0 -> Y != 31
2181  // (1 << Y) > 0 -> Y != 31
2182  if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
2183  return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2184  }
2185  } else if (Cmp.isEquality() && CIsPowerOf2) {
2186  return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2()));
2187  }
2188 
2189  return nullptr;
2190 }
2191 
2192 /// Fold icmp (shl X, Y), C.
2194  BinaryOperator *Shl,
2195  const APInt &C) {
2196  const APInt *ShiftVal;
2197  if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2198  return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2199 
2200  const APInt *ShiftAmt;
2201  if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2202  return foldICmpShlOne(Cmp, Shl, C);
2203 
2204  // Check that the shift amount is in range. If not, don't perform undefined
2205  // shifts. When the shift is visited, it will be simplified.
2206  unsigned TypeBits = C.getBitWidth();
2207  if (ShiftAmt->uge(TypeBits))
2208  return nullptr;
2209 
2210  ICmpInst::Predicate Pred = Cmp.getPredicate();
2211  Value *X = Shl->getOperand(0);
2212  Type *ShType = Shl->getType();
2213 
2214  // NSW guarantees that we are only shifting out sign bits from the high bits,
2215  // so we can ASHR the compare constant without needing a mask and eliminate
2216  // the shift.
2217  if (Shl->hasNoSignedWrap()) {
2218  if (Pred == ICmpInst::ICMP_SGT) {
2219  // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2220  APInt ShiftedC = C.ashr(*ShiftAmt);
2221  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2222  }
2223  if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2224  C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2225  APInt ShiftedC = C.ashr(*ShiftAmt);
2226  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2227  }
2228  if (Pred == ICmpInst::ICMP_SLT) {
2229  // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2230  // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2231  // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2232  // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2233  assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2234  APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2235  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2236  }
2237  // If this is a signed comparison to 0 and the shift is sign preserving,
2238  // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2239  // do that if we're sure to not continue on in this function.
2240  if (isSignTest(Pred, C))
2241  return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2242  }
2243 
2244  // NUW guarantees that we are only shifting out zero bits from the high bits,
2245  // so we can LSHR the compare constant without needing a mask and eliminate
2246  // the shift.
2247  if (Shl->hasNoUnsignedWrap()) {
2248  if (Pred == ICmpInst::ICMP_UGT) {
2249  // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2250  APInt ShiftedC = C.lshr(*ShiftAmt);
2251  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2252  }
2253  if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2254  C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2255  APInt ShiftedC = C.lshr(*ShiftAmt);
2256  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2257  }
2258  if (Pred == ICmpInst::ICMP_ULT) {
2259  // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2260  // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2261  // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2262  // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2263  assert(C.ugt(0) && "ult 0 should have been eliminated");
2264  APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2265  return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2266  }
2267  }
2268 
2269  if (Cmp.isEquality() && Shl->hasOneUse()) {
2270  // Strength-reduce the shift into an 'and'.
2272  ShType,
2273  APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2274  Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2275  Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2276  return new ICmpInst(Pred, And, LShrC);
2277  }
2278 
2279  // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2280  bool TrueIfSigned = false;
2281  if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2282  // (X << 31) <s 0 --> (X & 1) != 0
2284  ShType,
2285  APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2286  Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2287  return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2288  And, Constant::getNullValue(ShType));
2289  }
2290 
2291  // Simplify 'shl' inequality test into 'and' equality test.
2292  if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2293  // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2294  if ((C + 1).isPowerOf2() &&
2295  (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2296  Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2297  return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2299  And, Constant::getNullValue(ShType));
2300  }
2301  // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2302  if (C.isPowerOf2() &&
2303  (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2304  Value *And =
2305  Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2306  return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2308  And, Constant::getNullValue(ShType));
2309  }
2310  }
2311 
2312  // Transform (icmp pred iM (shl iM %v, N), C)
2313  // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2314  // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2315  // This enables us to get rid of the shift in favor of a trunc that may be
2316  // free on the target. It has the additional benefit of comparing to a
2317  // smaller constant that may be more target-friendly.
2318  unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2319  if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2320  DL.isLegalInteger(TypeBits - Amt)) {
2321  Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2322  if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2323  TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2324  Constant *NewC =
2325  ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2326  return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2327  }
2328 
2329  return nullptr;
2330 }
2331 
2332 /// Fold icmp ({al}shr X, Y), C.
2334  BinaryOperator *Shr,
2335  const APInt &C) {
2336  // An exact shr only shifts out zero bits, so:
2337  // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2338  Value *X = Shr->getOperand(0);
2339  CmpInst::Predicate Pred = Cmp.getPredicate();
2340  if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2341  return new ICmpInst(Pred, X, Cmp.getOperand(1));
2342 
2343  bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2344  const APInt *ShiftValC;
2345  if (match(X, m_APInt(ShiftValC))) {
2346  if (Cmp.isEquality())
2347  return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2348 
2349  // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2350  // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2351  bool TrueIfSigned;
2352  if (!IsAShr && ShiftValC->isNegative() &&
2353  isSignBitCheck(Pred, C, TrueIfSigned))
2354  return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2355  Shr->getOperand(1),
2356  ConstantInt::getNullValue(X->getType()));
2357 
2358  // If the shifted constant is a power-of-2, test the shift amount directly:
2359  // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2360  // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2361  if (!IsAShr && ShiftValC->isPowerOf2() &&
2362  (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2363  bool IsUGT = Pred == CmpInst::ICMP_UGT;
2364  assert(ShiftValC->uge(C) && "Expected simplify of compare");
2365  assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2366 
2367  unsigned CmpLZ =
2368  IsUGT ? C.countLeadingZeros() : (C - 1).countLeadingZeros();
2369  unsigned ShiftLZ = ShiftValC->countLeadingZeros();
2370  Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2371  auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2372  return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2373  }
2374  }
2375 
2376  const APInt *ShiftAmtC;
2377  if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2378  return nullptr;
2379 
2380  // Check that the shift amount is in range. If not, don't perform undefined
2381  // shifts. When the shift is visited it will be simplified.
2382  unsigned TypeBits = C.getBitWidth();
2383  unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2384  if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2385  return nullptr;
2386 
2387  bool IsExact = Shr->isExact();
2388  Type *ShrTy = Shr->getType();
2389  // TODO: If we could guarantee that InstSimplify would handle all of the
2390  // constant-value-based preconditions in the folds below, then we could assert
2391  // those conditions rather than checking them. This is difficult because of
2392  // undef/poison (PR34838).
2393  if (IsAShr) {
2394  if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2395  // When ShAmtC can be shifted losslessly:
2396  // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2397  // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2398  APInt ShiftedC = C.shl(ShAmtVal);
2399  if (ShiftedC.ashr(ShAmtVal) == C)
2400  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2401  }
2402  if (Pred == CmpInst::ICMP_SGT) {
2403  // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2404  APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2405  if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2406  (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2407  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2408  }
2409  if (Pred == CmpInst::ICMP_UGT) {
2410  // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2411  // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2412  // clause accounts for that pattern.
2413  APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2414  if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2415  (C + 1).shl(ShAmtVal).isMinSignedValue())
2416  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2417  }
2418 
2419  // If the compare constant has significant bits above the lowest sign-bit,
2420  // then convert an unsigned cmp to a test of the sign-bit:
2421  // (ashr X, ShiftC) u> C --> X s< 0
2422  // (ashr X, ShiftC) u< C --> X s> -1
2423  if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2424  if (Pred == CmpInst::ICMP_UGT) {
2425  return new ICmpInst(CmpInst::ICMP_SLT, X,
2426  ConstantInt::getNullValue(ShrTy));
2427  }
2428  if (Pred == CmpInst::ICMP_ULT) {
2429  return new ICmpInst(CmpInst::ICMP_SGT, X,
2431  }
2432  }
2433  } else {
2434  if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2435  // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2436  // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2437  APInt ShiftedC = C.shl(ShAmtVal);
2438  if (ShiftedC.lshr(ShAmtVal) == C)
2439  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2440  }
2441  if (Pred == CmpInst::ICMP_UGT) {
2442  // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2443  APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2444  if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2445  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2446  }
2447  }
2448 
2449  if (!Cmp.isEquality())
2450  return nullptr;
2451 
2452  // Handle equality comparisons of shift-by-constant.
2453 
2454  // If the comparison constant changes with the shift, the comparison cannot
2455  // succeed (bits of the comparison constant cannot match the shifted value).
2456  // This should be known by InstSimplify and already be folded to true/false.
2457  assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2458  (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2459  "Expected icmp+shr simplify did not occur.");
2460 
2461  // If the bits shifted out are known zero, compare the unshifted value:
2462  // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2463  if (Shr->isExact())
2464  return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2465 
2466  if (C.isZero()) {
2467  // == 0 is u< 1.
2468  if (Pred == CmpInst::ICMP_EQ)
2469  return new ICmpInst(CmpInst::ICMP_ULT, X,
2470  ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2471  else
2472  return new ICmpInst(CmpInst::ICMP_UGT, X,
2473  ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2474  }
2475 
2476  if (Shr->hasOneUse()) {
2477  // Canonicalize the shift into an 'and':
2478  // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2479  APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2480  Constant *Mask = ConstantInt::get(ShrTy, Val);
2481  Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2482  return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2483  }
2484 
2485  return nullptr;
2486 }
2487 
2489  BinaryOperator *SRem,
2490  const APInt &C) {
2491  // Match an 'is positive' or 'is negative' comparison of remainder by a
2492  // constant power-of-2 value:
2493  // (X % pow2C) sgt/slt 0
2494  const ICmpInst::Predicate Pred = Cmp.getPredicate();
2495  if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2496  Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2497  return nullptr;
2498 
2499  // TODO: The one-use check is standard because we do not typically want to
2500  // create longer instruction sequences, but this might be a special-case
2501  // because srem is not good for analysis or codegen.
2502  if (!SRem->hasOneUse())
2503  return nullptr;
2504 
2505  const APInt *DivisorC;
2506  if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2507  return nullptr;
2508 
2509  // For cmp_sgt/cmp_slt only zero valued C is handled.
2510  // For cmp_eq/cmp_ne only positive valued C is handled.
2511  if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2512  !C.isZero()) ||
2513  ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2514  !C.isStrictlyPositive()))
2515  return nullptr;
2516 
2517  // Mask off the sign bit and the modulo bits (low-bits).
2518  Type *Ty = SRem->getType();
2519  APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2520  Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2521  Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2522 
2523  if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2524  return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2525 
2526  // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2527  // bit is set. Example:
2528  // (i8 X % 32) s> 0 --> (X & 159) s> 0
2529  if (Pred == ICmpInst::ICMP_SGT)
2531 
2532  // For 'is negative?' check that the sign-bit is set and at least 1 masked
2533  // bit is set. Example:
2534  // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2535  return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2536 }
2537 
2538 /// Fold icmp (udiv X, Y), C.
2540  BinaryOperator *UDiv,
2541  const APInt &C) {
2542  ICmpInst::Predicate Pred = Cmp.getPredicate();
2543  Value *X = UDiv->getOperand(0);
2544  Value *Y = UDiv->getOperand(1);
2545  Type *Ty = UDiv->getType();
2546 
2547  const APInt *C2;
2548  if (!match(X, m_APInt(C2)))
2549  return nullptr;
2550 
2551  assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2552 
2553  // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2554  if (Pred == ICmpInst::ICMP_UGT) {
2555  assert(!C.isMaxValue() &&
2556  "icmp ugt X, UINT_MAX should have been simplified already.");
2557  return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2558  ConstantInt::get(Ty, C2->udiv(C + 1)));
2559  }
2560 
2561  // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2562  if (Pred == ICmpInst::ICMP_ULT) {
2563  assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2564  return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2565  ConstantInt::get(Ty, C2->udiv(C)));
2566  }
2567 
2568  return nullptr;
2569 }
2570 
2571 /// Fold icmp ({su}div X, Y), C.
2573  BinaryOperator *Div,
2574  const APInt &C) {
2575  ICmpInst::Predicate Pred = Cmp.getPredicate();
2576  Value *X = Div->getOperand(0);
2577  Value *Y = Div->getOperand(1);
2578  Type *Ty = Div->getType();
2579  bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2580 
2581  // If unsigned division and the compare constant is bigger than
2582  // UMAX/2 (negative), there's only one pair of values that satisfies an
2583  // equality check, so eliminate the division:
2584  // (X u/ Y) == C --> (X == C) && (Y == 1)
2585  // (X u/ Y) != C --> (X != C) || (Y != 1)
2586  // Similarly, if signed division and the compare constant is exactly SMIN:
2587  // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2588  // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2589  if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2590  (!DivIsSigned || C.isMinSignedValue())) {
2591  Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2592  Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2593  auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2594  return BinaryOperator::Create(Logic, XBig, YOne);
2595  }
2596 
2597  // Fold: icmp pred ([us]div X, C2), C -> range test
2598  // Fold this div into the comparison, producing a range check.
2599  // Determine, based on the divide type, what the range is being
2600  // checked. If there is an overflow on the low or high side, remember
2601  // it, otherwise compute the range [low, hi) bounding the new value.
2602  // See: InsertRangeTest above for the kinds of replacements possible.
2603  const APInt *C2;
2604  if (!match(Y, m_APInt(C2)))
2605  return nullptr;
2606 
2607  // FIXME: If the operand types don't match the type of the divide
2608  // then don't attempt this transform. The code below doesn't have the
2609  // logic to deal with a signed divide and an unsigned compare (and
2610  // vice versa). This is because (x /s C2) <s C produces different
2611  // results than (x /s C2) <u C or (x /u C2) <s C or even
2612  // (x /u C2) <u C. Simply casting the operands and result won't
2613  // work. :( The if statement below tests that condition and bails
2614  // if it finds it.
2615  if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2616  return nullptr;
2617 
2618  // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2619  // INT_MIN will also fail if the divisor is 1. Although folds of all these
2620  // division-by-constant cases should be present, we can not assert that they
2621  // have happened before we reach this icmp instruction.
2622  if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2623  return nullptr;
2624 
2625  // Compute Prod = C * C2. We are essentially solving an equation of
2626  // form X / C2 = C. We solve for X by multiplying C2 and C.
2627  // By solving for X, we can turn this into a range check instead of computing
2628  // a divide.
2629  APInt Prod = C * *C2;
2630 
2631  // Determine if the product overflows by seeing if the product is not equal to
2632  // the divide. Make sure we do the same kind of divide as in the LHS
2633  // instruction that we're folding.
2634  bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2635 
2636  // If the division is known to be exact, then there is no remainder from the
2637  // divide, so the covered range size is unit, otherwise it is the divisor.
2638  APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2639 
2640  // Figure out the interval that is being checked. For example, a comparison
2641  // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2642  // Compute this interval based on the constants involved and the signedness of
2643  // the compare/divide. This computes a half-open interval, keeping track of
2644  // whether either value in the interval overflows. After analysis each
2645  // overflow variable is set to 0 if it's corresponding bound variable is valid
2646  // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2647  int LoOverflow = 0, HiOverflow = 0;
2648  APInt LoBound, HiBound;
2649 
2650  if (!DivIsSigned) { // udiv
2651  // e.g. X/5 op 3 --> [15, 20)
2652  LoBound = Prod;
2653  HiOverflow = LoOverflow = ProdOV;
2654  if (!HiOverflow) {
2655  // If this is not an exact divide, then many values in the range collapse
2656  // to the same result value.
2657  HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2658  }
2659  } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2660  if (C.isZero()) { // (X / pos) op 0
2661  // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2662  LoBound = -(RangeSize - 1);
2663  HiBound = RangeSize;
2664  } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2665  LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2666  HiOverflow = LoOverflow = ProdOV;
2667  if (!HiOverflow)
2668  HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2669  } else { // (X / pos) op neg
2670  // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2671  HiBound = Prod + 1;
2672  LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2673  if (!LoOverflow) {
2674  APInt DivNeg = -RangeSize;
2675  LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2676  }
2677  }
2678  } else if (C2->isNegative()) { // Divisor is < 0.
2679  if (Div->isExact())
2680  RangeSize.negate();
2681  if (C.isZero()) { // (X / neg) op 0
2682  // e.g. X/-5 op 0 --> [-4, 5)
2683  LoBound = RangeSize + 1;
2684  HiBound = -RangeSize;
2685  if (HiBound == *C2) { // -INTMIN = INTMIN
2686  HiOverflow = 1; // [INTMIN+1, overflow)
2687  HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2688  }
2689  } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2690  // e.g. X/-5 op 3 --> [-19, -14)
2691  HiBound = Prod + 1;
2692  HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2693  if (!LoOverflow)
2694  LoOverflow =
2695  addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2696  } else { // (X / neg) op neg
2697  LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2698  LoOverflow = HiOverflow = ProdOV;
2699  if (!HiOverflow)
2700  HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2701  }
2702 
2703  // Dividing by a negative swaps the condition. LT <-> GT
2704  Pred = ICmpInst::getSwappedPredicate(Pred);
2705  }
2706 
2707  switch (Pred) {
2708  default:
2709  llvm_unreachable("Unhandled icmp predicate!");
2710  case ICmpInst::ICMP_EQ:
2711  if (LoOverflow && HiOverflow)
2712  return replaceInstUsesWith(Cmp, Builder.getFalse());
2713  if (HiOverflow)
2714  return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2715  X, ConstantInt::get(Ty, LoBound));
2716  if (LoOverflow)
2717  return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2718  X, ConstantInt::get(Ty, HiBound));
2719  return replaceInstUsesWith(
2720  Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2721  case ICmpInst::ICMP_NE:
2722  if (LoOverflow && HiOverflow)
2723  return replaceInstUsesWith(Cmp, Builder.getTrue());
2724  if (HiOverflow)
2725  return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2726  X, ConstantInt::get(Ty, LoBound));
2727  if (LoOverflow)
2728  return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2729  X, ConstantInt::get(Ty, HiBound));
2730  return replaceInstUsesWith(
2731  Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2732  case ICmpInst::ICMP_ULT:
2733  case ICmpInst::ICMP_SLT:
2734  if (LoOverflow == +1) // Low bound is greater than input range.
2735  return replaceInstUsesWith(Cmp, Builder.getTrue());
2736  if (LoOverflow == -1) // Low bound is less than input range.
2737  return replaceInstUsesWith(Cmp, Builder.getFalse());
2738  return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2739  case ICmpInst::ICMP_UGT:
2740  case ICmpInst::ICMP_SGT:
2741  if (HiOverflow == +1) // High bound greater than input range.
2742  return replaceInstUsesWith(Cmp, Builder.getFalse());
2743  if (HiOverflow == -1) // High bound less than input range.
2744  return replaceInstUsesWith(Cmp, Builder.getTrue());
2745  if (Pred == ICmpInst::ICMP_UGT)
2746  return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2747  return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2748  }
2749 
2750  return nullptr;
2751 }
2752 
2753 /// Fold icmp (sub X, Y), C.
2755  BinaryOperator *Sub,
2756  const APInt &C) {
2757  Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2758  ICmpInst::Predicate Pred = Cmp.getPredicate();
2759  Type *Ty = Sub->getType();
2760 
2761  // (SubC - Y) == C) --> Y == (SubC - C)
2762  // (SubC - Y) != C) --> Y != (SubC - C)
2763  Constant *SubC;
2764  if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2765  return new ICmpInst(Pred, Y,
2767  }
2768 
2769  // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2770  const APInt *C2;
2771  APInt SubResult;
2772  ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2773  bool HasNSW = Sub->hasNoSignedWrap();
2774  bool HasNUW = Sub->hasNoUnsignedWrap();
2775  if (match(X, m_APInt(C2)) &&
2776  ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2777  !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2778  return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2779 
2780  // X - Y == 0 --> X == Y.
2781  // X - Y != 0 --> X != Y.
2782  // TODO: We allow this with multiple uses as long as the other uses are not
2783  // in phis. The phi use check is guarding against a codegen regression
2784  // for a loop test. If the backend could undo this (and possibly
2785  // subsequent transforms), we would not need this hack.
2786  if (Cmp.isEquality() && C.isZero() &&
2787  none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2788  return new ICmpInst(Pred, X, Y);
2789 
2790  // The following transforms are only worth it if the only user of the subtract
2791  // is the icmp.
2792  // TODO: This is an artificial restriction for all of the transforms below
2793  // that only need a single replacement icmp. Can these use the phi test
2794  // like the transform above here?
2795  if (!Sub->hasOneUse())
2796  return nullptr;
2797 
2798  if (Sub->hasNoSignedWrap()) {
2799  // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2800  if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2801  return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2802 
2803  // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2804  if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2805  return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2806 
2807  // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2808  if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2809  return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2810 
2811  // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2812  if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2813  return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2814  }
2815 
2816  if (!match(X, m_APInt(C2)))
2817  return nullptr;
2818 
2819  // C2 - Y <u C -> (Y | (C - 1)) == C2
2820  // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2821  if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2822  (*C2 & (C - 1)) == (C - 1))
2823  return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2824 
2825  // C2 - Y >u C -> (Y | C) != C2
2826  // iff C2 & C == C and C + 1 is a power of 2
2827  if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2828  return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2829 
2830  // We have handled special cases that reduce.
2831  // Canonicalize any remaining sub to add as:
2832  // (C2 - Y) > C --> (Y + ~C2) < ~C
2833  Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2834  HasNUW, HasNSW);
2835  return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2836 }
2837 
2838 /// Fold icmp (add X, Y), C.
2840  BinaryOperator *Add,
2841  const APInt &C) {
2842  Value *Y = Add->getOperand(1);
2843  const APInt *C2;
2844  if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2845  return nullptr;
2846 
2847  // Fold icmp pred (add X, C2), C.
2848  Value *X = Add->getOperand(0);
2849  Type *Ty = Add->getType();
2850  const CmpInst::Predicate Pred = Cmp.getPredicate();
2851 
2852  // If the add does not wrap, we can always adjust the compare by subtracting
2853  // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2854  // are canonicalized to SGT/SLT/UGT/ULT.
2855  if ((Add->hasNoSignedWrap() &&
2856  (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2857  (Add->hasNoUnsignedWrap() &&
2858  (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2859  bool Overflow;
2860  APInt NewC =
2861  Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2862  // If there is overflow, the result must be true or false.
2863  // TODO: Can we assert there is no overflow because InstSimplify always
2864  // handles those cases?
2865  if (!Overflow)
2866  // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2867  return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2868  }
2869 
2870  auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2871  const APInt &Upper = CR.getUpper();
2872  const APInt &Lower = CR.getLower();
2873  if (Cmp.isSigned()) {
2874  if (Lower.isSignMask())
2875  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2876  if (Upper.isSignMask())
2877  return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2878  } else {
2879  if (Lower.isMinValue())
2880  return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2881  if (Upper.isMinValue())
2882  return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2883  }
2884 
2885  // This set of folds is intentionally placed after folds that use no-wrapping
2886  // flags because those folds are likely better for later analysis/codegen.
2889 
2890  // Fold compare with offset to opposite sign compare if it eliminates offset:
2891  // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
2892  if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
2893  return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
2894 
2895  // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
2896  if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
2897  return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
2898 
2899  // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
2900  if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
2901  return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
2902 
2903  // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
2904  if (Pred == CmpInst::ICMP_SLT && C == *C2)
2905  return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
2906 
2907  // (X + -1) <u C --> X <=u C (if X is never null)
2908  if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
2909  const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
2910  if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
2911  return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
2912  }
2913 
2914  if (!Add->hasOneUse())
2915  return nullptr;
2916 
2917  // X+C <u C2 -> (X & -C2) == C
2918  // iff C & (C2-1) == 0
2919  // C2 is a power of 2
2920  if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2921  return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2922  ConstantExpr::getNeg(cast<Constant>(Y)));
2923 
2924  // X+C >u C2 -> (X & ~C2) != C
2925  // iff C & C2 == 0
2926  // C2+1 is a power of 2
2927  if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2928  return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2929  ConstantExpr::getNeg(cast<Constant>(Y)));
2930 
2931  // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
2932  // to the ult form.
2933  // X+C2 >u C -> X+(C2-C-1) <u ~C
2934  if (Pred == ICmpInst::ICMP_UGT)
2935  return new ICmpInst(ICmpInst::ICMP_ULT,
2936  Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
2937  ConstantInt::get(Ty, ~C));
2938 
2939  return nullptr;
2940 }
2941 
2943  Value *&RHS, ConstantInt *&Less,
2944  ConstantInt *&Equal,
2945  ConstantInt *&Greater) {
2946  // TODO: Generalize this to work with other comparison idioms or ensure
2947  // they get canonicalized into this form.
2948 
2949  // select i1 (a == b),
2950  // i32 Equal,
2951  // i32 (select i1 (a < b), i32 Less, i32 Greater)
2952  // where Equal, Less and Greater are placeholders for any three constants.
2953  ICmpInst::Predicate PredA;
2954  if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2955  !ICmpInst::isEquality(PredA))
2956  return false;
2957  Value *EqualVal = SI->getTrueValue();
2958  Value *UnequalVal = SI->getFalseValue();
2959  // We still can get non-canonical predicate here, so canonicalize.
2960  if (PredA == ICmpInst::ICMP_NE)
2961  std::swap(EqualVal, UnequalVal);
2962  if (!match(EqualVal, m_ConstantInt(Equal)))
2963  return false;
2964  ICmpInst::Predicate PredB;
2965  Value *LHS2, *RHS2;
2966  if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2967  m_ConstantInt(Less), m_ConstantInt(Greater))))
2968  return false;
2969  // We can get predicate mismatch here, so canonicalize if possible:
2970  // First, ensure that 'LHS' match.
2971  if (LHS2 != LHS) {
2972  // x sgt y <--> y slt x
2973  std::swap(LHS2, RHS2);
2974  PredB = ICmpInst::getSwappedPredicate(PredB);
2975  }
2976  if (LHS2 != LHS)
2977  return false;
2978  // We also need to canonicalize 'RHS'.
2979  if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2980  // x sgt C-1 <--> x sge C <--> not(x slt C)
2981  auto FlippedStrictness =
2983  PredB, cast<Constant>(RHS2));
2984  if (!FlippedStrictness)
2985  return false;
2986  assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
2987  "basic correctness failure");
2988  RHS2 = FlippedStrictness->second;
2989  // And kind-of perform the result swap.
2990  std::swap(Less, Greater);
2991  PredB = ICmpInst::ICMP_SLT;
2992  }
2993  return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2994 }
2995 
2997  SelectInst *Select,
2998  ConstantInt *C) {
2999 
3000  assert(C && "Cmp RHS should be a constant int!");
3001  // If we're testing a constant value against the result of a three way
3002  // comparison, the result can be expressed directly in terms of the
3003  // original values being compared. Note: We could possibly be more
3004  // aggressive here and remove the hasOneUse test. The original select is
3005  // really likely to simplify or sink when we remove a test of the result.
3006  Value *OrigLHS, *OrigRHS;
3007  ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3008  if (Cmp.hasOneUse() &&
3009  matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3010  C3GreaterThan)) {
3011  assert(C1LessThan && C2Equal && C3GreaterThan);
3012 
3013  bool TrueWhenLessThan =
3014  ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
3015  ->isAllOnesValue();
3016  bool TrueWhenEqual =
3017  ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
3018  ->isAllOnesValue();
3019  bool TrueWhenGreaterThan =
3020  ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
3021  ->isAllOnesValue();
3022 
3023  // This generates the new instruction that will replace the original Cmp
3024  // Instruction. Instead of enumerating the various combinations when
3025  // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3026  // false, we rely on chaining of ORs and future passes of InstCombine to
3027  // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3028 
3029  // When none of the three constants satisfy the predicate for the RHS (C),
3030  // the entire original Cmp can be simplified to a false.
3031  Value *Cond = Builder.getFalse();
3032  if (TrueWhenLessThan)
3033  Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
3034  OrigLHS, OrigRHS));
3035  if (TrueWhenEqual)
3036  Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
3037  OrigLHS, OrigRHS));
3038  if (TrueWhenGreaterThan)
3039  Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
3040  OrigLHS, OrigRHS));
3041 
3042  return replaceInstUsesWith(Cmp, Cond);
3043  }
3044  return nullptr;
3045 }
3046 
3048  auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3049  if (!Bitcast)
3050  return nullptr;
3051 
3052  ICmpInst::Predicate Pred = Cmp.getPredicate();
3053  Value *Op1 = Cmp.getOperand(1);
3054  Value *BCSrcOp = Bitcast->getOperand(0);
3055  Type *SrcType = Bitcast->getSrcTy();
3056  Type *DstType = Bitcast->getType();
3057 
3058  // Make sure the bitcast doesn't change between scalar and vector and
3059  // doesn't change the number of vector elements.
3060  if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3061  SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3062  // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3063  Value *X;
3064  if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3065  // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3066  // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3067  // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3068  // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3069  if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3070  Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3071  match(Op1, m_Zero()))
3072  return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3073 
3074  // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3075  if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3076  return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3077 
3078  // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3079  if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3080  return new ICmpInst(Pred, X,
3081  ConstantInt::getAllOnesValue(X->getType()));
3082  }
3083 
3084  // Zero-equality checks are preserved through unsigned floating-point casts:
3085  // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3086  // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3087  if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3088  if (Cmp.isEquality() && match(Op1, m_Zero()))
3089  return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3090 
3091  // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3092  // the FP extend/truncate because that cast does not change the sign-bit.
3093  // This is true for all standard IEEE-754 types and the X86 80-bit type.
3094  // The sign-bit is always the most significant bit in those types.
3095  const APInt *C;
3096  bool TrueIfSigned;
3097  if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
3098  isSignBitCheck(Pred, *C, TrueIfSigned)) {
3099  if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3100  match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
3101  // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3102  // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3103  Type *XType = X->getType();
3104 
3105  // We can't currently handle Power style floating point operations here.
3106  if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3107  Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3108  if (auto *XVTy = dyn_cast<VectorType>(XType))
3109  NewType = VectorType::get(NewType, XVTy->getElementCount());
3110  Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3111  if (TrueIfSigned)
3112  return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3113  ConstantInt::getNullValue(NewType));
3114  else
3115  return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3116  ConstantInt::getAllOnesValue(NewType));
3117  }
3118  }
3119  }
3120  }
3121 
3122  // Test to see if the operands of the icmp are casted versions of other
3123  // values. If the ptr->ptr cast can be stripped off both arguments, do so.
3124  if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
3125  // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
3126  // so eliminate it as well.
3127  if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
3128  Op1 = BC2->getOperand(0);
3129 
3130  Op1 = Builder.CreateBitCast(Op1, SrcType);
3131  return new ICmpInst(Pred, BCSrcOp, Op1);
3132  }
3133 
3134  const APInt *C;
3135  if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3136  !SrcType->isIntOrIntVectorTy())
3137  return nullptr;
3138 
3139  // If this is checking if all elements of a vector compare are set or not,
3140  // invert the casted vector equality compare and test if all compare
3141  // elements are clear or not. Compare against zero is generally easier for
3142  // analysis and codegen.
3143  // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3144  // Example: are all elements equal? --> are zero elements not equal?
3145  // TODO: Try harder to reduce compare of 2 freely invertible operands?
3146  if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
3147  isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
3148  Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
3149  return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3150  }
3151 
3152  // If this is checking if all elements of an extended vector are clear or not,
3153  // compare in a narrow type to eliminate the extend:
3154  // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3155  Value *X;
3156  if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3157  match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3158  if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3159  Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3160  Value *NewCast = Builder.CreateBitCast(X, NewType);
3161  return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3162  }
3163  }
3164 
3165  // Folding: icmp <pred> iN X, C
3166  // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3167  // and C is a splat of a K-bit pattern
3168  // and SC is a constant vector = <C', C', C', ..., C'>
3169  // Into:
3170  // %E = extractelement <M x iK> %vec, i32 C'
3171  // icmp <pred> iK %E, trunc(C)
3172  Value *Vec;
3174  if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3175  // Check whether every element of Mask is the same constant
3176  if (all_equal(Mask)) {
3177  auto *VecTy = cast<VectorType>(SrcType);
3178  auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3179  if (C->isSplat(EltTy->getBitWidth())) {
3180  // Fold the icmp based on the value of C
3181  // If C is M copies of an iK sized bit pattern,
3182  // then:
3183  // => %E = extractelement <N x iK> %vec, i32 Elem
3184  // icmp <pred> iK %SplatVal, <pattern>
3185  Value *Elem = Builder.getInt32(Mask[0]);
3186  Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3187  Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3188  return new ICmpInst(Pred, Extract, NewC);
3189  }
3190  }
3191  }
3192  return nullptr;
3193 }
3194 
3195 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3196 /// where X is some kind of instruction.
3198  const APInt *C;
3199 
3200  if (match(Cmp.getOperand(1), m_APInt(C))) {
3201  if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3202  if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3203  return I;
3204 
3205  if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3206  // For now, we only support constant integers while folding the
3207  // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3208  // similar to the cases handled by binary ops above.
3209  if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3210  if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3211  return I;
3212 
3213  if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3214  if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3215  return I;
3216 
3217  if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3218  if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3219  return I;
3220 
3221  // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3222  // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3223  // TODO: This checks one-use, but that is not strictly necessary.
3224  Value *Cmp0 = Cmp.getOperand(0);
3225  Value *X, *Y;
3226  if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3227  (match(Cmp0,
3228  m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3229  m_Value(X), m_Value(Y)))) ||
3230  match(Cmp0,
3231  m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3232  m_Value(X), m_Value(Y))))))
3233  return new ICmpInst(Cmp.getPredicate(), X, Y);
3234  }
3235 
3236  if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3237  return foldICmpInstWithConstantAllowUndef(Cmp, *C);
3238 
3239  return nullptr;
3240 }
3241 
3242 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3243 /// icmp eq/ne BO, C.
3245  ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3246  // TODO: Some of these folds could work with arbitrary constants, but this
3247  // function is limited to scalar and vector splat constants.
3248  if (!Cmp.isEquality())
3249  return nullptr;
3250 
3251  ICmpInst::Predicate Pred = Cmp.getPredicate();
3252  bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3253  Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3254  Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3255 
3256  switch (BO->getOpcode()) {
3257  case Instruction::SRem:
3258  // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3259  if (C.isZero() && BO->hasOneUse()) {
3260  const APInt *BOC;
3261  if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3262  Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3263  return new ICmpInst(Pred, NewRem,
3265  }
3266  }
3267  break;
3268  case Instruction::Add: {
3269  // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3270  if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3271  if (BO->hasOneUse())
3272  return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, BOC));
3273  } else if (C.isZero()) {
3274  // Replace ((add A, B) != 0) with (A != -B) if A or B is
3275  // efficiently invertible, or if the add has just this one use.
3276  if (Value *NegVal = dyn_castNegVal(BOp1))
3277  return new ICmpInst(Pred, BOp0, NegVal);
3278  if (Value *NegVal = dyn_castNegVal(BOp0))
3279  return new ICmpInst(Pred, NegVal, BOp1);
3280  if (BO->hasOneUse()) {
3281  Value *Neg = Builder.CreateNeg(BOp1);
3282  Neg->takeName(BO);
3283  return new ICmpInst(Pred, BOp0, Neg);
3284  }
3285  }
3286  break;
3287  }
3288  case Instruction::Xor:
3289  if (BO->hasOneUse()) {
3290  if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3291  // For the xor case, we can xor two constants together, eliminating
3292  // the explicit xor.
3293  return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3294  } else if (C.isZero()) {
3295  // Replace ((xor A, B) != 0) with (A != B)
3296  return new ICmpInst(Pred, BOp0, BOp1);
3297  }
3298  }
3299  break;
3300  case Instruction::Or: {
3301  const APInt *BOC;
3302  if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3303  // Comparing if all bits outside of a constant mask are set?
3304  // Replace (X | C) == -1 with (X & ~C) == ~C.
3305  // This removes the -1 constant.
3306  Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3307  Value *And = Builder.CreateAnd(BOp0, NotBOC);
3308  return new ICmpInst(Pred, And, NotBOC);
3309  }
3310  break;
3311  }
3312  case Instruction::And: {
3313  const APInt *BOC;
3314  if (match(BOp1, m_APInt(BOC))) {
3315  // If we have ((X & C) == C), turn it into ((X & C) != 0).
3316  if (C == *BOC && C.isPowerOf2())
3317  return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
3319  }
3320  break;
3321  }
3322  case Instruction::UDiv:
3323  if (C.isZero()) {
3324  // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3325  auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3326  return new ICmpInst(NewPred, BOp1, BOp0);
3327  }
3328  break;
3329  default:
3330  break;
3331  }
3332  return nullptr;
3333 }
3334 
3335 /// Fold an equality icmp with LLVM intrinsic and constant operand.
3337  ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3338  Type *Ty = II->getType();
3339  unsigned BitWidth = C.getBitWidth();
3340  const ICmpInst::Predicate Pred = Cmp.getPredicate();
3341 
3342  switch (II->getIntrinsicID()) {
3343  case Intrinsic::abs:
3344  // abs(A) == 0 -> A == 0
3345  // abs(A) == INT_MIN -> A == INT_MIN
3346  if (C.isZero() || C.isMinSignedValue())
3347  return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3348  break;
3349 
3350  case Intrinsic::bswap:
3351  // bswap(A) == C -> A == bswap(C)
3352  return new ICmpInst(Pred, II->getArgOperand(0),
3353  ConstantInt::get(Ty, C.byteSwap()));
3354 
3355  case Intrinsic::ctlz:
3356  case Intrinsic::cttz: {
3357  // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3358  if (C == BitWidth)
3359  return new ICmpInst(Pred, II->getArgOperand(0),
3361 
3362  // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3363  // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3364  // Limit to one use to ensure we don't increase instruction count.
3365  unsigned Num = C.getLimitedValue(BitWidth);
3366  if (Num != BitWidth && II->hasOneUse()) {
3367  bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3368  APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3369  : APInt::getHighBitsSet(BitWidth, Num + 1);
3370  APInt Mask2 = IsTrailing
3372  : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3373  return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3374  ConstantInt::get(Ty, Mask2));
3375  }
3376  break;
3377  }
3378 
3379  case Intrinsic::ctpop: {
3380  // popcount(A) == 0 -> A == 0 and likewise for !=
3381  // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3382  bool IsZero = C.isZero();
3383  if (IsZero || C == BitWidth)
3384  return new ICmpInst(Pred, II->getArgOperand(0),
3385  IsZero ? Constant::getNullValue(Ty)
3387 
3388  break;
3389  }
3390 
3391  case Intrinsic::fshl:
3392  case Intrinsic::fshr:
3393  if (II->getArgOperand(0) == II->getArgOperand(1)) {
3394  const APInt *RotAmtC;
3395  // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3396  // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3397  if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3398  return new ICmpInst(Pred, II->getArgOperand(0),
3399  II->getIntrinsicID() == Intrinsic::fshl
3400  ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3401  : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3402  }
3403  break;
3404 
3405  case Intrinsic::uadd_sat: {
3406  // uadd.sat(a, b) == 0 -> (a | b) == 0
3407  if (C.isZero()) {
3408  Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3409  return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3410  }
3411  break;
3412  }
3413 
3414  case Intrinsic::usub_sat: {
3415  // usub.sat(a, b) == 0 -> a <= b
3416  if (C.isZero()) {
3417  ICmpInst::Predicate NewPred =
3419  return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3420  }
3421  break;
3422  }
3423  default:
3424  break;
3425  }
3426 
3427  return nullptr;
3428 }
3429 
3430 /// Fold an icmp with LLVM intrinsics
3432  assert(Cmp.isEquality());
3433 
3434  ICmpInst::Predicate Pred = Cmp.getPredicate();
3435  Value *Op0 = Cmp.getOperand(0);
3436  Value *Op1 = Cmp.getOperand(1);
3437  const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3438  const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3439  if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3440  return nullptr;
3441 
3442  switch (IIOp0->getIntrinsicID()) {
3443  case Intrinsic::bswap:
3444  case Intrinsic::bitreverse:
3445  // If both operands are byte-swapped or bit-reversed, just compare the
3446  // original values.
3447  return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3448  case Intrinsic::fshl:
3449  case Intrinsic::fshr:
3450  // If both operands are rotated by same amount, just compare the
3451  // original values.
3452  if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3453  break;
3454  if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3455  break;
3456  if (IIOp0->getOperand(2) != IIOp1->getOperand(2))
3457  break;
3458  return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3459  default:
3460  break;
3461  }
3462 
3463  return nullptr;
3464 }
3465 
3466 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3467 /// where X is some kind of instruction and C is AllowUndef.
3468 /// TODO: Move more folds which allow undef to this function.
3469 Instruction *
3471  const APInt &C) {
3472  const ICmpInst::Predicate Pred = Cmp.getPredicate();
3473  if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3474  switch (II->getIntrinsicID()) {
3475  default:
3476  break;
3477  case Intrinsic::fshl:
3478  case Intrinsic::fshr:
3479  if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3480  // (rot X, ?) == 0/-1 --> X == 0/-1
3481  if (C.isZero() || C.isAllOnes())
3482  return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3483  }
3484  break;
3485  }
3486  }
3487 
3488  return nullptr;
3489 }
3490 
3491 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
3493  BinaryOperator *BO,
3494  const APInt &C) {
3495  switch (BO->getOpcode()) {
3496  case Instruction::Xor:
3497  if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3498  return I;
3499  break;
3500  case Instruction::And:
3501  if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3502  return I;
3503  break;
3504  case Instruction::Or:
3505  if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3506  return I;
3507  break;
3508  case Instruction::Mul:
3509  if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3510  return I;
3511  break;
3512  case Instruction::Shl:
3513  if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3514  return I;
3515  break;
3516  case Instruction::LShr:
3517  case Instruction::AShr:
3518  if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3519  return I;
3520  break;
3521  case Instruction::SRem:
3522  if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3523  return I;
3524  break;
3525  case Instruction::UDiv:
3526  if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3527  return I;
3528  [[fallthrough]];
3529  case Instruction::SDiv:
3530  if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3531  return I;
3532  break;
3533  case Instruction::Sub:
3534  if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3535  return I;
3536  break;
3537  case Instruction::Add:
3538  if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3539  return I;
3540  break;
3541  default:
3542  break;
3543  }
3544 
3545  // TODO: These folds could be refactored to be part of the above calls.
3546  return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3547 }
3548 
3549 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
3551  IntrinsicInst *II,
3552  const APInt &C) {
3553  if (Cmp.isEquality())
3554  return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3555 
3556  Type *Ty = II->getType();
3557  unsigned BitWidth = C.getBitWidth();
3558  ICmpInst::Predicate Pred = Cmp.getPredicate();
3559  switch (II->getIntrinsicID()) {
3560  case Intrinsic::ctpop: {
3561  // (ctpop X > BitWidth - 1) --> X == -1
3562  Value *X = II->getArgOperand(0);
3563  if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3564  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3566  // (ctpop X < BitWidth) --> X != -1
3567  if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3568  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3570  break;
3571  }
3572  case Intrinsic::ctlz: {
3573  // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3574  if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3575  unsigned Num = C.getLimitedValue();
3576  APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3577  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3578  II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3579  }
3580 
3581  // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3582  if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3583  unsigned Num = C.getLimitedValue();
3584  APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3585  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3586  II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3587  }
3588  break;
3589  }
3590  case Intrinsic::cttz: {
3591  // Limit to one use to ensure we don't increase instruction count.
3592  if (!II->hasOneUse())
3593  return nullptr;
3594 
3595  // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3596  if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3597  APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3598  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3599  Builder.CreateAnd(II->getArgOperand(0), Mask),
3601  }
3602 
3603  // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3604  if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3605  APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3606  return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3607  Builder.CreateAnd(II->getArgOperand(0), Mask),
3609  }
3610  break;
3611  }
3612  default:
3613  break;
3614  }
3615 
3616  return nullptr;
3617 }
3618 
3619 /// Handle icmp with constant (but not simple integer constant) RHS.
3621  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3622  Constant *RHSC = dyn_cast<Constant>(Op1);
3623  Instruction *LHSI = dyn_cast<Instruction>(Op0);
3624  if (!RHSC || !LHSI)
3625  return nullptr;
3626 
3627  switch (LHSI->getOpcode()) {
3628  case Instruction::GetElementPtr:
3629  // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3630  if (RHSC->isNullValue() &&
3631  cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3632  return new ICmpInst(
3633  I.getPredicate(), LHSI->getOperand(0),
3635  break;
3636  case Instruction::PHI:
3637  // Only fold icmp into the PHI if the phi and icmp are in the same
3638  // block. If in the same block, we're encouraging jump threading. If
3639  // not, we are just pessimizing the code by making an i1 phi.
3640  if (LHSI->getParent() == I.getParent())
3641  if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3642  return NV;
3643  break;
3644  case Instruction::IntToPtr:
3645  // icmp pred inttoptr(X), null -> icmp pred X, 0
3646  if (RHSC->isNullValue() &&
3647  DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3648  return new ICmpInst(
3649  I.getPredicate(), LHSI->getOperand(0),
3651  break;
3652 
3653  case Instruction::Load:
3654  // Try to optimize things like "A[i] > 4" to index computations.
3655  if (GetElementPtrInst *GEP =
3656  dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3657  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3658  if (Instruction *Res =
3659  foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3660  return Res;
3661  break;
3662  }
3663 
3664  return nullptr;
3665 }
3666 
3668  SelectInst *SI, Value *RHS,
3669  const ICmpInst &I) {
3670  // Try to fold the comparison into the select arms, which will cause the
3671  // select to be converted into a logical and/or.
3672  auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3673  if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3674  return Res;
3675  if (Optional<bool> Impl = isImpliedCondition(SI->getCondition(), Pred, Op,
3676  RHS, DL, SelectCondIsTrue))
3677  return ConstantInt::get(I.getType(), *Impl);
3678  return nullptr;
3679  };
3680 
3681  ConstantInt *CI = nullptr;
3682  Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3683  if (Op1)
3684  CI = dyn_cast<ConstantInt>(Op1);
3685 
3686  Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3687  if (Op2)
3688  CI = dyn_cast<ConstantInt>(Op2);
3689 
3690  // We only want to perform this transformation if it will not lead to
3691  // additional code. This is true if either both sides of the select
3692  // fold to a constant (in which case the icmp is replaced with a select
3693  // which will usually simplify) or this is the only user of the
3694  // select (in which case we are trading a select+icmp for a simpler
3695  // select+icmp) or all uses of the select can be replaced based on
3696  // dominance information ("Global cases").
3697  bool Transform = false;
3698  if (Op1 && Op2)
3699  Transform = true;
3700  else if (Op1 || Op2) {
3701  // Local case
3702  if (SI->hasOneUse())
3703  Transform = true;
3704  // Global cases
3705  else if (CI && !CI->isZero())
3706  // When Op1 is constant try replacing select with second operand.
3707  // Otherwise Op2 is constant and try replacing select with first
3708  // operand.
3709  Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
3710  }
3711  if (Transform) {
3712  if (!Op1)
3713  Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
3714  if (!Op2)
3715  Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
3716  return SelectInst::Create(SI->getOperand(0), Op1, Op2);
3717  }
3718 
3719  return nullptr;
3720 }
3721 
3722 /// Some comparisons can be simplified.
3723 /// In this case, we are looking for comparisons that look like
3724 /// a check for a lossy truncation.
3725 /// Folds:
3726 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3727 /// Where Mask is some pattern that produces all-ones in low bits:
3728 /// (-1 >> y)
3729 /// ((-1 << y) >> y) <- non-canonical, has extra uses
3730 /// ~(-1 << y)
3731 /// ((1 << y) + (-1)) <- non-canonical, has extra uses
3732 /// The Mask can be a constant, too.
3733 /// For some predicates, the operands are commutative.
3734 /// For others, x can only be on a specific side.
3737  ICmpInst::Predicate SrcPred;
3738  Value *X, *M, *Y;
3739  auto m_VariableMask = m_CombineOr(
3741  m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3744  auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3745  if (!match(&I, m_c_ICmp(SrcPred,
3747  m_Deferred(X))))
3748  return nullptr;
3749 
3750  ICmpInst::Predicate DstPred;
3751  switch (SrcPred) {
3752  case ICmpInst::Predicate::ICMP_EQ:
3753  // x & (-1 >> y) == x -> x u<= (-1 >> y)
3754  DstPred = ICmpInst::Predicate::ICMP_ULE;
3755  break;
3756  case ICmpInst::Predicate::ICMP_NE:
3757  // x & (-1 >> y) != x -> x u> (-1 >> y)
3758  DstPred = ICmpInst::Predicate::ICMP_UGT;
3759  break;
3760  case ICmpInst::Predicate::ICMP_ULT:
3761  // x & (-1 >> y) u< x -> x u> (-1 >> y)
3762  // x u> x & (-1 >> y) -> x u> (-1 >> y)
3763  DstPred = ICmpInst::Predicate::ICMP_UGT;
3764  break;
3765  case ICmpInst::Predicate::ICMP_UGE:
3766  // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3767  // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3768  DstPred = ICmpInst::Predicate::ICMP_ULE;
3769  break;
3770  case ICmpInst::Predicate::ICMP_SLT:
3771  // x & (-1 >> y) s< x -> x s> (-1 >> y)
3772  // x s> x & (-1 >> y) -> x s> (-1 >> y)
3773  if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3774  return nullptr;
3775  if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3776  return nullptr;
3777  DstPred = ICmpInst::Predicate::ICMP_SGT;
3778  break;
3779  case ICmpInst::Predicate::ICMP_SGE:
3780  // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3781  // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3782  if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3783  return nullptr;
3784  if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3785  return nullptr;
3786  DstPred = ICmpInst::Predicate::ICMP_SLE;
3787  break;
3788  case ICmpInst::Predicate::ICMP_SGT:
3789  case ICmpInst::Predicate::ICMP_SLE:
3790  return nullptr;
3791  case ICmpInst::Predicate::ICMP_UGT:
3792  case ICmpInst::Predicate::ICMP_ULE:
3793  llvm_unreachable("Instsimplify took care of commut. variant");
3794  break;
3795  default:
3796  llvm_unreachable("All possible folds are handled.");
3797  }
3798 
3799  // The mask value may be a vector constant that has undefined elements. But it
3800  // may not be safe to propagate those undefs into the new compare, so replace
3801  // those elements by copying an existing, defined, and safe scalar constant.
3802  Type *OpTy = M->getType();
3803  auto *VecC = dyn_cast<Constant>(M);
3804  auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
3805  if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
3806  Constant *SafeReplacementConstant = nullptr;
3807  for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
3808  if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
3809  SafeReplacementConstant = VecC->getAggregateElement(i);
3810  break;
3811  }
3812  }
3813  assert(SafeReplacementConstant && "Failed to find undef replacement");
3814  M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
3815  }
3816 
3817  return Builder.CreateICmp(DstPred, X, M);
3818 }
3819 
3820 /// Some comparisons can be simplified.
3821 /// In this case, we are looking for comparisons that look like
3822 /// a check for a lossy signed truncation.
3823 /// Folds: (MaskedBits is a constant.)
3824 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3825 /// Into:
3826 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3827 /// Where KeptBits = bitwidth(%x) - MaskedBits
3828 static Value *
3831  ICmpInst::Predicate SrcPred;
3832  Value *X;
3833  const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3834  // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3835  if (!match(&I, m_c_ICmp(SrcPred,
3837  m_APInt(C1))),
3838  m_Deferred(X))))
3839  return nullptr;
3840 
3841  // Potential handling of non-splats: for each element:
3842  // * if both are undef, replace with constant 0.
3843  // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3844  // * if both are not undef, and are different, bailout.
3845  // * else, only one is undef, then pick the non-undef one.
3846 
3847  // The shift amount must be equal.
3848  if (*C0 != *C1)
3849  return nullptr;
3850  const APInt &MaskedBits = *C0;
3851  assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3852 
3853  ICmpInst::Predicate DstPred;
3854  switch (SrcPred) {
3855  case ICmpInst::Predicate::ICMP_EQ:
3856  // ((%x << MaskedBits) a>> MaskedBits) == %x
3857  // =>
3858  // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3859  DstPred = ICmpInst::Predicate::ICMP_ULT;
3860  break;
3861  case ICmpInst::Predicate::ICMP_NE:
3862  // ((%x << MaskedBits) a>> MaskedBits) != %x
3863  // =>
3864  // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3865  DstPred = ICmpInst::Predicate::ICMP_UGE;
3866  break;
3867  // FIXME: are more folds possible?
3868  default:
3869  return nullptr;
3870  }
3871 
3872  auto *XType = X->getType();
3873  const unsigned XBitWidth = XType->getScalarSizeInBits();
3874  const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3875  assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3876 
3877  // KeptBits = bitwidth(%x) - MaskedBits
3878  const APInt KeptBits = BitWidth - MaskedBits;
3879  assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3880  // ICmpCst = (1 << KeptBits)
3881  const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3882  assert(ICmpCst.isPowerOf2());
3883  // AddCst = (1 << (KeptBits-1))
3884  const APInt AddCst = ICmpCst.lshr(1);
3885  assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3886 
3887  // T0 = add %x, AddCst
3888  Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3889  // T1 = T0 DstPred ICmpCst
3890  Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3891 
3892  return T1;
3893 }
3894 
3895 // Given pattern:
3896 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3897 // we should move shifts to the same hand of 'and', i.e. rewrite as
3898 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3899 // We are only interested in opposite logical shifts here.
3900 // One of the shifts can be truncated.
3901 // If we can, we want to end up creating 'lshr' shift.
3902 static Value *
3905  if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3906  !I.getOperand(0)->hasOneUse())
3907  return nullptr;
3908 
3909  auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3910 
3911  // Look for an 'and' of two logical shifts, one of which may be truncated.
3912  // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3913  Instruction *XShift, *MaybeTruncation, *YShift;
3914  if (!match(
3915  I.getOperand(0),
3916  m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3918  m_AnyLogicalShift, m_Instruction(YShift))),
3919  m_Instruction(MaybeTruncation)))))
3920  return nullptr;
3921 
3922  // We potentially looked past 'trunc', but only when matching YShift,
3923  // therefore YShift must have the widest type.
3924  Instruction *WidestShift = YShift;
3925  // Therefore XShift must have the shallowest type.
3926  // Or they both have identical types if there was no truncation.
3927  Instruction *NarrowestShift = XShift;
3928 
3929  Type *WidestTy = WidestShift->getType();
3930  Type *NarrowestTy = NarrowestShift->getType();
3931  assert(NarrowestTy == I.getOperand(0)->getType() &&
3932  "We did not look past any shifts while matching XShift though.");
3933  bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3934 
3935  // If YShift is a 'lshr', swap the shifts around.
3936  if (match(YShift, m_LShr(m_Value(), m_Value())))
3937  std::swap(XShift, YShift);
3938 
3939  // The shifts must be in opposite directions.
3940  auto XShiftOpcode = XShift->getOpcode();
3941  if (XShiftOpcode == YShift->getOpcode())
3942  return nullptr; // Do not care about same-direction shifts here.
3943 
3944  Value *X, *XShAmt, *Y, *YShAmt;
3945  match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3946  match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3947 
3948  // If one of the values being shifted is a constant, then we will end with
3949  // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3950  // however, we will need to ensure that we won't increase instruction count.
3951  if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3952  // At least one of the hands of the 'and' should be one-use shift.
3953  if (!match(I.getOperand(0),
3954  m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3955  return nullptr;
3956  if (HadTrunc) {
3957  // Due to the 'trunc', we will need to widen X. For that either the old
3958  // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3959  if (!MaybeTruncation->hasOneUse() &&
3960  !NarrowestShift->getOperand(1)->hasOneUse())
3961  return nullptr;
3962  }
3963  }
3964 
3965  // We have two shift amounts from two different shifts. The types of those
3966  // shift amounts may not match. If that's the case let's bailout now.
3967  if (XShAmt->getType() != YShAmt->getType())
3968  return nullptr;
3969 
3970  // As input, we have the following pattern:
3971  // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3972  // We want to rewrite that as:
3973  // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3974  // While we know that originally (Q+K) would not overflow
3975  // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
3976  // shift amounts. so it may now overflow in smaller bitwidth.
3977  // To ensure that does not happen, we need to ensure that the total maximal
3978  // shift amount is still representable in that smaller bit width.
3979  unsigned MaximalPossibleTotalShiftAmount =
3980  (WidestTy->getScalarSizeInBits() - 1) +
3981  (NarrowestTy->getScalarSizeInBits() - 1);
3982  APInt MaximalRepresentableShiftAmount =
3984  if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
3985  return nullptr;
3986 
3987  // Can we fold (XShAmt+YShAmt) ?
3988  auto *NewShAmt = dyn_cast_or_null<Constant>(
3989  simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
3990  /*isNUW=*/false, SQ.getWithInstruction(&I)));
3991  if (!NewShAmt)
3992  return nullptr;
3993  NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
3994  unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
3995 
3996  // Is the new shift amount smaller than the bit width?
3997  // FIXME: could also rely on ConstantRange.
3998  if (!match(NewShAmt,
3999  m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
4000  APInt(WidestBitWidth, WidestBitWidth))))
4001  return nullptr;
4002 
4003  // An extra legality check is needed if we had trunc-of-lshr.
4004  if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4005  auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4006  WidestShift]() {
4007  // It isn't obvious whether it's worth it to analyze non-constants here.
4008  // Also, let's basically give up on non-splat cases, pessimizing vectors.
4009  // If *any* of these preconditions matches we can perform the fold.
4010  Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4011  ? NewShAmt->getSplatValue()
4012  : NewShAmt;
4013  // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4014  if (NewShAmtSplat &&
4015  (NewShAmtSplat->isNullValue() ||
4016  NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4017  return true;
4018  // We consider *min* leading zeros so a single outlier
4019  // blocks the transform as opposed to allowing it.
4020  if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4021  KnownBits Known = computeKnownBits(C, SQ.DL);
4022  unsigned MinLeadZero = Known.countMinLeadingZeros();
4023  // If the value being shifted has at most lowest bit set we can fold.
4024  unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4025  if (MaxActiveBits <= 1)
4026  return true;
4027  // Precondition: NewShAmt u<= countLeadingZeros(C)
4028  if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
4029  return true;
4030  }
4031  if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
4032  KnownBits Known = computeKnownBits(C, SQ.DL);
4033  unsigned MinLeadZero = Known.countMinLeadingZeros();
4034  // If the value being shifted has at most lowest bit set we can fold.
4035  unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4036  if (MaxActiveBits <= 1)
4037  return true;
4038  // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
4039  if (NewShAmtSplat) {
4040  APInt AdjNewShAmt =
4041  (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
4042  if (AdjNewShAmt.ule(MinLeadZero))
4043  return true;
4044  }
4045  }
4046  return false; // Can't tell if it's ok.
4047  };
4048  if (!CanFold())
4049  return nullptr;
4050  }
4051 
4052  // All good, we can do this fold.
4053  X = Builder.CreateZExt(X, WidestTy);
4054  Y = Builder.CreateZExt(Y, WidestTy);
4055  // The shift is the same that was for X.
4056  Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
4057  ? Builder.CreateLShr(X, NewShAmt)
4058  : Builder.CreateShl(X, NewShAmt);
4059  Value *T1 = Builder.CreateAnd(T0, Y);
4060  return Builder.CreateICmp(I.getPredicate(), T1,
4061  Constant::getNullValue(WidestTy));
4062 }
4063 
4064 /// Fold
4065 /// (-1 u/ x) u< y
4066 /// ((x * y) ?/ x) != y
4067 /// to
4068 /// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
4069 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
4070 /// will mean that we are looking for the opposite answer.
4072  ICmpInst::Predicate Pred;
4073  Value *X, *Y;
4074  Instruction *Mul;
4075  Instruction *Div;
4076  bool NeedNegation;
4077  // Look for: (-1 u/ x) u</u>= y
4078  if (!I.isEquality() &&
4079  match(&I, m_c_ICmp(Pred,
4081  m_Instruction(Div)),
4082  m_Value(Y)))) {
4083  Mul = nullptr;
4084 
4085  // Are we checking that overflow does not happen, or does happen?
4086  switch (Pred) {
4087  case ICmpInst::Predicate::ICMP_ULT:
4088  NeedNegation = false;
4089  break; // OK
4090  case ICmpInst::Predicate::ICMP_UGE:
4091  NeedNegation = true;
4092  break; // OK
4093  default:
4094  return nullptr; // Wrong predicate.
4095  }
4096  } else // Look for: ((x * y) / x) !=/== y
4097  if (I.isEquality() &&
4098  match(&I,
4099  m_c_ICmp(Pred, m_Value(Y),
4100  m_CombineAnd(
4102  m_Value(X)),
4103  m_Instruction(Mul)),
4104  m_Deferred(X))),
4105  m_Instruction(Div))))) {
4106  NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
4107  } else
4108  return nullptr;
4109 
4111  // If the pattern included (x * y), we'll want to insert new instructions
4112  // right before that original multiplication so that we can replace it.
4113  bool MulHadOtherUses = Mul && !Mul->hasOneUse();
4114  if (MulHadOtherUses)
4115  Builder.SetInsertPoint(Mul);
4116 
4117  Function *F = Intrinsic::getDeclaration(I.getModule(),
4118  Div->getOpcode() == Instruction::UDiv
4119  ? Intrinsic::umul_with_overflow
4120  : Intrinsic::smul_with_overflow,
4121  X->getType());
4122  CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
4123 
4124  // If the multiplication was used elsewhere, to ensure that we don't leave
4125  // "duplicate" instructions, replace uses of that original multiplication
4126  // with the multiplication result from the with.overflow intrinsic.
4127  if (MulHadOtherUses)
4128  replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4129 
4130  Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4131  if (NeedNegation) // This technically increases instruction count.
4132  Res = Builder.CreateNot(Res, "mul.not.ov");
4133 
4134  // If we replaced the mul, erase it. Do this after all uses of Builder,
4135  // as the mul is used as insertion point.
4136  if (MulHadOtherUses)
4137  eraseInstFromFunction(*Mul);
4138 
4139  return Res;
4140 }
4141 
4143  CmpInst::Predicate Pred;
4144  Value *X;
4145  if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X))))
4146  return nullptr;
4147 
4148  if (ICmpInst::isSigned(Pred))
4149  Pred = ICmpInst::getSwappedPredicate(Pred);
4150  else if (ICmpInst::isUnsigned(Pred))
4151  Pred = ICmpInst::getSignedPredicate(Pred);
4152  // else for equality-comparisons just keep the predicate.
4153 
4154  return ICmpInst::Create(Instruction::ICmp, Pred, X,
4155  Constant::getNullValue(X->getType()), I.getName());
4156 }
4157 
4158 /// Try to fold icmp (binop), X or icmp X, (binop).
4159 /// TODO: A large part of this logic is duplicated in InstSimplify's
4160 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4161 /// duplication.
4163  const SimplifyQuery &SQ) {
4164  const SimplifyQuery Q = SQ.getWithInstruction(&I);
4165  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4166 
4167  // Special logic for binary operators.
4168  BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
4169  BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
4170  if (!BO0 && !BO1)
4171  return nullptr;
4172 
4173  if (Instruction *NewICmp = foldICmpXNegX(I))
4174  return NewICmp;
4175 
4176  const CmpInst::Predicate Pred = I.getPredicate();
4177  Value *X;
4178 
4179  // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
4180  // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
4181  if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
4182  (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4183  return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
4184  // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
4185  if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
4186  (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4187  return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
4188 
4189  {
4190  // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
4191  Constant *C;
4192  if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
4193  m_ImmConstant(C)))) &&
4194  (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
4196  return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
4197  }
4198  // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
4199  if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
4200  m_ImmConstant(C)))) &&
4201  (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
4203  return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
4204  }
4205  }
4206 
4207  {
4208  // Similar to above: an unsigned overflow comparison may use offset + mask:
4209  // ((Op1 + C) & C) u< Op1 --> Op1 != 0
4210  // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
4211  // Op0 u> ((Op0 + C) & C) --> Op0 != 0
4212  // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
4213  BinaryOperator *BO;
4214  const APInt *C;
4215  if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
4216  match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4218  CmpInst::Predicate NewPred =
4220  Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4221  return new ICmpInst(NewPred, Op1, Zero);
4222  }
4223 
4224  if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
4225  match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4227  CmpInst::Predicate NewPred =
4229  Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4230  return new ICmpInst(NewPred, Op0, Zero);
4231  }
4232  }
4233 
4234  bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
4235  if (BO0 && isa<OverflowingBinaryOperator>(BO0))
4236  NoOp0WrapProblem =
4237  ICmpInst::isEquality(Pred) ||
4238  (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
4239  (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
4240  if (BO1 && isa<OverflowingBinaryOperator>(BO1))
4241  NoOp1WrapProblem =
4242  ICmpInst::isEquality(Pred) ||
4243  (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
4244  (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
4245 
4246  // Analyze the case when either Op0 or Op1 is an add instruction.
4247  // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
4248  Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
4249  if (BO0 && BO0->getOpcode() == Instruction::Add) {
4250  A = BO0->getOperand(0);
4251  B = BO0->getOperand(1);
4252  }
4253  if (BO1 && BO1->getOpcode() == Instruction::Add) {
4254  C = BO1->getOperand(0);
4255  D = BO1->getOperand(1);
4256  }
4257 
4258  // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
4259  // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
4260  if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
4261  return new ICmpInst(Pred, A == Op1 ? B : A,
4262  Constant::getNullValue(Op1->getType()));
4263 
4264  // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
4265  // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
4266  if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
4267  return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
4268  C == Op0 ? D : C);
4269 
4270  // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
4271  if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
4272  NoOp1WrapProblem) {
4273  // Determine Y and Z in the form icmp (X+Y), (X+Z).
4274  Value *Y, *Z;
4275  if (A == C) {
4276  // C + B == C + D -> B == D
4277  Y = B;
4278  Z = D;
4279  } else if (A == D) {
4280  // D + B == C + D -> B == C
4281  Y = B;
4282  Z = C;
4283  } else if (B == C) {
4284  // A + C == C + D -> A == D
4285  Y = A;
4286  Z = D;
4287  } else {
4288  assert(B == D);
4289  // A + D == C + D -> A == C
4290  Y = A;
4291  Z = C;
4292  }
4293  return new ICmpInst(Pred, Y, Z);
4294  }
4295 
4296  // icmp slt (A + -1), Op1 -> icmp sle A, Op1
4297  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
4298  match(B, m_AllOnes()))
4299  return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
4300 
4301  // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
4302  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
4303  match(B, m_AllOnes()))
4304  return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
4305 
4306  // icmp sle (A + 1), Op1 -> icmp slt A, Op1
4307  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
4308  return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
4309 
4310  // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
4311  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
4312  return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
4313 
4314  // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
4315  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
4316  match(D, m_AllOnes()))
4317  return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
4318 
4319  // icmp sle Op0, (C + -1) -> icmp slt Op0, C
4320  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
4321  match(D, m_AllOnes()))
4322  return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
4323 
4324  // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
4325  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
4326  return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
4327 
4328  // icmp slt Op0, (C + 1) -> icmp sle Op0, C
4329  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
4330  return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
4331 
4332  // TODO: The subtraction-related identities shown below also hold, but
4333  // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
4334  // wouldn't happen even if they were implemented.
4335  //
4336  // icmp ult (A - 1), Op1 -> icmp ule A, Op1
4337  // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
4338  // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
4339  // icmp ule Op0, (C - 1) -> icmp ult Op0, C
4340 
4341  // icmp ule (A + 1), Op0 -> icmp ult A, Op1
4342  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
4343  return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
4344 
4345  // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
4346  if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
4347  return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
4348 
4349  // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
4350  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
4351  return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
4352 
4353  // icmp ult Op0, (C + 1) -> icmp ule Op0, C
4354  if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
4355  return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
4356 
4357  // if C1 has greater magnitude than C2:
4358  // icmp (A + C1), (C + C2) -> icmp (A + C3), C
4359  // s.t. C3 = C1 - C2
4360  //
4361  // if C2 has greater magnitude than C1:
4362  // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
4363  // s.t. C3 = C2 - C1
4364  if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4365  (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
4366  const APInt *AP1, *AP2;
4367  // TODO: Support non-uniform vectors.
4368  // TODO: Allow undef passthrough if B AND D's element is undef.
4369  if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) &&
4370  AP1->isNegative() == AP2->isNegative()) {
4371  APInt AP1Abs = AP1->abs();
4372  APInt AP2Abs = AP2->abs();
4373  if (AP1Abs.uge(AP2Abs)) {
4374  APInt Diff = *AP1 - *AP2;
4375  bool HasNUW = BO0->hasNoUnsignedWrap() && Diff.ule(*AP1);
4376  bool HasNSW = BO0->hasNoSignedWrap();
4377  Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4378  Value *NewAdd = Builder.CreateAdd(A, C3, "", HasNUW, HasNSW);
4379  return new ICmpInst(Pred, NewAdd, C);
4380  } else {
4381  APInt Diff = *AP2 - *AP1;
4382  bool HasNUW = BO1->hasNoUnsignedWrap() && Diff.ule(*AP2);
4383  bool HasNSW = BO1->hasNoSignedWrap();
4384  Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4385  Value *NewAdd = Builder.CreateAdd(C, C3, "", HasNUW, HasNSW);
4386  return new ICmpInst(Pred, A, NewAdd);
4387  }
4388  }
4389  Constant *Cst1, *Cst2;
4390  if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
4391  ICmpInst::isEquality(Pred)) {
4392  Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
4393  Value *NewAdd = Builder.CreateAdd(C, Diff);
4394  return new ICmpInst(Pred, A, NewAdd);
4395  }
4396  }
4397 
4398  // Analyze the case when either Op0 or Op1 is a sub instruction.
4399  // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
4400  A = nullptr;
4401  B = nullptr;
4402  C = nullptr;
4403  D = nullptr;
4404  if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4405  A = BO0->getOperand(0);
4406  B = BO0->getOperand(1);
4407  }
4408  if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4409  C = BO1->getOperand(0);
4410  D = BO1->getOperand(1);
4411  }
4412 
4413  // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
4414  if (A == Op1 && NoOp0WrapProblem)
4415  return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4416  // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
4417  if (C == Op0 && NoOp1WrapProblem)
4418  return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4419 
4420  // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
4421  // (A - B) u>/u<= A --> B u>/u<= A
4422  if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4423  return new ICmpInst(Pred, B, A);
4424  // C u</u>= (C - D) --> C u</u>= D
4425  if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4426  return new ICmpInst(Pred, C, D);
4427  // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
4428  if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
4429  isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4430  return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
4431  // C u<=/u> (C - D) --> C u</u>= D iff B != 0
4432  if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
4433  isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4434  return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
4435 
4436  // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
4437  if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
4438  return new ICmpInst(Pred, A, C);
4439 
4440  // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
4441  if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
4442  return new ICmpInst(Pred, D, B);
4443 
4444  // icmp (0-X) < cst --> x > -cst
4445  if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4446  Value *X;
4447  if (match(BO0, m_Neg(m_Value(X))))
4448  if (Constant *RHSC = dyn_cast<Constant>(Op1))
4449  if (RHSC->isNotMinSignedValue())
4450  return new ICmpInst(I.getSwappedPredicate(), X,
4451  ConstantExpr::getNeg(RHSC));
4452  }
4453 
4454  {
4455  // Try to remove shared constant multiplier from equality comparison:
4456  // X * C == Y * C (with no overflowing/aliasing) --> X == Y
4457  Value *X, *Y;
4458  const APInt *C;
4459  if (match(Op0, m_Mul(m_Value(X), m_APInt(C))) && *C != 0 &&
4460  match(Op1, m_Mul(m_Value(Y), m_SpecificInt(*C))) && I.isEquality())
4461  if (!C->countTrailingZeros() ||
4462  (BO0 && BO1 && BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap()) ||
4463  (BO0 && BO1 && BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap()))
4464  return new ICmpInst(Pred, X, Y);
4465  }
4466 
4467  BinaryOperator *SRem = nullptr;
4468  // icmp (srem X, Y), Y
4469  if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
4470  SRem = BO0;
4471  // icmp Y, (srem X, Y)
4472  else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4473  Op0 == BO1->getOperand(1))
4474  SRem = BO1;
4475  if (SRem) {
4476  // We don't check hasOneUse to avoid increasing register pressure because
4477  // the value we use is the same value this instruction was already using.
4478  switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4479  default:
4480  break;
4481  case ICmpInst::ICMP_EQ:
4482  return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4483  case ICmpInst::ICMP_NE:
4484  return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4485  case ICmpInst::ICMP_SGT:
4486  case ICmpInst::ICMP_SGE:
4487  return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4489  case ICmpInst::ICMP_SLT:
4490  case ICmpInst::ICMP_SLE:
4491  return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4492  Constant::getNullValue(SRem->getType()));
4493  }
4494  }
4495 
4496  if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
4497  BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
4498  switch (BO0->getOpcode()) {
4499  default:
4500  break;
4501  case Instruction::Add:
4502  case Instruction::Sub:
4503  case Instruction::Xor: {
4504  if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4505  return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4506 
4507  const APInt *C;
4508  if (match(BO0->getOperand(1), m_APInt(C))) {
4509  // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
4510  if (C->isSignMask()) {
4511  ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4512  return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4513  }
4514 
4515  // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
4516  if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
4517  ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4518  NewPred = I.getSwappedPredicate(NewPred);
4519  return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4520  }
4521  }
4522  break;
4523  }
4524  case Instruction::Mul: {
4525  if (!I.isEquality())
4526  break;
4527 
4528  const APInt *C;
4529  if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
4530  !C->isOne()) {
4531  // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
4532  // Mask = -1 >> count-trailing-zeros(C).
4533  if (unsigned TZs = C->countTrailingZeros()) {
4535  BO0->getType(),
4536  APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
4537  Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
4538  Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
4539  return new ICmpInst(Pred, And1, And2);
4540  }
4541  }
4542  break;
4543  }
4544  case Instruction::UDiv:
4545  case Instruction::LShr:
4546  if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
4547  break;
4548  return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4549 
4550  case Instruction::SDiv:
4551  if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
4552  break;
4553  return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4554 
4555  case Instruction::AShr:
4556  if (!BO0->isExact() || !BO1->isExact())
4557  break;
4558  return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4559 
4560  case Instruction::Shl: {
4561  bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4562  bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4563  if (!NUW && !NSW)
4564  break;
4565  if (!NSW && I.isSigned())
4566  break;
4567  return