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"
17 #include "llvm/Analysis/CmpInstAnalysis.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/VectorUtils.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/GetElementPtrTypeIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Support/KnownBits.h"
27 #include "llvm/Transforms/InstCombine/InstCombiner.h"
28
29 using namespace llvm;
30 using namespace PatternMatch;
31
32 #define DEBUG_TYPE "instcombine"
33
34 // How many times is a select replaced by one of its operands?
35 STATISTIC(NumSel, "Number of select opts");
36
37
38 /// Compute Result = In1+In2, returning true if the result overflowed for this
39 /// type.
addWithOverflow(APInt & Result,const APInt & In1,const APInt & In2,bool IsSigned=false)40 static bool addWithOverflow(APInt &Result, const APInt &In1,
41 const APInt &In2, bool IsSigned = false) {
42 bool Overflow;
43 if (IsSigned)
44 Result = In1.sadd_ov(In2, Overflow);
45 else
46 Result = In1.uadd_ov(In2, Overflow);
47
48 return Overflow;
49 }
50
51 /// Compute Result = In1-In2, returning true if the result overflowed for this
52 /// type.
subWithOverflow(APInt & Result,const APInt & In1,const APInt & In2,bool IsSigned=false)53 static bool subWithOverflow(APInt &Result, const APInt &In1,
54 const APInt &In2, bool IsSigned = false) {
55 bool Overflow;
56 if (IsSigned)
57 Result = In1.ssub_ov(In2, Overflow);
58 else
59 Result = In1.usub_ov(In2, Overflow);
60
61 return Overflow;
62 }
63
64 /// Given an icmp instruction, return true if any use of this comparison is a
65 /// branch on sign bit comparison.
hasBranchUse(ICmpInst & I)66 static bool hasBranchUse(ICmpInst &I) {
67 for (auto *U : I.users())
68 if (isa<BranchInst>(U))
69 return true;
70 return false;
71 }
72
73 /// Returns true if the exploded icmp can be expressed as a signed comparison
74 /// to zero and updates the predicate accordingly.
75 /// The signedness of the comparison is preserved.
76 /// TODO: Refactor with decomposeBitTestICmp()?
isSignTest(ICmpInst::Predicate & Pred,const APInt & C)77 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
78 if (!ICmpInst::isSigned(Pred))
79 return false;
80
81 if (C.isZero())
82 return ICmpInst::isRelational(Pred);
83
84 if (C.isOne()) {
85 if (Pred == ICmpInst::ICMP_SLT) {
86 Pred = ICmpInst::ICMP_SLE;
87 return true;
88 }
89 } else if (C.isAllOnes()) {
90 if (Pred == ICmpInst::ICMP_SGT) {
91 Pred = ICmpInst::ICMP_SGE;
92 return true;
93 }
94 }
95
96 return false;
97 }
98
99 /// This is called when we see this pattern:
100 /// cmp pred (load (gep GV, ...)), cmpcst
101 /// where GV is a global variable with a constant initializer. Try to simplify
102 /// this into some simple computation that does not need the load. For example
103 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
104 ///
105 /// If AndCst is non-null, then the loaded value is masked with that constant
106 /// before doing the comparison. This handles cases like "A[i]&4 == 0".
foldCmpLoadFromIndexedGlobal(LoadInst * LI,GetElementPtrInst * GEP,GlobalVariable * GV,CmpInst & ICI,ConstantInt * AndCst)107 Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
108 LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
109 ConstantInt *AndCst) {
110 if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
111 GV->getValueType() != GEP->getSourceElementType() ||
112 !GV->isConstant() || !GV->hasDefinitiveInitializer())
113 return nullptr;
114
115 Constant *Init = GV->getInitializer();
116 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
117 return nullptr;
118
119 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
120 // Don't blow up on huge arrays.
121 if (ArrayElementCount > MaxArraySizeForCombine)
122 return nullptr;
123
124 // There are many forms of this optimization we can handle, for now, just do
125 // the simple index into a single-dimensional array.
126 //
127 // Require: GEP GV, 0, i {{, constant indices}}
128 if (GEP->getNumOperands() < 3 ||
129 !isa<ConstantInt>(GEP->getOperand(1)) ||
130 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
131 isa<Constant>(GEP->getOperand(2)))
132 return nullptr;
133
134 // Check that indices after the variable are constants and in-range for the
135 // type they index. Collect the indices. This is typically for arrays of
136 // structs.
137 SmallVector<unsigned, 4> LaterIndices;
138
139 Type *EltTy = Init->getType()->getArrayElementType();
140 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
141 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
142 if (!Idx) return nullptr; // Variable index.
143
144 uint64_t IdxVal = Idx->getZExtValue();
145 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
146
147 if (StructType *STy = dyn_cast<StructType>(EltTy))
148 EltTy = STy->getElementType(IdxVal);
149 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
150 if (IdxVal >= ATy->getNumElements()) return nullptr;
151 EltTy = ATy->getElementType();
152 } else {
153 return nullptr; // Unknown type.
154 }
155
156 LaterIndices.push_back(IdxVal);
157 }
158
159 enum { Overdefined = -3, Undefined = -2 };
160
161 // Variables for our state machines.
162
163 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
164 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
165 // and 87 is the second (and last) index. FirstTrueElement is -2 when
166 // undefined, otherwise set to the first true element. SecondTrueElement is
167 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
168 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
169
170 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
171 // form "i != 47 & i != 87". Same state transitions as for true elements.
172 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
173
174 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
175 /// define a state machine that triggers for ranges of values that the index
176 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
177 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
178 /// index in the range (inclusive). We use -2 for undefined here because we
179 /// use relative comparisons and don't want 0-1 to match -1.
180 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
181
182 // MagicBitvector - This is a magic bitvector where we set a bit if the
183 // comparison is true for element 'i'. If there are 64 elements or less in
184 // the array, this will fully represent all the comparison results.
185 uint64_t MagicBitvector = 0;
186
187 // Scan the array and see if one of our patterns matches.
188 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
189 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
190 Constant *Elt = Init->getAggregateElement(i);
191 if (!Elt) return nullptr;
192
193 // If this is indexing an array of structures, get the structure element.
194 if (!LaterIndices.empty()) {
195 Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
196 if (!Elt)
197 return nullptr;
198 }
199
200 // If the element is masked, handle it.
201 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
202
203 // Find out if the comparison would be true or false for the i'th element.
204 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
205 CompareRHS, DL, &TLI);
206 // If the result is undef for this element, ignore it.
207 if (isa<UndefValue>(C)) {
208 // Extend range state machines to cover this element in case there is an
209 // undef in the middle of the range.
210 if (TrueRangeEnd == (int)i-1)
211 TrueRangeEnd = i;
212 if (FalseRangeEnd == (int)i-1)
213 FalseRangeEnd = i;
214 continue;
215 }
216
217 // If we can't compute the result for any of the elements, we have to give
218 // up evaluating the entire conditional.
219 if (!isa<ConstantInt>(C)) return nullptr;
220
221 // Otherwise, we know if the comparison is true or false for this element,
222 // update our state machines.
223 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
224
225 // State machine for single/double/range index comparison.
226 if (IsTrueForElt) {
227 // Update the TrueElement state machine.
228 if (FirstTrueElement == Undefined)
229 FirstTrueElement = TrueRangeEnd = i; // First true element.
230 else {
231 // Update double-compare state machine.
232 if (SecondTrueElement == Undefined)
233 SecondTrueElement = i;
234 else
235 SecondTrueElement = Overdefined;
236
237 // Update range state machine.
238 if (TrueRangeEnd == (int)i-1)
239 TrueRangeEnd = i;
240 else
241 TrueRangeEnd = Overdefined;
242 }
243 } else {
244 // Update the FalseElement state machine.
245 if (FirstFalseElement == Undefined)
246 FirstFalseElement = FalseRangeEnd = i; // First false element.
247 else {
248 // Update double-compare state machine.
249 if (SecondFalseElement == Undefined)
250 SecondFalseElement = i;
251 else
252 SecondFalseElement = Overdefined;
253
254 // Update range state machine.
255 if (FalseRangeEnd == (int)i-1)
256 FalseRangeEnd = i;
257 else
258 FalseRangeEnd = Overdefined;
259 }
260 }
261
262 // If this element is in range, update our magic bitvector.
263 if (i < 64 && IsTrueForElt)
264 MagicBitvector |= 1ULL << i;
265
266 // If all of our states become overdefined, bail out early. Since the
267 // predicate is expensive, only check it every 8 elements. This is only
268 // really useful for really huge arrays.
269 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
270 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
271 FalseRangeEnd == Overdefined)
272 return nullptr;
273 }
274
275 // Now that we've scanned the entire array, emit our new comparison(s). We
276 // order the state machines in complexity of the generated code.
277 Value *Idx = GEP->getOperand(2);
278
279 // If the index is larger than the pointer size of the target, truncate the
280 // index down like the GEP would do implicitly. We don't have to do this for
281 // an inbounds GEP because the index can't be out of range.
282 if (!GEP->isInBounds()) {
283 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
284 unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
285 if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > PtrSize)
286 Idx = Builder.CreateTrunc(Idx, IntPtrTy);
287 }
288
289 // If inbounds keyword is not present, Idx * ElementSize can overflow.
290 // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
291 // Then, there are two possible values for Idx to match offset 0:
292 // 0x00..00, 0x80..00.
293 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
294 // comparison is false if Idx was 0x80..00.
295 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
296 unsigned ElementSize =
297 DL.getTypeAllocSize(Init->getType()->getArrayElementType());
298 auto MaskIdx = [&](Value* Idx){
299 if (!GEP->isInBounds() && countTrailingZeros(ElementSize) != 0) {
300 Value *Mask = ConstantInt::get(Idx->getType(), -1);
301 Mask = Builder.CreateLShr(Mask, countTrailingZeros(ElementSize));
302 Idx = Builder.CreateAnd(Idx, Mask);
303 }
304 return Idx;
305 };
306
307 // If the comparison is only true for one or two elements, emit direct
308 // comparisons.
309 if (SecondTrueElement != Overdefined) {
310 Idx = MaskIdx(Idx);
311 // None true -> false.
312 if (FirstTrueElement == Undefined)
313 return replaceInstUsesWith(ICI, Builder.getFalse());
314
315 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
316
317 // True for one element -> 'i == 47'.
318 if (SecondTrueElement == Undefined)
319 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
320
321 // True for two elements -> 'i == 47 | i == 72'.
322 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
323 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
324 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
325 return BinaryOperator::CreateOr(C1, C2);
326 }
327
328 // If the comparison is only false for one or two elements, emit direct
329 // comparisons.
330 if (SecondFalseElement != Overdefined) {
331 Idx = MaskIdx(Idx);
332 // None false -> true.
333 if (FirstFalseElement == Undefined)
334 return replaceInstUsesWith(ICI, Builder.getTrue());
335
336 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
337
338 // False for one element -> 'i != 47'.
339 if (SecondFalseElement == Undefined)
340 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
341
342 // False for two elements -> 'i != 47 & i != 72'.
343 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
344 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
345 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
346 return BinaryOperator::CreateAnd(C1, C2);
347 }
348
349 // If the comparison can be replaced with a range comparison for the elements
350 // where it is true, emit the range check.
351 if (TrueRangeEnd != Overdefined) {
352 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
353 Idx = MaskIdx(Idx);
354
355 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
356 if (FirstTrueElement) {
357 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
358 Idx = Builder.CreateAdd(Idx, Offs);
359 }
360
361 Value *End = ConstantInt::get(Idx->getType(),
362 TrueRangeEnd-FirstTrueElement+1);
363 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
364 }
365
366 // False range check.
367 if (FalseRangeEnd != Overdefined) {
368 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
369 Idx = MaskIdx(Idx);
370 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
371 if (FirstFalseElement) {
372 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
373 Idx = Builder.CreateAdd(Idx, Offs);
374 }
375
376 Value *End = ConstantInt::get(Idx->getType(),
377 FalseRangeEnd-FirstFalseElement);
378 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
379 }
380
381 // If a magic bitvector captures the entire comparison state
382 // of this load, replace it with computation that does:
383 // ((magic_cst >> i) & 1) != 0
384 {
385 Type *Ty = nullptr;
386
387 // Look for an appropriate type:
388 // - The type of Idx if the magic fits
389 // - The smallest fitting legal type
390 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
391 Ty = Idx->getType();
392 else
393 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
394
395 if (Ty) {
396 Idx = MaskIdx(Idx);
397 Value *V = Builder.CreateIntCast(Idx, Ty, false);
398 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
399 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
400 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
401 }
402 }
403
404 return nullptr;
405 }
406
407 /// Returns true if we can rewrite Start as a GEP with pointer Base
408 /// and some integer offset. The nodes that need to be re-written
409 /// for this transformation will be added to Explored.
canRewriteGEPAsOffset(Type * ElemTy,Value * Start,Value * Base,const DataLayout & DL,SetVector<Value * > & Explored)410 static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
411 const DataLayout &DL,
412 SetVector<Value *> &Explored) {
413 SmallVector<Value *, 16> WorkList(1, Start);
414 Explored.insert(Base);
415
416 // The following traversal gives us an order which can be used
417 // when doing the final transformation. Since in the final
418 // transformation we create the PHI replacement instructions first,
419 // we don't have to get them in any particular order.
420 //
421 // However, for other instructions we will have to traverse the
422 // operands of an instruction first, which means that we have to
423 // do a post-order traversal.
424 while (!WorkList.empty()) {
425 SetVector<PHINode *> PHIs;
426
427 while (!WorkList.empty()) {
428 if (Explored.size() >= 100)
429 return false;
430
431 Value *V = WorkList.back();
432
433 if (Explored.contains(V)) {
434 WorkList.pop_back();
435 continue;
436 }
437
438 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
439 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
440 // We've found some value that we can't explore which is different from
441 // the base. Therefore we can't do this transformation.
442 return false;
443
444 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
445 auto *CI = cast<CastInst>(V);
446 if (!CI->isNoopCast(DL))
447 return false;
448
449 if (!Explored.contains(CI->getOperand(0)))
450 WorkList.push_back(CI->getOperand(0));
451 }
452
453 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
454 // We're limiting the GEP to having one index. This will preserve
455 // the original pointer type. We could handle more cases in the
456 // future.
457 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
458 GEP->getSourceElementType() != ElemTy)
459 return false;
460
461 if (!Explored.contains(GEP->getOperand(0)))
462 WorkList.push_back(GEP->getOperand(0));
463 }
464
465 if (WorkList.back() == V) {
466 WorkList.pop_back();
467 // We've finished visiting this node, mark it as such.
468 Explored.insert(V);
469 }
470
471 if (auto *PN = dyn_cast<PHINode>(V)) {
472 // We cannot transform PHIs on unsplittable basic blocks.
473 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
474 return false;
475 Explored.insert(PN);
476 PHIs.insert(PN);
477 }
478 }
479
480 // Explore the PHI nodes further.
481 for (auto *PN : PHIs)
482 for (Value *Op : PN->incoming_values())
483 if (!Explored.contains(Op))
484 WorkList.push_back(Op);
485 }
486
487 // Make sure that we can do this. Since we can't insert GEPs in a basic
488 // block before a PHI node, we can't easily do this transformation if
489 // we have PHI node users of transformed instructions.
490 for (Value *Val : Explored) {
491 for (Value *Use : Val->uses()) {
492
493 auto *PHI = dyn_cast<PHINode>(Use);
494 auto *Inst = dyn_cast<Instruction>(Val);
495
496 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
497 !Explored.contains(PHI))
498 continue;
499
500 if (PHI->getParent() == Inst->getParent())
501 return false;
502 }
503 }
504 return true;
505 }
506
507 // Sets the appropriate insert point on Builder where we can add
508 // a replacement Instruction for V (if that is possible).
setInsertionPoint(IRBuilder<> & Builder,Value * V,bool Before=true)509 static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
510 bool Before = true) {
511 if (auto *PHI = dyn_cast<PHINode>(V)) {
512 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
513 return;
514 }
515 if (auto *I = dyn_cast<Instruction>(V)) {
516 if (!Before)
517 I = &*std::next(I->getIterator());
518 Builder.SetInsertPoint(I);
519 return;
520 }
521 if (auto *A = dyn_cast<Argument>(V)) {
522 // Set the insertion point in the entry block.
523 BasicBlock &Entry = A->getParent()->getEntryBlock();
524 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
525 return;
526 }
527 // Otherwise, this is a constant and we don't need to set a new
528 // insertion point.
529 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
530 }
531
532 /// Returns a re-written value of Start as an indexed GEP using Base as a
533 /// pointer.
rewriteGEPAsOffset(Type * ElemTy,Value * Start,Value * Base,const DataLayout & DL,SetVector<Value * > & Explored)534 static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
535 const DataLayout &DL,
536 SetVector<Value *> &Explored) {
537 // Perform all the substitutions. This is a bit tricky because we can
538 // have cycles in our use-def chains.
539 // 1. Create the PHI nodes without any incoming values.
540 // 2. Create all the other values.
541 // 3. Add the edges for the PHI nodes.
542 // 4. Emit GEPs to get the original pointers.
543 // 5. Remove the original instructions.
544 Type *IndexType = IntegerType::get(
545 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
546
547 DenseMap<Value *, Value *> NewInsts;
548 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
549
550 // Create the new PHI nodes, without adding any incoming values.
551 for (Value *Val : Explored) {
552 if (Val == Base)
553 continue;
554 // Create empty phi nodes. This avoids cyclic dependencies when creating
555 // the remaining instructions.
556 if (auto *PHI = dyn_cast<PHINode>(Val))
557 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
558 PHI->getName() + ".idx", PHI);
559 }
560 IRBuilder<> Builder(Base->getContext());
561
562 // Create all the other instructions.
563 for (Value *Val : Explored) {
564
565 if (NewInsts.find(Val) != NewInsts.end())
566 continue;
567
568 if (auto *CI = dyn_cast<CastInst>(Val)) {
569 // Don't get rid of the intermediate variable here; the store can grow
570 // the map which will invalidate the reference to the input value.
571 Value *V = NewInsts[CI->getOperand(0)];
572 NewInsts[CI] = V;
573 continue;
574 }
575 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
576 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
577 : GEP->getOperand(1);
578 setInsertionPoint(Builder, GEP);
579 // Indices might need to be sign extended. GEPs will magically do
580 // this, but we need to do it ourselves here.
581 if (Index->getType()->getScalarSizeInBits() !=
582 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
583 Index = Builder.CreateSExtOrTrunc(
584 Index, NewInsts[GEP->getOperand(0)]->getType(),
585 GEP->getOperand(0)->getName() + ".sext");
586 }
587
588 auto *Op = NewInsts[GEP->getOperand(0)];
589 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
590 NewInsts[GEP] = Index;
591 else
592 NewInsts[GEP] = Builder.CreateNSWAdd(
593 Op, Index, GEP->getOperand(0)->getName() + ".add");
594 continue;
595 }
596 if (isa<PHINode>(Val))
597 continue;
598
599 llvm_unreachable("Unexpected instruction type");
600 }
601
602 // Add the incoming values to the PHI nodes.
603 for (Value *Val : Explored) {
604 if (Val == Base)
605 continue;
606 // All the instructions have been created, we can now add edges to the
607 // phi nodes.
608 if (auto *PHI = dyn_cast<PHINode>(Val)) {
609 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
610 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
611 Value *NewIncoming = PHI->getIncomingValue(I);
612
613 if (NewInsts.find(NewIncoming) != NewInsts.end())
614 NewIncoming = NewInsts[NewIncoming];
615
616 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
617 }
618 }
619 }
620
621 PointerType *PtrTy =
622 ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
623 for (Value *Val : Explored) {
624 if (Val == Base)
625 continue;
626
627 // Depending on the type, for external users we have to emit
628 // a GEP or a GEP + ptrtoint.
629 setInsertionPoint(Builder, Val, false);
630
631 // Cast base to the expected type.
632 Value *NewVal = Builder.CreateBitOrPointerCast(
633 Base, PtrTy, Start->getName() + "to.ptr");
634 NewVal = Builder.CreateInBoundsGEP(ElemTy, NewVal, ArrayRef(NewInsts[Val]),
635 Val->getName() + ".ptr");
636 NewVal = Builder.CreateBitOrPointerCast(
637 NewVal, Val->getType(), Val->getName() + ".conv");
638 Val->replaceAllUsesWith(NewVal);
639 }
640
641 return NewInsts[Start];
642 }
643
644 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
645 /// the input Value as a constant indexed GEP. Returns a pair containing
646 /// the GEPs Pointer and Index.
647 static std::pair<Value *, Value *>
getAsConstantIndexedAddress(Type * ElemTy,Value * V,const DataLayout & DL)648 getAsConstantIndexedAddress(Type *ElemTy, Value *V, const DataLayout &DL) {
649 Type *IndexType = IntegerType::get(V->getContext(),
650 DL.getIndexTypeSizeInBits(V->getType()));
651
652 Constant *Index = ConstantInt::getNullValue(IndexType);
653 while (true) {
654 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
655 // We accept only inbouds GEPs here to exclude the possibility of
656 // overflow.
657 if (!GEP->isInBounds())
658 break;
659 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
660 GEP->getSourceElementType() == ElemTy) {
661 V = GEP->getOperand(0);
662 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
663 Index = ConstantExpr::getAdd(
664 Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
665 continue;
666 }
667 break;
668 }
669 if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
670 if (!CI->isNoopCast(DL))
671 break;
672 V = CI->getOperand(0);
673 continue;
674 }
675 if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
676 if (!CI->isNoopCast(DL))
677 break;
678 V = CI->getOperand(0);
679 continue;
680 }
681 break;
682 }
683 return {V, Index};
684 }
685
686 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
687 /// We can look through PHIs, GEPs and casts in order to determine a common base
688 /// between GEPLHS and RHS.
transformToIndexedCompare(GEPOperator * GEPLHS,Value * RHS,ICmpInst::Predicate Cond,const DataLayout & DL)689 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
690 ICmpInst::Predicate Cond,
691 const DataLayout &DL) {
692 // FIXME: Support vector of pointers.
693 if (GEPLHS->getType()->isVectorTy())
694 return nullptr;
695
696 if (!GEPLHS->hasAllConstantIndices())
697 return nullptr;
698
699 Type *ElemTy = GEPLHS->getSourceElementType();
700 Value *PtrBase, *Index;
701 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
702
703 // The set of nodes that will take part in this transformation.
704 SetVector<Value *> Nodes;
705
706 if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
707 return nullptr;
708
709 // We know we can re-write this as
710 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
711 // Since we've only looked through inbouds GEPs we know that we
712 // can't have overflow on either side. We can therefore re-write
713 // this as:
714 // OFFSET1 cmp OFFSET2
715 Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes);
716
717 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
718 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
719 // offset. Since Index is the offset of LHS to the base pointer, we will now
720 // compare the offsets instead of comparing the pointers.
721 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
722 }
723
724 /// Fold comparisons between a GEP instruction and something else. At this point
725 /// we know that the GEP is on the LHS of the comparison.
foldGEPICmp(GEPOperator * GEPLHS,Value * RHS,ICmpInst::Predicate Cond,Instruction & I)726 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
727 ICmpInst::Predicate Cond,
728 Instruction &I) {
729 // Don't transform signed compares of GEPs into index compares. Even if the
730 // GEP is inbounds, the final add of the base pointer can have signed overflow
731 // and would change the result of the icmp.
732 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
733 // the maximum signed value for the pointer type.
734 if (ICmpInst::isSigned(Cond))
735 return nullptr;
736
737 // Look through bitcasts and addrspacecasts. We do not however want to remove
738 // 0 GEPs.
739 if (!isa<GetElementPtrInst>(RHS))
740 RHS = RHS->stripPointerCasts();
741
742 Value *PtrBase = GEPLHS->getOperand(0);
743 if (PtrBase == RHS && GEPLHS->isInBounds()) {
744 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
745 Value *Offset = EmitGEPOffset(GEPLHS);
746 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
747 Constant::getNullValue(Offset->getType()));
748 }
749
750 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
751 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
752 !NullPointerIsDefined(I.getFunction(),
753 RHS->getType()->getPointerAddressSpace())) {
754 // For most address spaces, an allocation can't be placed at null, but null
755 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
756 // the only valid inbounds address derived from null, is null itself.
757 // Thus, we have four cases to consider:
758 // 1) Base == nullptr, Offset == 0 -> inbounds, null
759 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
760 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
761 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
762 //
763 // (Note if we're indexing a type of size 0, that simply collapses into one
764 // of the buckets above.)
765 //
766 // In general, we're allowed to make values less poison (i.e. remove
767 // sources of full UB), so in this case, we just select between the two
768 // non-poison cases (1 and 4 above).
769 //
770 // For vectors, we apply the same reasoning on a per-lane basis.
771 auto *Base = GEPLHS->getPointerOperand();
772 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
773 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
774 Base = Builder.CreateVectorSplat(EC, Base);
775 }
776 return new ICmpInst(Cond, Base,
777 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
778 cast<Constant>(RHS), Base->getType()));
779 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
780 // If the base pointers are different, but the indices are the same, just
781 // compare the base pointer.
782 if (PtrBase != GEPRHS->getOperand(0)) {
783 bool IndicesTheSame =
784 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
785 GEPLHS->getPointerOperand()->getType() ==
786 GEPRHS->getPointerOperand()->getType() &&
787 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
788 if (IndicesTheSame)
789 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
790 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
791 IndicesTheSame = false;
792 break;
793 }
794
795 // If all indices are the same, just compare the base pointers.
796 Type *BaseType = GEPLHS->getOperand(0)->getType();
797 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
798 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
799
800 // If we're comparing GEPs with two base pointers that only differ in type
801 // and both GEPs have only constant indices or just one use, then fold
802 // the compare with the adjusted indices.
803 // FIXME: Support vector of pointers.
804 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
805 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
806 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
807 PtrBase->stripPointerCasts() ==
808 GEPRHS->getOperand(0)->stripPointerCasts() &&
809 !GEPLHS->getType()->isVectorTy()) {
810 Value *LOffset = EmitGEPOffset(GEPLHS);
811 Value *ROffset = EmitGEPOffset(GEPRHS);
812
813 // If we looked through an addrspacecast between different sized address
814 // spaces, the LHS and RHS pointers are different sized
815 // integers. Truncate to the smaller one.
816 Type *LHSIndexTy = LOffset->getType();
817 Type *RHSIndexTy = ROffset->getType();
818 if (LHSIndexTy != RHSIndexTy) {
819 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
820 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
821 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
822 } else
823 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
824 }
825
826 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
827 LOffset, ROffset);
828 return replaceInstUsesWith(I, Cmp);
829 }
830
831 // Otherwise, the base pointers are different and the indices are
832 // different. Try convert this to an indexed compare by looking through
833 // PHIs/casts.
834 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
835 }
836
837 // If one of the GEPs has all zero indices, recurse.
838 // FIXME: Handle vector of pointers.
839 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
840 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
841 ICmpInst::getSwappedPredicate(Cond), I);
842
843 // If the other GEP has all zero indices, recurse.
844 // FIXME: Handle vector of pointers.
845 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
846 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
847
848 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
849 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
850 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
851 // If the GEPs only differ by one index, compare it.
852 unsigned NumDifferences = 0; // Keep track of # differences.
853 unsigned DiffOperand = 0; // The operand that differs.
854 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
855 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
856 Type *LHSType = GEPLHS->getOperand(i)->getType();
857 Type *RHSType = GEPRHS->getOperand(i)->getType();
858 // FIXME: Better support for vector of pointers.
859 if (LHSType->getPrimitiveSizeInBits() !=
860 RHSType->getPrimitiveSizeInBits() ||
861 (GEPLHS->getType()->isVectorTy() &&
862 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
863 // Irreconcilable differences.
864 NumDifferences = 2;
865 break;
866 }
867
868 if (NumDifferences++) break;
869 DiffOperand = i;
870 }
871
872 if (NumDifferences == 0) // SAME GEP?
873 return replaceInstUsesWith(I, // No comparison is needed here.
874 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
875
876 else if (NumDifferences == 1 && GEPsInBounds) {
877 Value *LHSV = GEPLHS->getOperand(DiffOperand);
878 Value *RHSV = GEPRHS->getOperand(DiffOperand);
879 // Make sure we do a signed comparison here.
880 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
881 }
882 }
883
884 // Only lower this if the icmp is the only user of the GEP or if we expect
885 // the result to fold to a constant!
886 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
887 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
888 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
889 Value *L = EmitGEPOffset(GEPLHS);
890 Value *R = EmitGEPOffset(GEPRHS);
891 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
892 }
893 }
894
895 // Try convert this to an indexed compare by looking through PHIs/casts as a
896 // last resort.
897 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
898 }
899
foldAllocaCmp(ICmpInst & ICI,const AllocaInst * Alloca)900 Instruction *InstCombinerImpl::foldAllocaCmp(ICmpInst &ICI,
901 const AllocaInst *Alloca) {
902 assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
903
904 // It would be tempting to fold away comparisons between allocas and any
905 // pointer not based on that alloca (e.g. an argument). However, even
906 // though such pointers cannot alias, they can still compare equal.
907 //
908 // But LLVM doesn't specify where allocas get their memory, so if the alloca
909 // doesn't escape we can argue that it's impossible to guess its value, and we
910 // can therefore act as if any such guesses are wrong.
911 //
912 // The code below checks that the alloca doesn't escape, and that it's only
913 // used in a comparison once (the current instruction). The
914 // single-comparison-use condition ensures that we're trivially folding all
915 // comparisons against the alloca consistently, and avoids the risk of
916 // erroneously folding a comparison of the pointer with itself.
917
918 unsigned MaxIter = 32; // Break cycles and bound to constant-time.
919
920 SmallVector<const Use *, 32> Worklist;
921 for (const Use &U : Alloca->uses()) {
922 if (Worklist.size() >= MaxIter)
923 return nullptr;
924 Worklist.push_back(&U);
925 }
926
927 unsigned NumCmps = 0;
928 while (!Worklist.empty()) {
929 assert(Worklist.size() <= MaxIter);
930 const Use *U = Worklist.pop_back_val();
931 const Value *V = U->getUser();
932 --MaxIter;
933
934 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
935 isa<SelectInst>(V)) {
936 // Track the uses.
937 } else if (isa<LoadInst>(V)) {
938 // Loading from the pointer doesn't escape it.
939 continue;
940 } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
941 // Storing *to* the pointer is fine, but storing the pointer escapes it.
942 if (SI->getValueOperand() == U->get())
943 return nullptr;
944 continue;
945 } else if (isa<ICmpInst>(V)) {
946 if (NumCmps++)
947 return nullptr; // Found more than one cmp.
948 continue;
949 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
950 switch (Intrin->getIntrinsicID()) {
951 // These intrinsics don't escape or compare the pointer. Memset is safe
952 // because we don't allow ptrtoint. Memcpy and memmove are safe because
953 // we don't allow stores, so src cannot point to V.
954 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
955 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
956 continue;
957 default:
958 return nullptr;
959 }
960 } else {
961 return nullptr;
962 }
963 for (const Use &U : V->uses()) {
964 if (Worklist.size() >= MaxIter)
965 return nullptr;
966 Worklist.push_back(&U);
967 }
968 }
969
970 auto *Res = ConstantInt::get(ICI.getType(),
971 !CmpInst::isTrueWhenEqual(ICI.getPredicate()));
972 return replaceInstUsesWith(ICI, Res);
973 }
974
975 /// Fold "icmp pred (X+C), X".
foldICmpAddOpConst(Value * X,const APInt & C,ICmpInst::Predicate Pred)976 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
977 ICmpInst::Predicate Pred) {
978 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
979 // so the values can never be equal. Similarly for all other "or equals"
980 // operators.
981 assert(!!C && "C should not be zero!");
982
983 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
984 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
985 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
986 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
987 Constant *R = ConstantInt::get(X->getType(),
988 APInt::getMaxValue(C.getBitWidth()) - C);
989 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
990 }
991
992 // (X+1) >u X --> X <u (0-1) --> X != 255
993 // (X+2) >u X --> X <u (0-2) --> X <u 254
994 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
995 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
996 return new ICmpInst(ICmpInst::ICMP_ULT, X,
997 ConstantInt::get(X->getType(), -C));
998
999 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
1000
1001 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
1002 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
1003 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
1004 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
1005 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
1006 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
1007 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
1008 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1009 ConstantInt::get(X->getType(), SMax - C));
1010
1011 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
1012 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
1013 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
1014 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
1015 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
1016 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
1017
1018 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
1019 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1020 ConstantInt::get(X->getType(), SMax - (C - 1)));
1021 }
1022
1023 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
1024 /// (icmp eq/ne A, Log2(AP2/AP1)) ->
1025 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
foldICmpShrConstConst(ICmpInst & I,Value * A,const APInt & AP1,const APInt & AP2)1026 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
1027 const APInt &AP1,
1028 const APInt &AP2) {
1029 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1030
1031 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1032 if (I.getPredicate() == I.ICMP_NE)
1033 Pred = CmpInst::getInversePredicate(Pred);
1034 return new ICmpInst(Pred, LHS, RHS);
1035 };
1036
1037 // Don't bother doing any work for cases which InstSimplify handles.
1038 if (AP2.isZero())
1039 return nullptr;
1040
1041 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1042 if (IsAShr) {
1043 if (AP2.isAllOnes())
1044 return nullptr;
1045 if (AP2.isNegative() != AP1.isNegative())
1046 return nullptr;
1047 if (AP2.sgt(AP1))
1048 return nullptr;
1049 }
1050
1051 if (!AP1)
1052 // 'A' must be large enough to shift out the highest set bit.
1053 return getICmp(I.ICMP_UGT, A,
1054 ConstantInt::get(A->getType(), AP2.logBase2()));
1055
1056 if (AP1 == AP2)
1057 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1058
1059 int Shift;
1060 if (IsAShr && AP1.isNegative())
1061 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
1062 else
1063 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
1064
1065 if (Shift > 0) {
1066 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1067 // There are multiple solutions if we are comparing against -1 and the LHS
1068 // of the ashr is not a power of two.
1069 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1070 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1071 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1072 } else if (AP1 == AP2.lshr(Shift)) {
1073 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1074 }
1075 }
1076
1077 // Shifting const2 will never be equal to const1.
1078 // FIXME: This should always be handled by InstSimplify?
1079 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1080 return replaceInstUsesWith(I, TorF);
1081 }
1082
1083 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1084 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
foldICmpShlConstConst(ICmpInst & I,Value * A,const APInt & AP1,const APInt & AP2)1085 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1086 const APInt &AP1,
1087 const APInt &AP2) {
1088 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1089
1090 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1091 if (I.getPredicate() == I.ICMP_NE)
1092 Pred = CmpInst::getInversePredicate(Pred);
1093 return new ICmpInst(Pred, LHS, RHS);
1094 };
1095
1096 // Don't bother doing any work for cases which InstSimplify handles.
1097 if (AP2.isZero())
1098 return nullptr;
1099
1100 unsigned AP2TrailingZeros = AP2.countTrailingZeros();
1101
1102 if (!AP1 && AP2TrailingZeros != 0)
1103 return getICmp(
1104 I.ICMP_UGE, A,
1105 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1106
1107 if (AP1 == AP2)
1108 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1109
1110 // Get the distance between the lowest bits that are set.
1111 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
1112
1113 if (Shift > 0 && AP2.shl(Shift) == AP1)
1114 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1115
1116 // Shifting const2 will never be equal to const1.
1117 // FIXME: This should always be handled by InstSimplify?
1118 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1119 return replaceInstUsesWith(I, TorF);
1120 }
1121
1122 /// The caller has matched a pattern of the form:
1123 /// I = icmp ugt (add (add A, B), CI2), CI1
1124 /// If this is of the form:
1125 /// sum = a + b
1126 /// if (sum+128 >u 255)
1127 /// Then replace it with llvm.sadd.with.overflow.i8.
1128 ///
processUGT_ADDCST_ADD(ICmpInst & I,Value * A,Value * B,ConstantInt * CI2,ConstantInt * CI1,InstCombinerImpl & IC)1129 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1130 ConstantInt *CI2, ConstantInt *CI1,
1131 InstCombinerImpl &IC) {
1132 // The transformation we're trying to do here is to transform this into an
1133 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1134 // with a narrower add, and discard the add-with-constant that is part of the
1135 // range check (if we can't eliminate it, this isn't profitable).
1136
1137 // In order to eliminate the add-with-constant, the compare can be its only
1138 // use.
1139 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1140 if (!AddWithCst->hasOneUse())
1141 return nullptr;
1142
1143 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1144 if (!CI2->getValue().isPowerOf2())
1145 return nullptr;
1146 unsigned NewWidth = CI2->getValue().countTrailingZeros();
1147 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1148 return nullptr;
1149
1150 // The width of the new add formed is 1 more than the bias.
1151 ++NewWidth;
1152
1153 // Check to see that CI1 is an all-ones value with NewWidth bits.
1154 if (CI1->getBitWidth() == NewWidth ||
1155 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1156 return nullptr;
1157
1158 // This is only really a signed overflow check if the inputs have been
1159 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1160 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1161 if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
1162 IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
1163 return nullptr;
1164
1165 // In order to replace the original add with a narrower
1166 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1167 // and truncates that discard the high bits of the add. Verify that this is
1168 // the case.
1169 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1170 for (User *U : OrigAdd->users()) {
1171 if (U == AddWithCst)
1172 continue;
1173
1174 // Only accept truncates for now. We would really like a nice recursive
1175 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1176 // chain to see which bits of a value are actually demanded. If the
1177 // original add had another add which was then immediately truncated, we
1178 // could still do the transformation.
1179 TruncInst *TI = dyn_cast<TruncInst>(U);
1180 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1181 return nullptr;
1182 }
1183
1184 // If the pattern matches, truncate the inputs to the narrower type and
1185 // use the sadd_with_overflow intrinsic to efficiently compute both the
1186 // result and the overflow bit.
1187 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1188 Function *F = Intrinsic::getDeclaration(
1189 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1190
1191 InstCombiner::BuilderTy &Builder = IC.Builder;
1192
1193 // Put the new code above the original add, in case there are any uses of the
1194 // add between the add and the compare.
1195 Builder.SetInsertPoint(OrigAdd);
1196
1197 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1198 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1199 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1200 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1201 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1202
1203 // The inner add was the result of the narrow add, zero extended to the
1204 // wider type. Replace it with the result computed by the intrinsic.
1205 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1206 IC.eraseInstFromFunction(*OrigAdd);
1207
1208 // The original icmp gets replaced with the overflow value.
1209 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1210 }
1211
1212 /// If we have:
1213 /// icmp eq/ne (urem/srem %x, %y), 0
1214 /// iff %y is a power-of-two, we can replace this with a bit test:
1215 /// icmp eq/ne (and %x, (add %y, -1)), 0
foldIRemByPowerOfTwoToBitTest(ICmpInst & I)1216 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1217 // This fold is only valid for equality predicates.
1218 if (!I.isEquality())
1219 return nullptr;
1220 ICmpInst::Predicate Pred;
1221 Value *X, *Y, *Zero;
1222 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1223 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1224 return nullptr;
1225 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
1226 return nullptr;
1227 // This may increase instruction count, we don't enforce that Y is a constant.
1228 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1229 Value *Masked = Builder.CreateAnd(X, Mask);
1230 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1231 }
1232
1233 /// Fold equality-comparison between zero and any (maybe truncated) right-shift
1234 /// by one-less-than-bitwidth into a sign test on the original value.
foldSignBitTest(ICmpInst & I)1235 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1236 Instruction *Val;
1237 ICmpInst::Predicate Pred;
1238 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1239 return nullptr;
1240
1241 Value *X;
1242 Type *XTy;
1243
1244 Constant *C;
1245 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1246 XTy = X->getType();
1247 unsigned XBitWidth = XTy->getScalarSizeInBits();
1248 if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1249 APInt(XBitWidth, XBitWidth - 1))))
1250 return nullptr;
1251 } else if (isa<BinaryOperator>(Val) &&
1252 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1253 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1254 /*AnalyzeForSignBitExtraction=*/true))) {
1255 XTy = X->getType();
1256 } else
1257 return nullptr;
1258
1259 return ICmpInst::Create(Instruction::ICmp,
1260 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1261 : ICmpInst::ICMP_SLT,
1262 X, ConstantInt::getNullValue(XTy));
1263 }
1264
1265 // Handle icmp pred X, 0
foldICmpWithZero(ICmpInst & Cmp)1266 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1267 CmpInst::Predicate Pred = Cmp.getPredicate();
1268 if (!match(Cmp.getOperand(1), m_Zero()))
1269 return nullptr;
1270
1271 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1272 if (Pred == ICmpInst::ICMP_SGT) {
1273 Value *A, *B;
1274 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1275 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
1276 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1277 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
1278 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1279 }
1280 }
1281
1282 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
1283 return New;
1284
1285 // Given:
1286 // icmp eq/ne (urem %x, %y), 0
1287 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1288 // icmp eq/ne %x, 0
1289 Value *X, *Y;
1290 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1291 ICmpInst::isEquality(Pred)) {
1292 KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
1293 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
1294 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1295 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1296 }
1297
1298 return nullptr;
1299 }
1300
1301 /// Fold icmp Pred X, C.
1302 /// TODO: This code structure does not make sense. The saturating add fold
1303 /// should be moved to some other helper and extended as noted below (it is also
1304 /// possible that code has been made unnecessary - do we canonicalize IR to
1305 /// overflow/saturating intrinsics or not?).
foldICmpWithConstant(ICmpInst & Cmp)1306 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1307 // Match the following pattern, which is a common idiom when writing
1308 // overflow-safe integer arithmetic functions. The source performs an addition
1309 // in wider type and explicitly checks for overflow using comparisons against
1310 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1311 //
1312 // TODO: This could probably be generalized to handle other overflow-safe
1313 // operations if we worked out the formulas to compute the appropriate magic
1314 // constants.
1315 //
1316 // sum = a + b
1317 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1318 CmpInst::Predicate Pred = Cmp.getPredicate();
1319 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1320 Value *A, *B;
1321 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1322 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1323 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1324 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1325 return Res;
1326
1327 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1328 Constant *C = dyn_cast<Constant>(Op1);
1329 if (!C)
1330 return nullptr;
1331
1332 if (auto *Phi = dyn_cast<PHINode>(Op0))
1333 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
1334 Type *Ty = Cmp.getType();
1335 Builder.SetInsertPoint(Phi);
1336 PHINode *NewPhi =
1337 Builder.CreatePHI(Ty, Phi->getNumOperands());
1338 for (BasicBlock *Predecessor : predecessors(Phi->getParent())) {
1339 auto *Input =
1340 cast<Constant>(Phi->getIncomingValueForBlock(Predecessor));
1341 auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C);
1342 NewPhi->addIncoming(BoolInput, Predecessor);
1343 }
1344 NewPhi->takeName(&Cmp);
1345 return replaceInstUsesWith(Cmp, NewPhi);
1346 }
1347
1348 return nullptr;
1349 }
1350
1351 /// Canonicalize icmp instructions based on dominating conditions.
foldICmpWithDominatingICmp(ICmpInst & Cmp)1352 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1353 // This is a cheap/incomplete check for dominance - just match a single
1354 // predecessor with a conditional branch.
1355 BasicBlock *CmpBB = Cmp.getParent();
1356 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1357 if (!DomBB)
1358 return nullptr;
1359
1360 Value *DomCond;
1361 BasicBlock *TrueBB, *FalseBB;
1362 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1363 return nullptr;
1364
1365 assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
1366 "Predecessor block does not point to successor?");
1367
1368 // The branch should get simplified. Don't bother simplifying this condition.
1369 if (TrueBB == FalseBB)
1370 return nullptr;
1371
1372 // Try to simplify this compare to T/F based on the dominating condition.
1373 std::optional<bool> Imp =
1374 isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
1375 if (Imp)
1376 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
1377
1378 CmpInst::Predicate Pred = Cmp.getPredicate();
1379 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1380 ICmpInst::Predicate DomPred;
1381 const APInt *C, *DomC;
1382 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
1383 match(Y, m_APInt(C))) {
1384 // We have 2 compares of a variable with constants. Calculate the constant
1385 // ranges of those compares to see if we can transform the 2nd compare:
1386 // DomBB:
1387 // DomCond = icmp DomPred X, DomC
1388 // br DomCond, CmpBB, FalseBB
1389 // CmpBB:
1390 // Cmp = icmp Pred X, C
1391 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);
1392 ConstantRange DominatingCR =
1393 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
1394 : ConstantRange::makeExactICmpRegion(
1395 CmpInst::getInversePredicate(DomPred), *DomC);
1396 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1397 ConstantRange Difference = DominatingCR.difference(CR);
1398 if (Intersection.isEmptySet())
1399 return replaceInstUsesWith(Cmp, Builder.getFalse());
1400 if (Difference.isEmptySet())
1401 return replaceInstUsesWith(Cmp, Builder.getTrue());
1402
1403 // Canonicalizing a sign bit comparison that gets used in a branch,
1404 // pessimizes codegen by generating branch on zero instruction instead
1405 // of a test and branch. So we avoid canonicalizing in such situations
1406 // because test and branch instruction has better branch displacement
1407 // than compare and branch instruction.
1408 bool UnusedBit;
1409 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1410 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1411 return nullptr;
1412
1413 // Avoid an infinite loop with min/max canonicalization.
1414 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1415 if (Cmp.hasOneUse() &&
1416 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1417 return nullptr;
1418
1419 if (const APInt *EqC = Intersection.getSingleElement())
1420 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1421 if (const APInt *NeC = Difference.getSingleElement())
1422 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1423 }
1424
1425 return nullptr;
1426 }
1427
1428 /// Fold icmp (trunc X), C.
foldICmpTruncConstant(ICmpInst & Cmp,TruncInst * Trunc,const APInt & C)1429 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1430 TruncInst *Trunc,
1431 const APInt &C) {
1432 ICmpInst::Predicate Pred = Cmp.getPredicate();
1433 Value *X = Trunc->getOperand(0);
1434 if (C.isOne() && C.getBitWidth() > 1) {
1435 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1436 Value *V = nullptr;
1437 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1438 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1439 ConstantInt::get(V->getType(), 1));
1440 }
1441
1442 Type *SrcTy = X->getType();
1443 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1444 SrcBits = SrcTy->getScalarSizeInBits();
1445
1446 // TODO: Handle any shifted constant by subtracting trailing zeros.
1447 // TODO: Handle non-equality predicates.
1448 Value *Y;
1449 if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
1450 // (trunc (1 << Y) to iN) == 0 --> Y u>= N
1451 // (trunc (1 << Y) to iN) != 0 --> Y u< N
1452 if (C.isZero()) {
1453 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1454 return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
1455 }
1456 // (trunc (1 << Y) to iN) == 2**C --> Y == C
1457 // (trunc (1 << Y) to iN) != 2**C --> Y != C
1458 if (C.isPowerOf2())
1459 return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
1460 }
1461
1462 if (Cmp.isEquality() && Trunc->hasOneUse()) {
1463 // Canonicalize to a mask and wider compare if the wide type is suitable:
1464 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1465 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1466 Constant *Mask =
1467 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1468 Value *And = Builder.CreateAnd(X, Mask);
1469 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1470 return new ICmpInst(Pred, And, WideC);
1471 }
1472
1473 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1474 // of the high bits truncated out of x are known.
1475 KnownBits Known = computeKnownBits(X, 0, &Cmp);
1476
1477 // If all the high bits are known, we can do this xform.
1478 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
1479 // Pull in the high bits from known-ones set.
1480 APInt NewRHS = C.zext(SrcBits);
1481 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1482 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1483 }
1484 }
1485
1486 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1487 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1488 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1489 Value *ShOp;
1490 const APInt *ShAmtC;
1491 bool TrueIfSigned;
1492 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1493 match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
1494 DstBits == SrcBits - ShAmtC->getZExtValue()) {
1495 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1496 ConstantInt::getNullValue(SrcTy))
1497 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1498 ConstantInt::getAllOnesValue(SrcTy));
1499 }
1500
1501 return nullptr;
1502 }
1503
1504 /// Fold icmp (xor X, Y), C.
foldICmpXorConstant(ICmpInst & Cmp,BinaryOperator * Xor,const APInt & C)1505 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1506 BinaryOperator *Xor,
1507 const APInt &C) {
1508 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1509 return I;
1510
1511 Value *X = Xor->getOperand(0);
1512 Value *Y = Xor->getOperand(1);
1513 const APInt *XorC;
1514 if (!match(Y, m_APInt(XorC)))
1515 return nullptr;
1516
1517 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1518 // fold the xor.
1519 ICmpInst::Predicate Pred = Cmp.getPredicate();
1520 bool TrueIfSigned = false;
1521 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1522
1523 // If the sign bit of the XorCst is not set, there is no change to
1524 // the operation, just stop using the Xor.
1525 if (!XorC->isNegative())
1526 return replaceOperand(Cmp, 0, X);
1527
1528 // Emit the opposite comparison.
1529 if (TrueIfSigned)
1530 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1531 ConstantInt::getAllOnesValue(X->getType()));
1532 else
1533 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1534 ConstantInt::getNullValue(X->getType()));
1535 }
1536
1537 if (Xor->hasOneUse()) {
1538 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1539 if (!Cmp.isEquality() && XorC->isSignMask()) {
1540 Pred = Cmp.getFlippedSignednessPredicate();
1541 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1542 }
1543
1544 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1545 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1546 Pred = Cmp.getFlippedSignednessPredicate();
1547 Pred = Cmp.getSwappedPredicate(Pred);
1548 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1549 }
1550 }
1551
1552 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1553 if (Pred == ICmpInst::ICMP_UGT) {
1554 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1555 if (*XorC == ~C && (C + 1).isPowerOf2())
1556 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1557 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1558 if (*XorC == C && (C + 1).isPowerOf2())
1559 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1560 }
1561 if (Pred == ICmpInst::ICMP_ULT) {
1562 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1563 if (*XorC == -C && C.isPowerOf2())
1564 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1565 ConstantInt::get(X->getType(), ~C));
1566 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1567 if (*XorC == C && (-C).isPowerOf2())
1568 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1569 ConstantInt::get(X->getType(), ~C));
1570 }
1571 return nullptr;
1572 }
1573
1574 /// For power-of-2 C:
1575 /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1576 /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
foldICmpXorShiftConst(ICmpInst & Cmp,BinaryOperator * Xor,const APInt & C)1577 Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1578 BinaryOperator *Xor,
1579 const APInt &C) {
1580 CmpInst::Predicate Pred = Cmp.getPredicate();
1581 APInt PowerOf2;
1582 if (Pred == ICmpInst::ICMP_ULT)
1583 PowerOf2 = C;
1584 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1585 PowerOf2 = C + 1;
1586 else
1587 return nullptr;
1588 if (!PowerOf2.isPowerOf2())
1589 return nullptr;
1590 Value *X;
1591 const APInt *ShiftC;
1592 if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
1593 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1594 return nullptr;
1595 uint64_t Shift = ShiftC->getLimitedValue();
1596 Type *XType = X->getType();
1597 if (Shift == 0 || PowerOf2.isMinSignedValue())
1598 return nullptr;
1599 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1600 APInt Bound =
1601 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1602 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1603 }
1604
1605 /// Fold icmp (and (sh X, Y), C2), C1.
foldICmpAndShift(ICmpInst & Cmp,BinaryOperator * And,const APInt & C1,const APInt & C2)1606 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1607 BinaryOperator *And,
1608 const APInt &C1,
1609 const APInt &C2) {
1610 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1611 if (!Shift || !Shift->isShift())
1612 return nullptr;
1613
1614 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1615 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1616 // code produced by the clang front-end, for bitfield access.
1617 // This seemingly simple opportunity to fold away a shift turns out to be
1618 // rather complicated. See PR17827 for details.
1619 unsigned ShiftOpcode = Shift->getOpcode();
1620 bool IsShl = ShiftOpcode == Instruction::Shl;
1621 const APInt *C3;
1622 if (match(Shift->getOperand(1), m_APInt(C3))) {
1623 APInt NewAndCst, NewCmpCst;
1624 bool AnyCmpCstBitsShiftedOut;
1625 if (ShiftOpcode == Instruction::Shl) {
1626 // For a left shift, we can fold if the comparison is not signed. We can
1627 // also fold a signed comparison if the mask value and comparison value
1628 // are not negative. These constraints may not be obvious, but we can
1629 // prove that they are correct using an SMT solver.
1630 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1631 return nullptr;
1632
1633 NewCmpCst = C1.lshr(*C3);
1634 NewAndCst = C2.lshr(*C3);
1635 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1636 } else if (ShiftOpcode == Instruction::LShr) {
1637 // For a logical right shift, we can fold if the comparison is not signed.
1638 // We can also fold a signed comparison if the shifted mask value and the
1639 // shifted comparison value are not negative. These constraints may not be
1640 // obvious, but we can prove that they are correct using an SMT solver.
1641 NewCmpCst = C1.shl(*C3);
1642 NewAndCst = C2.shl(*C3);
1643 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1644 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1645 return nullptr;
1646 } else {
1647 // For an arithmetic shift, check that both constants don't use (in a
1648 // signed sense) the top bits being shifted out.
1649 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1650 NewCmpCst = C1.shl(*C3);
1651 NewAndCst = C2.shl(*C3);
1652 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1653 if (NewAndCst.ashr(*C3) != C2)
1654 return nullptr;
1655 }
1656
1657 if (AnyCmpCstBitsShiftedOut) {
1658 // If we shifted bits out, the fold is not going to work out. As a
1659 // special case, check to see if this means that the result is always
1660 // true or false now.
1661 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1662 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1663 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1664 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1665 } else {
1666 Value *NewAnd = Builder.CreateAnd(
1667 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1668 return new ICmpInst(Cmp.getPredicate(),
1669 NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
1670 }
1671 }
1672
1673 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1674 // preferable because it allows the C2 << Y expression to be hoisted out of a
1675 // loop if Y is invariant and X is not.
1676 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1677 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
1678 // Compute C2 << Y.
1679 Value *NewShift =
1680 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1681 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1682
1683 // Compute X & (C2 << Y).
1684 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1685 return replaceOperand(Cmp, 0, NewAnd);
1686 }
1687
1688 return nullptr;
1689 }
1690
1691 /// Fold icmp (and X, C2), C1.
foldICmpAndConstConst(ICmpInst & Cmp,BinaryOperator * And,const APInt & C1)1692 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1693 BinaryOperator *And,
1694 const APInt &C1) {
1695 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1696
1697 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
1698 // TODO: We canonicalize to the longer form for scalars because we have
1699 // better analysis/folds for icmp, and codegen may be better with icmp.
1700 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
1701 match(And->getOperand(1), m_One()))
1702 return new TruncInst(And->getOperand(0), Cmp.getType());
1703
1704 const APInt *C2;
1705 Value *X;
1706 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1707 return nullptr;
1708
1709 // Don't perform the following transforms if the AND has multiple uses
1710 if (!And->hasOneUse())
1711 return nullptr;
1712
1713 if (Cmp.isEquality() && C1.isZero()) {
1714 // Restrict this fold to single-use 'and' (PR10267).
1715 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1716 if (C2->isSignMask()) {
1717 Constant *Zero = Constant::getNullValue(X->getType());
1718 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1719 return new ICmpInst(NewPred, X, Zero);
1720 }
1721
1722 APInt NewC2 = *C2;
1723 KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
1724 // Set high zeros of C2 to allow matching negated power-of-2.
1725 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1726 Know.countMinLeadingZeros());
1727
1728 // Restrict this fold only for single-use 'and' (PR10267).
1729 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1730 if (NewC2.isNegatedPowerOf2()) {
1731 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1732 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1733 return new ICmpInst(NewPred, X, NegBOC);
1734 }
1735 }
1736
1737 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1738 // the input width without changing the value produced, eliminate the cast:
1739 //
1740 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1741 //
1742 // We can do this transformation if the constants do not have their sign bits
1743 // set or if it is an equality comparison. Extending a relational comparison
1744 // when we're checking the sign bit would not work.
1745 Value *W;
1746 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1747 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1748 // TODO: Is this a good transform for vectors? Wider types may reduce
1749 // throughput. Should this transform be limited (even for scalars) by using
1750 // shouldChangeType()?
1751 if (!Cmp.getType()->isVectorTy()) {
1752 Type *WideType = W->getType();
1753 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1754 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1755 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1756 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1757 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1758 }
1759 }
1760
1761 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1762 return I;
1763
1764 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1765 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1766 //
1767 // iff pred isn't signed
1768 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1769 match(And->getOperand(1), m_One())) {
1770 Constant *One = cast<Constant>(And->getOperand(1));
1771 Value *Or = And->getOperand(0);
1772 Value *A, *B, *LShr;
1773 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1774 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1775 unsigned UsesRemoved = 0;
1776 if (And->hasOneUse())
1777 ++UsesRemoved;
1778 if (Or->hasOneUse())
1779 ++UsesRemoved;
1780 if (LShr->hasOneUse())
1781 ++UsesRemoved;
1782
1783 // Compute A & ((1 << B) | 1)
1784 Value *NewOr = nullptr;
1785 if (auto *C = dyn_cast<Constant>(B)) {
1786 if (UsesRemoved >= 1)
1787 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
1788 } else {
1789 if (UsesRemoved >= 3)
1790 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1791 /*HasNUW=*/true),
1792 One, Or->getName());
1793 }
1794 if (NewOr) {
1795 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1796 return replaceOperand(Cmp, 0, NewAnd);
1797 }
1798 }
1799 }
1800
1801 return nullptr;
1802 }
1803
1804 /// Fold icmp (and X, Y), C.
foldICmpAndConstant(ICmpInst & Cmp,BinaryOperator * And,const APInt & C)1805 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1806 BinaryOperator *And,
1807 const APInt &C) {
1808 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1809 return I;
1810
1811 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1812 bool TrueIfNeg;
1813 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1814 // ((X - 1) & ~X) < 0 --> X == 0
1815 // ((X - 1) & ~X) >= 0 --> X != 0
1816 Value *X;
1817 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1818 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1819 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1820 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1821 }
1822 }
1823
1824 // TODO: These all require that Y is constant too, so refactor with the above.
1825
1826 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1827 Value *X = And->getOperand(0);
1828 Value *Y = And->getOperand(1);
1829 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1830 if (auto *LI = dyn_cast<LoadInst>(X))
1831 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1832 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
1833 if (Instruction *Res =
1834 foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
1835 return Res;
1836
1837 if (!Cmp.isEquality())
1838 return nullptr;
1839
1840 // X & -C == -C -> X > u ~C
1841 // X & -C != -C -> X <= u ~C
1842 // iff C is a power of 2
1843 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1844 auto NewPred =
1845 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1846 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1847 }
1848
1849 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1850 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1851 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1852 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1853 if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&
1854 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1855 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1856 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1857 Value *And = Builder.CreateAnd(TruncY, X);
1858 return BinaryOperator::CreateNot(And);
1859 }
1860 return BinaryOperator::CreateAnd(TruncY, X);
1861 }
1862
1863 return nullptr;
1864 }
1865
1866 /// Fold icmp (or X, Y), C.
foldICmpOrConstant(ICmpInst & Cmp,BinaryOperator * Or,const APInt & C)1867 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
1868 BinaryOperator *Or,
1869 const APInt &C) {
1870 ICmpInst::Predicate Pred = Cmp.getPredicate();
1871 if (C.isOne()) {
1872 // icmp slt signum(V) 1 --> icmp slt V, 1
1873 Value *V = nullptr;
1874 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
1875 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1876 ConstantInt::get(V->getType(), 1));
1877 }
1878
1879 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
1880 const APInt *MaskC;
1881 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
1882 if (*MaskC == C && (C + 1).isPowerOf2()) {
1883 // X | C == C --> X <=u C
1884 // X | C != C --> X >u C
1885 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
1886 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
1887 return new ICmpInst(Pred, OrOp0, OrOp1);
1888 }
1889
1890 // More general: canonicalize 'equality with set bits mask' to
1891 // 'equality with clear bits mask'.
1892 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
1893 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
1894 if (Or->hasOneUse()) {
1895 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
1896 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
1897 return new ICmpInst(Pred, And, NewC);
1898 }
1899 }
1900
1901 // (X | (X-1)) s< 0 --> X s< 1
1902 // (X | (X-1)) s> -1 --> X s> 0
1903 Value *X;
1904 bool TrueIfSigned;
1905 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1906 match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {
1907 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
1908 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
1909 return new ICmpInst(NewPred, X, NewC);
1910 }
1911
1912 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
1913 return nullptr;
1914
1915 Value *P, *Q;
1916 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
1917 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
1918 // -> and (icmp eq P, null), (icmp eq Q, null).
1919 Value *CmpP =
1920 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
1921 Value *CmpQ =
1922 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
1923 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1924 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
1925 }
1926
1927 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
1928 // a shorter form that has more potential to be folded even further.
1929 Value *X1, *X2, *X3, *X4;
1930 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
1931 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
1932 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
1933 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
1934 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
1935 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
1936 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1937 return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
1938 }
1939
1940 return nullptr;
1941 }
1942
1943 /// Fold icmp (mul X, Y), C.
foldICmpMulConstant(ICmpInst & Cmp,BinaryOperator * Mul,const APInt & C)1944 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
1945 BinaryOperator *Mul,
1946 const APInt &C) {
1947 ICmpInst::Predicate Pred = Cmp.getPredicate();
1948 Type *MulTy = Mul->getType();
1949 Value *X = Mul->getOperand(0);
1950
1951 // If there's no overflow:
1952 // X * X == 0 --> X == 0
1953 // X * X != 0 --> X != 0
1954 if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
1955 (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
1956 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
1957
1958 const APInt *MulC;
1959 if (!match(Mul->getOperand(1), m_APInt(MulC)))
1960 return nullptr;
1961
1962 // If this is a test of the sign bit and the multiply is sign-preserving with
1963 // a constant operand, use the multiply LHS operand instead:
1964 // (X * +MulC) < 0 --> X < 0
1965 // (X * -MulC) < 0 --> X > 0
1966 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
1967 if (MulC->isNegative())
1968 Pred = ICmpInst::getSwappedPredicate(Pred);
1969 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
1970 }
1971
1972 if (MulC->isZero() || (!Mul->hasNoSignedWrap() && !Mul->hasNoUnsignedWrap()))
1973 return nullptr;
1974
1975 // If the multiply does not wrap, try to divide the compare constant by the
1976 // multiplication factor.
1977 if (Cmp.isEquality()) {
1978 // (mul nsw X, MulC) == C --> X == C /s MulC
1979 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
1980 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
1981 return new ICmpInst(Pred, X, NewC);
1982 }
1983 // (mul nuw X, MulC) == C --> X == C /u MulC
1984 if (Mul->hasNoUnsignedWrap() && C.urem(*MulC).isZero()) {
1985 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
1986 return new ICmpInst(Pred, X, NewC);
1987 }
1988 }
1989
1990 // With a matching no-overflow guarantee, fold the constants:
1991 // (X * MulC) < C --> X < (C / MulC)
1992 // (X * MulC) > C --> X > (C / MulC)
1993 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
1994 Constant *NewC = nullptr;
1995 if (Mul->hasNoSignedWrap()) {
1996 // MININT / -1 --> overflow.
1997 if (C.isMinSignedValue() && MulC->isAllOnes())
1998 return nullptr;
1999 if (MulC->isNegative())
2000 Pred = ICmpInst::getSwappedPredicate(Pred);
2001
2002 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE)
2003 NewC = ConstantInt::get(
2004 MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
2005 if (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT)
2006 NewC = ConstantInt::get(
2007 MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));
2008 } else {
2009 assert(Mul->hasNoUnsignedWrap() && "Expected mul nuw");
2010 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)
2011 NewC = ConstantInt::get(
2012 MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
2013 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)
2014 NewC = ConstantInt::get(
2015 MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));
2016 }
2017
2018 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2019 }
2020
2021 /// Fold icmp (shl 1, Y), C.
foldICmpShlOne(ICmpInst & Cmp,Instruction * Shl,const APInt & C)2022 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
2023 const APInt &C) {
2024 Value *Y;
2025 if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
2026 return nullptr;
2027
2028 Type *ShiftType = Shl->getType();
2029 unsigned TypeBits = C.getBitWidth();
2030 bool CIsPowerOf2 = C.isPowerOf2();
2031 ICmpInst::Predicate Pred = Cmp.getPredicate();
2032 if (Cmp.isUnsigned()) {
2033 // (1 << Y) pred C -> Y pred Log2(C)
2034 if (!CIsPowerOf2) {
2035 // (1 << Y) < 30 -> Y <= 4
2036 // (1 << Y) <= 30 -> Y <= 4
2037 // (1 << Y) >= 30 -> Y > 4
2038 // (1 << Y) > 30 -> Y > 4
2039 if (Pred == ICmpInst::ICMP_ULT)
2040 Pred = ICmpInst::ICMP_ULE;
2041 else if (Pred == ICmpInst::ICMP_UGE)
2042 Pred = ICmpInst::ICMP_UGT;
2043 }
2044
2045 unsigned CLog2 = C.logBase2();
2046 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2047 } else if (Cmp.isSigned()) {
2048 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2049 // (1 << Y) > 0 -> Y != 31
2050 // (1 << Y) > C -> Y != 31 if C is negative.
2051 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2052 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2053
2054 // (1 << Y) < 0 -> Y == 31
2055 // (1 << Y) < 1 -> Y == 31
2056 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2057 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2058 if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
2059 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2060 }
2061
2062 return nullptr;
2063 }
2064
2065 /// Fold icmp (shl X, Y), C.
foldICmpShlConstant(ICmpInst & Cmp,BinaryOperator * Shl,const APInt & C)2066 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2067 BinaryOperator *Shl,
2068 const APInt &C) {
2069 const APInt *ShiftVal;
2070 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2071 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2072
2073 const APInt *ShiftAmt;
2074 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2075 return foldICmpShlOne(Cmp, Shl, C);
2076
2077 // Check that the shift amount is in range. If not, don't perform undefined
2078 // shifts. When the shift is visited, it will be simplified.
2079 unsigned TypeBits = C.getBitWidth();
2080 if (ShiftAmt->uge(TypeBits))
2081 return nullptr;
2082
2083 ICmpInst::Predicate Pred = Cmp.getPredicate();
2084 Value *X = Shl->getOperand(0);
2085 Type *ShType = Shl->getType();
2086
2087 // NSW guarantees that we are only shifting out sign bits from the high bits,
2088 // so we can ASHR the compare constant without needing a mask and eliminate
2089 // the shift.
2090 if (Shl->hasNoSignedWrap()) {
2091 if (Pred == ICmpInst::ICMP_SGT) {
2092 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2093 APInt ShiftedC = C.ashr(*ShiftAmt);
2094 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2095 }
2096 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2097 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2098 APInt ShiftedC = C.ashr(*ShiftAmt);
2099 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2100 }
2101 if (Pred == ICmpInst::ICMP_SLT) {
2102 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2103 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2104 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2105 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2106 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2107 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2108 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2109 }
2110 // If this is a signed comparison to 0 and the shift is sign preserving,
2111 // use the shift LHS operand instead; isSignTest may change 'Pred', so only
2112 // do that if we're sure to not continue on in this function.
2113 if (isSignTest(Pred, C))
2114 return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
2115 }
2116
2117 // NUW guarantees that we are only shifting out zero bits from the high bits,
2118 // so we can LSHR the compare constant without needing a mask and eliminate
2119 // the shift.
2120 if (Shl->hasNoUnsignedWrap()) {
2121 if (Pred == ICmpInst::ICMP_UGT) {
2122 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2123 APInt ShiftedC = C.lshr(*ShiftAmt);
2124 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2125 }
2126 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2127 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2128 APInt ShiftedC = C.lshr(*ShiftAmt);
2129 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2130 }
2131 if (Pred == ICmpInst::ICMP_ULT) {
2132 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2133 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2134 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2135 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2136 assert(C.ugt(0) && "ult 0 should have been eliminated");
2137 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2138 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2139 }
2140 }
2141
2142 if (Cmp.isEquality() && Shl->hasOneUse()) {
2143 // Strength-reduce the shift into an 'and'.
2144 Constant *Mask = ConstantInt::get(
2145 ShType,
2146 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2147 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2148 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2149 return new ICmpInst(Pred, And, LShrC);
2150 }
2151
2152 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2153 bool TrueIfSigned = false;
2154 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2155 // (X << 31) <s 0 --> (X & 1) != 0
2156 Constant *Mask = ConstantInt::get(
2157 ShType,
2158 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2159 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2160 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2161 And, Constant::getNullValue(ShType));
2162 }
2163
2164 // Simplify 'shl' inequality test into 'and' equality test.
2165 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2166 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2167 if ((C + 1).isPowerOf2() &&
2168 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2169 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2170 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2171 : ICmpInst::ICMP_NE,
2172 And, Constant::getNullValue(ShType));
2173 }
2174 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2175 if (C.isPowerOf2() &&
2176 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2177 Value *And =
2178 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2179 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2180 : ICmpInst::ICMP_NE,
2181 And, Constant::getNullValue(ShType));
2182 }
2183 }
2184
2185 // Transform (icmp pred iM (shl iM %v, N), C)
2186 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2187 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2188 // This enables us to get rid of the shift in favor of a trunc that may be
2189 // free on the target. It has the additional benefit of comparing to a
2190 // smaller constant that may be more target-friendly.
2191 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2192 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
2193 DL.isLegalInteger(TypeBits - Amt)) {
2194 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
2195 if (auto *ShVTy = dyn_cast<VectorType>(ShType))
2196 TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
2197 Constant *NewC =
2198 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2199 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
2200 }
2201
2202 return nullptr;
2203 }
2204
2205 /// Fold icmp ({al}shr X, Y), C.
foldICmpShrConstant(ICmpInst & Cmp,BinaryOperator * Shr,const APInt & C)2206 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2207 BinaryOperator *Shr,
2208 const APInt &C) {
2209 // An exact shr only shifts out zero bits, so:
2210 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2211 Value *X = Shr->getOperand(0);
2212 CmpInst::Predicate Pred = Cmp.getPredicate();
2213 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2214 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2215
2216 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2217 const APInt *ShiftValC;
2218 if (match(X, m_APInt(ShiftValC))) {
2219 if (Cmp.isEquality())
2220 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2221
2222 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2223 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2224 bool TrueIfSigned;
2225 if (!IsAShr && ShiftValC->isNegative() &&
2226 isSignBitCheck(Pred, C, TrueIfSigned))
2227 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2228 Shr->getOperand(1),
2229 ConstantInt::getNullValue(X->getType()));
2230
2231 // If the shifted constant is a power-of-2, test the shift amount directly:
2232 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2233 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2234 if (!IsAShr && ShiftValC->isPowerOf2() &&
2235 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2236 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2237 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2238 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2239
2240 unsigned CmpLZ =
2241 IsUGT ? C.countLeadingZeros() : (C - 1).countLeadingZeros();
2242 unsigned ShiftLZ = ShiftValC->countLeadingZeros();
2243 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2244 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2245 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2246 }
2247 }
2248
2249 const APInt *ShiftAmtC;
2250 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2251 return nullptr;
2252
2253 // Check that the shift amount is in range. If not, don't perform undefined
2254 // shifts. When the shift is visited it will be simplified.
2255 unsigned TypeBits = C.getBitWidth();
2256 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2257 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2258 return nullptr;
2259
2260 bool IsExact = Shr->isExact();
2261 Type *ShrTy = Shr->getType();
2262 // TODO: If we could guarantee that InstSimplify would handle all of the
2263 // constant-value-based preconditions in the folds below, then we could assert
2264 // those conditions rather than checking them. This is difficult because of
2265 // undef/poison (PR34838).
2266 if (IsAShr) {
2267 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2268 // When ShAmtC can be shifted losslessly:
2269 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2270 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2271 APInt ShiftedC = C.shl(ShAmtVal);
2272 if (ShiftedC.ashr(ShAmtVal) == C)
2273 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2274 }
2275 if (Pred == CmpInst::ICMP_SGT) {
2276 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2277 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2278 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2279 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2280 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2281 }
2282 if (Pred == CmpInst::ICMP_UGT) {
2283 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2284 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2285 // clause accounts for that pattern.
2286 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2287 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2288 (C + 1).shl(ShAmtVal).isMinSignedValue())
2289 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2290 }
2291
2292 // If the compare constant has significant bits above the lowest sign-bit,
2293 // then convert an unsigned cmp to a test of the sign-bit:
2294 // (ashr X, ShiftC) u> C --> X s< 0
2295 // (ashr X, ShiftC) u< C --> X s> -1
2296 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2297 if (Pred == CmpInst::ICMP_UGT) {
2298 return new ICmpInst(CmpInst::ICMP_SLT, X,
2299 ConstantInt::getNullValue(ShrTy));
2300 }
2301 if (Pred == CmpInst::ICMP_ULT) {
2302 return new ICmpInst(CmpInst::ICMP_SGT, X,
2303 ConstantInt::getAllOnesValue(ShrTy));
2304 }
2305 }
2306 } else {
2307 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2308 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2309 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2310 APInt ShiftedC = C.shl(ShAmtVal);
2311 if (ShiftedC.lshr(ShAmtVal) == C)
2312 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2313 }
2314 if (Pred == CmpInst::ICMP_UGT) {
2315 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2316 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2317 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2318 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2319 }
2320 }
2321
2322 if (!Cmp.isEquality())
2323 return nullptr;
2324
2325 // Handle equality comparisons of shift-by-constant.
2326
2327 // If the comparison constant changes with the shift, the comparison cannot
2328 // succeed (bits of the comparison constant cannot match the shifted value).
2329 // This should be known by InstSimplify and already be folded to true/false.
2330 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2331 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2332 "Expected icmp+shr simplify did not occur.");
2333
2334 // If the bits shifted out are known zero, compare the unshifted value:
2335 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2336 if (Shr->isExact())
2337 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2338
2339 if (C.isZero()) {
2340 // == 0 is u< 1.
2341 if (Pred == CmpInst::ICMP_EQ)
2342 return new ICmpInst(CmpInst::ICMP_ULT, X,
2343 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
2344 else
2345 return new ICmpInst(CmpInst::ICMP_UGT, X,
2346 ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
2347 }
2348
2349 if (Shr->hasOneUse()) {
2350 // Canonicalize the shift into an 'and':
2351 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2352 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2353 Constant *Mask = ConstantInt::get(ShrTy, Val);
2354 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2355 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2356 }
2357
2358 return nullptr;
2359 }
2360
foldICmpSRemConstant(ICmpInst & Cmp,BinaryOperator * SRem,const APInt & C)2361 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2362 BinaryOperator *SRem,
2363 const APInt &C) {
2364 // Match an 'is positive' or 'is negative' comparison of remainder by a
2365 // constant power-of-2 value:
2366 // (X % pow2C) sgt/slt 0
2367 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2368 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2369 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2370 return nullptr;
2371
2372 // TODO: The one-use check is standard because we do not typically want to
2373 // create longer instruction sequences, but this might be a special-case
2374 // because srem is not good for analysis or codegen.
2375 if (!SRem->hasOneUse())
2376 return nullptr;
2377
2378 const APInt *DivisorC;
2379 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2380 return nullptr;
2381
2382 // For cmp_sgt/cmp_slt only zero valued C is handled.
2383 // For cmp_eq/cmp_ne only positive valued C is handled.
2384 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2385 !C.isZero()) ||
2386 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2387 !C.isStrictlyPositive()))
2388 return nullptr;
2389
2390 // Mask off the sign bit and the modulo bits (low-bits).
2391 Type *Ty = SRem->getType();
2392 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2393 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2394 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2395
2396 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2397 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2398
2399 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2400 // bit is set. Example:
2401 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2402 if (Pred == ICmpInst::ICMP_SGT)
2403 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2404
2405 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2406 // bit is set. Example:
2407 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2408 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2409 }
2410
2411 /// Fold icmp (udiv X, Y), C.
foldICmpUDivConstant(ICmpInst & Cmp,BinaryOperator * UDiv,const APInt & C)2412 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2413 BinaryOperator *UDiv,
2414 const APInt &C) {
2415 ICmpInst::Predicate Pred = Cmp.getPredicate();
2416 Value *X = UDiv->getOperand(0);
2417 Value *Y = UDiv->getOperand(1);
2418 Type *Ty = UDiv->getType();
2419
2420 const APInt *C2;
2421 if (!match(X, m_APInt(C2)))
2422 return nullptr;
2423
2424 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2425
2426 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2427 if (Pred == ICmpInst::ICMP_UGT) {
2428 assert(!C.isMaxValue() &&
2429 "icmp ugt X, UINT_MAX should have been simplified already.");
2430 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2431 ConstantInt::get(Ty, C2->udiv(C + 1)));
2432 }
2433
2434 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2435 if (Pred == ICmpInst::ICMP_ULT) {
2436 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2437 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2438 ConstantInt::get(Ty, C2->udiv(C)));
2439 }
2440
2441 return nullptr;
2442 }
2443
2444 /// Fold icmp ({su}div X, Y), C.
foldICmpDivConstant(ICmpInst & Cmp,BinaryOperator * Div,const APInt & C)2445 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2446 BinaryOperator *Div,
2447 const APInt &C) {
2448 ICmpInst::Predicate Pred = Cmp.getPredicate();
2449 Value *X = Div->getOperand(0);
2450 Value *Y = Div->getOperand(1);
2451 Type *Ty = Div->getType();
2452 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2453
2454 // If unsigned division and the compare constant is bigger than
2455 // UMAX/2 (negative), there's only one pair of values that satisfies an
2456 // equality check, so eliminate the division:
2457 // (X u/ Y) == C --> (X == C) && (Y == 1)
2458 // (X u/ Y) != C --> (X != C) || (Y != 1)
2459 // Similarly, if signed division and the compare constant is exactly SMIN:
2460 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2461 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2462 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2463 (!DivIsSigned || C.isMinSignedValue())) {
2464 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2465 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2466 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2467 return BinaryOperator::Create(Logic, XBig, YOne);
2468 }
2469
2470 // Fold: icmp pred ([us]div X, C2), C -> range test
2471 // Fold this div into the comparison, producing a range check.
2472 // Determine, based on the divide type, what the range is being
2473 // checked. If there is an overflow on the low or high side, remember
2474 // it, otherwise compute the range [low, hi) bounding the new value.
2475 // See: InsertRangeTest above for the kinds of replacements possible.
2476 const APInt *C2;
2477 if (!match(Y, m_APInt(C2)))
2478 return nullptr;
2479
2480 // FIXME: If the operand types don't match the type of the divide
2481 // then don't attempt this transform. The code below doesn't have the
2482 // logic to deal with a signed divide and an unsigned compare (and
2483 // vice versa). This is because (x /s C2) <s C produces different
2484 // results than (x /s C2) <u C or (x /u C2) <s C or even
2485 // (x /u C2) <u C. Simply casting the operands and result won't
2486 // work. :( The if statement below tests that condition and bails
2487 // if it finds it.
2488 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
2489 return nullptr;
2490
2491 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2492 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2493 // division-by-constant cases should be present, we can not assert that they
2494 // have happened before we reach this icmp instruction.
2495 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2496 return nullptr;
2497
2498 // Compute Prod = C * C2. We are essentially solving an equation of
2499 // form X / C2 = C. We solve for X by multiplying C2 and C.
2500 // By solving for X, we can turn this into a range check instead of computing
2501 // a divide.
2502 APInt Prod = C * *C2;
2503
2504 // Determine if the product overflows by seeing if the product is not equal to
2505 // the divide. Make sure we do the same kind of divide as in the LHS
2506 // instruction that we're folding.
2507 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2508
2509 // If the division is known to be exact, then there is no remainder from the
2510 // divide, so the covered range size is unit, otherwise it is the divisor.
2511 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2512
2513 // Figure out the interval that is being checked. For example, a comparison
2514 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2515 // Compute this interval based on the constants involved and the signedness of
2516 // the compare/divide. This computes a half-open interval, keeping track of
2517 // whether either value in the interval overflows. After analysis each
2518 // overflow variable is set to 0 if it's corresponding bound variable is valid
2519 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2520 int LoOverflow = 0, HiOverflow = 0;
2521 APInt LoBound, HiBound;
2522
2523 if (!DivIsSigned) { // udiv
2524 // e.g. X/5 op 3 --> [15, 20)
2525 LoBound = Prod;
2526 HiOverflow = LoOverflow = ProdOV;
2527 if (!HiOverflow) {
2528 // If this is not an exact divide, then many values in the range collapse
2529 // to the same result value.
2530 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2531 }
2532 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2533 if (C.isZero()) { // (X / pos) op 0
2534 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2535 LoBound = -(RangeSize - 1);
2536 HiBound = RangeSize;
2537 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2538 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2539 HiOverflow = LoOverflow = ProdOV;
2540 if (!HiOverflow)
2541 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2542 } else { // (X / pos) op neg
2543 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2544 HiBound = Prod + 1;
2545 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2546 if (!LoOverflow) {
2547 APInt DivNeg = -RangeSize;
2548 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2549 }
2550 }
2551 } else if (C2->isNegative()) { // Divisor is < 0.
2552 if (Div->isExact())
2553 RangeSize.negate();
2554 if (C.isZero()) { // (X / neg) op 0
2555 // e.g. X/-5 op 0 --> [-4, 5)
2556 LoBound = RangeSize + 1;
2557 HiBound = -RangeSize;
2558 if (HiBound == *C2) { // -INTMIN = INTMIN
2559 HiOverflow = 1; // [INTMIN+1, overflow)
2560 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2561 }
2562 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2563 // e.g. X/-5 op 3 --> [-19, -14)
2564 HiBound = Prod + 1;
2565 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2566 if (!LoOverflow)
2567 LoOverflow =
2568 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2569 } else { // (X / neg) op neg
2570 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2571 LoOverflow = HiOverflow = ProdOV;
2572 if (!HiOverflow)
2573 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2574 }
2575
2576 // Dividing by a negative swaps the condition. LT <-> GT
2577 Pred = ICmpInst::getSwappedPredicate(Pred);
2578 }
2579
2580 switch (Pred) {
2581 default:
2582 llvm_unreachable("Unhandled icmp predicate!");
2583 case ICmpInst::ICMP_EQ:
2584 if (LoOverflow && HiOverflow)
2585 return replaceInstUsesWith(Cmp, Builder.getFalse());
2586 if (HiOverflow)
2587 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2588 X, ConstantInt::get(Ty, LoBound));
2589 if (LoOverflow)
2590 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2591 X, ConstantInt::get(Ty, HiBound));
2592 return replaceInstUsesWith(
2593 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2594 case ICmpInst::ICMP_NE:
2595 if (LoOverflow && HiOverflow)
2596 return replaceInstUsesWith(Cmp, Builder.getTrue());
2597 if (HiOverflow)
2598 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2599 X, ConstantInt::get(Ty, LoBound));
2600 if (LoOverflow)
2601 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2602 X, ConstantInt::get(Ty, HiBound));
2603 return replaceInstUsesWith(
2604 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2605 case ICmpInst::ICMP_ULT:
2606 case ICmpInst::ICMP_SLT:
2607 if (LoOverflow == +1) // Low bound is greater than input range.
2608 return replaceInstUsesWith(Cmp, Builder.getTrue());
2609 if (LoOverflow == -1) // Low bound is less than input range.
2610 return replaceInstUsesWith(Cmp, Builder.getFalse());
2611 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2612 case ICmpInst::ICMP_UGT:
2613 case ICmpInst::ICMP_SGT:
2614 if (HiOverflow == +1) // High bound greater than input range.
2615 return replaceInstUsesWith(Cmp, Builder.getFalse());
2616 if (HiOverflow == -1) // High bound less than input range.
2617 return replaceInstUsesWith(Cmp, Builder.getTrue());
2618 if (Pred == ICmpInst::ICMP_UGT)
2619 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
2620 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
2621 }
2622
2623 return nullptr;
2624 }
2625
2626 /// Fold icmp (sub X, Y), C.
foldICmpSubConstant(ICmpInst & Cmp,BinaryOperator * Sub,const APInt & C)2627 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
2628 BinaryOperator *Sub,
2629 const APInt &C) {
2630 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
2631 ICmpInst::Predicate Pred = Cmp.getPredicate();
2632 Type *Ty = Sub->getType();
2633
2634 // (SubC - Y) == C) --> Y == (SubC - C)
2635 // (SubC - Y) != C) --> Y != (SubC - C)
2636 Constant *SubC;
2637 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
2638 return new ICmpInst(Pred, Y,
2639 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
2640 }
2641
2642 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
2643 const APInt *C2;
2644 APInt SubResult;
2645 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
2646 bool HasNSW = Sub->hasNoSignedWrap();
2647 bool HasNUW = Sub->hasNoUnsignedWrap();
2648 if (match(X, m_APInt(C2)) &&
2649 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
2650 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
2651 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
2652
2653 // X - Y == 0 --> X == Y.
2654 // X - Y != 0 --> X != Y.
2655 // TODO: We allow this with multiple uses as long as the other uses are not
2656 // in phis. The phi use check is guarding against a codegen regression
2657 // for a loop test. If the backend could undo this (and possibly
2658 // subsequent transforms), we would not need this hack.
2659 if (Cmp.isEquality() && C.isZero() &&
2660 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
2661 return new ICmpInst(Pred, X, Y);
2662
2663 // The following transforms are only worth it if the only user of the subtract
2664 // is the icmp.
2665 // TODO: This is an artificial restriction for all of the transforms below
2666 // that only need a single replacement icmp. Can these use the phi test
2667 // like the transform above here?
2668 if (!Sub->hasOneUse())
2669 return nullptr;
2670
2671 if (Sub->hasNoSignedWrap()) {
2672 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
2673 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
2674 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
2675
2676 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
2677 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
2678 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
2679
2680 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
2681 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
2682 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
2683
2684 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
2685 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
2686 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
2687 }
2688
2689 if (!match(X, m_APInt(C2)))
2690 return nullptr;
2691
2692 // C2 - Y <u C -> (Y | (C - 1)) == C2
2693 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
2694 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
2695 (*C2 & (C - 1)) == (C - 1))
2696 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
2697
2698 // C2 - Y >u C -> (Y | C) != C2
2699 // iff C2 & C == C and C + 1 is a power of 2
2700 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
2701 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
2702
2703 // We have handled special cases that reduce.
2704 // Canonicalize any remaining sub to add as:
2705 // (C2 - Y) > C --> (Y + ~C2) < ~C
2706 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
2707 HasNUW, HasNSW);
2708 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
2709 }
2710
2711 /// Fold icmp (add X, Y), C.
foldICmpAddConstant(ICmpInst & Cmp,BinaryOperator * Add,const APInt & C)2712 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
2713 BinaryOperator *Add,
2714 const APInt &C) {
2715 Value *Y = Add->getOperand(1);
2716 const APInt *C2;
2717 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
2718 return nullptr;
2719
2720 // Fold icmp pred (add X, C2), C.
2721 Value *X = Add->getOperand(0);
2722 Type *Ty = Add->getType();
2723 const CmpInst::Predicate Pred = Cmp.getPredicate();
2724
2725 // If the add does not wrap, we can always adjust the compare by subtracting
2726 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
2727 // are canonicalized to SGT/SLT/UGT/ULT.
2728 if ((Add->hasNoSignedWrap() &&
2729 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
2730 (Add->hasNoUnsignedWrap() &&
2731 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
2732 bool Overflow;
2733 APInt NewC =
2734 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
2735 // If there is overflow, the result must be true or false.
2736 // TODO: Can we assert there is no overflow because InstSimplify always
2737 // handles those cases?
2738 if (!Overflow)
2739 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
2740 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
2741 }
2742
2743 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
2744 const APInt &Upper = CR.getUpper();
2745 const APInt &Lower = CR.getLower();
2746 if (Cmp.isSigned()) {
2747 if (Lower.isSignMask())
2748 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
2749 if (Upper.isSignMask())
2750 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
2751 } else {
2752 if (Lower.isMinValue())
2753 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
2754 if (Upper.isMinValue())
2755 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
2756 }
2757
2758 // This set of folds is intentionally placed after folds that use no-wrapping
2759 // flags because those folds are likely better for later analysis/codegen.
2760 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
2761 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
2762
2763 // Fold compare with offset to opposite sign compare if it eliminates offset:
2764 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
2765 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
2766 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
2767
2768 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
2769 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
2770 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
2771
2772 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
2773 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
2774 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
2775
2776 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
2777 if (Pred == CmpInst::ICMP_SLT && C == *C2)
2778 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
2779
2780 // (X + -1) <u C --> X <=u C (if X is never null)
2781 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
2782 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
2783 if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
2784 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
2785 }
2786
2787 if (!Add->hasOneUse())
2788 return nullptr;
2789
2790 // X+C <u C2 -> (X & -C2) == C
2791 // iff C & (C2-1) == 0
2792 // C2 is a power of 2
2793 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
2794 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
2795 ConstantExpr::getNeg(cast<Constant>(Y)));
2796
2797 // X+C >u C2 -> (X & ~C2) != C
2798 // iff C & C2 == 0
2799 // C2+1 is a power of 2
2800 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
2801 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
2802 ConstantExpr::getNeg(cast<Constant>(Y)));
2803
2804 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
2805 // to the ult form.
2806 // X+C2 >u C -> X+(C2-C-1) <u ~C
2807 if (Pred == ICmpInst::ICMP_UGT)
2808 return new ICmpInst(ICmpInst::ICMP_ULT,
2809 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
2810 ConstantInt::get(Ty, ~C));
2811
2812 return nullptr;
2813 }
2814
matchThreeWayIntCompare(SelectInst * SI,Value * & LHS,Value * & RHS,ConstantInt * & Less,ConstantInt * & Equal,ConstantInt * & Greater)2815 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
2816 Value *&RHS, ConstantInt *&Less,
2817 ConstantInt *&Equal,
2818 ConstantInt *&Greater) {
2819 // TODO: Generalize this to work with other comparison idioms or ensure
2820 // they get canonicalized into this form.
2821
2822 // select i1 (a == b),
2823 // i32 Equal,
2824 // i32 (select i1 (a < b), i32 Less, i32 Greater)
2825 // where Equal, Less and Greater are placeholders for any three constants.
2826 ICmpInst::Predicate PredA;
2827 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
2828 !ICmpInst::isEquality(PredA))
2829 return false;
2830 Value *EqualVal = SI->getTrueValue();
2831 Value *UnequalVal = SI->getFalseValue();
2832 // We still can get non-canonical predicate here, so canonicalize.
2833 if (PredA == ICmpInst::ICMP_NE)
2834 std::swap(EqualVal, UnequalVal);
2835 if (!match(EqualVal, m_ConstantInt(Equal)))
2836 return false;
2837 ICmpInst::Predicate PredB;
2838 Value *LHS2, *RHS2;
2839 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
2840 m_ConstantInt(Less), m_ConstantInt(Greater))))
2841 return false;
2842 // We can get predicate mismatch here, so canonicalize if possible:
2843 // First, ensure that 'LHS' match.
2844 if (LHS2 != LHS) {
2845 // x sgt y <--> y slt x
2846 std::swap(LHS2, RHS2);
2847 PredB = ICmpInst::getSwappedPredicate(PredB);
2848 }
2849 if (LHS2 != LHS)
2850 return false;
2851 // We also need to canonicalize 'RHS'.
2852 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
2853 // x sgt C-1 <--> x sge C <--> not(x slt C)
2854 auto FlippedStrictness =
2855 InstCombiner::getFlippedStrictnessPredicateAndConstant(
2856 PredB, cast<Constant>(RHS2));
2857 if (!FlippedStrictness)
2858 return false;
2859 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
2860 "basic correctness failure");
2861 RHS2 = FlippedStrictness->second;
2862 // And kind-of perform the result swap.
2863 std::swap(Less, Greater);
2864 PredB = ICmpInst::ICMP_SLT;
2865 }
2866 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
2867 }
2868
foldICmpSelectConstant(ICmpInst & Cmp,SelectInst * Select,ConstantInt * C)2869 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
2870 SelectInst *Select,
2871 ConstantInt *C) {
2872
2873 assert(C && "Cmp RHS should be a constant int!");
2874 // If we're testing a constant value against the result of a three way
2875 // comparison, the result can be expressed directly in terms of the
2876 // original values being compared. Note: We could possibly be more
2877 // aggressive here and remove the hasOneUse test. The original select is
2878 // really likely to simplify or sink when we remove a test of the result.
2879 Value *OrigLHS, *OrigRHS;
2880 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
2881 if (Cmp.hasOneUse() &&
2882 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
2883 C3GreaterThan)) {
2884 assert(C1LessThan && C2Equal && C3GreaterThan);
2885
2886 bool TrueWhenLessThan =
2887 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
2888 ->isAllOnesValue();
2889 bool TrueWhenEqual =
2890 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
2891 ->isAllOnesValue();
2892 bool TrueWhenGreaterThan =
2893 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
2894 ->isAllOnesValue();
2895
2896 // This generates the new instruction that will replace the original Cmp
2897 // Instruction. Instead of enumerating the various combinations when
2898 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
2899 // false, we rely on chaining of ORs and future passes of InstCombine to
2900 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
2901
2902 // When none of the three constants satisfy the predicate for the RHS (C),
2903 // the entire original Cmp can be simplified to a false.
2904 Value *Cond = Builder.getFalse();
2905 if (TrueWhenLessThan)
2906 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
2907 OrigLHS, OrigRHS));
2908 if (TrueWhenEqual)
2909 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
2910 OrigLHS, OrigRHS));
2911 if (TrueWhenGreaterThan)
2912 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
2913 OrigLHS, OrigRHS));
2914
2915 return replaceInstUsesWith(Cmp, Cond);
2916 }
2917 return nullptr;
2918 }
2919
foldICmpBitCast(ICmpInst & Cmp)2920 Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
2921 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
2922 if (!Bitcast)
2923 return nullptr;
2924
2925 ICmpInst::Predicate Pred = Cmp.getPredicate();
2926 Value *Op1 = Cmp.getOperand(1);
2927 Value *BCSrcOp = Bitcast->getOperand(0);
2928 Type *SrcType = Bitcast->getSrcTy();
2929 Type *DstType = Bitcast->getType();
2930
2931 // Make sure the bitcast doesn't change between scalar and vector and
2932 // doesn't change the number of vector elements.
2933 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
2934 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
2935 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
2936 Value *X;
2937 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
2938 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
2939 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
2940 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
2941 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
2942 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
2943 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
2944 match(Op1, m_Zero()))
2945 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2946
2947 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
2948 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
2949 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
2950
2951 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
2952 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
2953 return new ICmpInst(Pred, X,
2954 ConstantInt::getAllOnesValue(X->getType()));
2955 }
2956
2957 // Zero-equality checks are preserved through unsigned floating-point casts:
2958 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
2959 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
2960 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
2961 if (Cmp.isEquality() && match(Op1, m_Zero()))
2962 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2963
2964 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
2965 // the FP extend/truncate because that cast does not change the sign-bit.
2966 // This is true for all standard IEEE-754 types and the X86 80-bit type.
2967 // The sign-bit is always the most significant bit in those types.
2968 const APInt *C;
2969 bool TrueIfSigned;
2970 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
2971 isSignBitCheck(Pred, *C, TrueIfSigned)) {
2972 if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
2973 match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
2974 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
2975 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
2976 Type *XType = X->getType();
2977
2978 // We can't currently handle Power style floating point operations here.
2979 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
2980 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
2981 if (auto *XVTy = dyn_cast<VectorType>(XType))
2982 NewType = VectorType::get(NewType, XVTy->getElementCount());
2983 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
2984 if (TrueIfSigned)
2985 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
2986 ConstantInt::getNullValue(NewType));
2987 else
2988 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
2989 ConstantInt::getAllOnesValue(NewType));
2990 }
2991 }
2992 }
2993 }
2994
2995 // Test to see if the operands of the icmp are casted versions of other
2996 // values. If the ptr->ptr cast can be stripped off both arguments, do so.
2997 if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
2998 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
2999 // so eliminate it as well.
3000 if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
3001 Op1 = BC2->getOperand(0);
3002
3003 Op1 = Builder.CreateBitCast(Op1, SrcType);
3004 return new ICmpInst(Pred, BCSrcOp, Op1);
3005 }
3006
3007 const APInt *C;
3008 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3009 !SrcType->isIntOrIntVectorTy())
3010 return nullptr;
3011
3012 // If this is checking if all elements of a vector compare are set or not,
3013 // invert the casted vector equality compare and test if all compare
3014 // elements are clear or not. Compare against zero is generally easier for
3015 // analysis and codegen.
3016 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3017 // Example: are all elements equal? --> are zero elements not equal?
3018 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3019 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
3020 isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
3021 Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
3022 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3023 }
3024
3025 // If this is checking if all elements of an extended vector are clear or not,
3026 // compare in a narrow type to eliminate the extend:
3027 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3028 Value *X;
3029 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3030 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3031 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3032 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3033 Value *NewCast = Builder.CreateBitCast(X, NewType);
3034 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3035 }
3036 }
3037
3038 // Folding: icmp <pred> iN X, C
3039 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3040 // and C is a splat of a K-bit pattern
3041 // and SC is a constant vector = <C', C', C', ..., C'>
3042 // Into:
3043 // %E = extractelement <M x iK> %vec, i32 C'
3044 // icmp <pred> iK %E, trunc(C)
3045 Value *Vec;
3046 ArrayRef<int> Mask;
3047 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3048 // Check whether every element of Mask is the same constant
3049 if (all_equal(Mask)) {
3050 auto *VecTy = cast<VectorType>(SrcType);
3051 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3052 if (C->isSplat(EltTy->getBitWidth())) {
3053 // Fold the icmp based on the value of C
3054 // If C is M copies of an iK sized bit pattern,
3055 // then:
3056 // => %E = extractelement <N x iK> %vec, i32 Elem
3057 // icmp <pred> iK %SplatVal, <pattern>
3058 Value *Elem = Builder.getInt32(Mask[0]);
3059 Value *Extract = Builder.CreateExtractElement(Vec, Elem);
3060 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3061 return new ICmpInst(Pred, Extract, NewC);
3062 }
3063 }
3064 }
3065 return nullptr;
3066 }
3067
3068 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3069 /// where X is some kind of instruction.
foldICmpInstWithConstant(ICmpInst & Cmp)3070 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3071 const APInt *C;
3072
3073 if (match(Cmp.getOperand(1), m_APInt(C))) {
3074 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3075 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3076 return I;
3077
3078 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3079 // For now, we only support constant integers while folding the
3080 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3081 // similar to the cases handled by binary ops above.
3082 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3083 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3084 return I;
3085
3086 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3087 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3088 return I;
3089
3090 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3091 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
3092 return I;
3093
3094 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3095 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3096 // TODO: This checks one-use, but that is not strictly necessary.
3097 Value *Cmp0 = Cmp.getOperand(0);
3098 Value *X, *Y;
3099 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3100 (match(Cmp0,
3101 m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
3102 m_Value(X), m_Value(Y)))) ||
3103 match(Cmp0,
3104 m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
3105 m_Value(X), m_Value(Y))))))
3106 return new ICmpInst(Cmp.getPredicate(), X, Y);
3107 }
3108
3109 if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
3110 return foldICmpInstWithConstantAllowUndef(Cmp, *C);
3111
3112 return nullptr;
3113 }
3114
3115 /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3116 /// icmp eq/ne BO, C.
foldICmpBinOpEqualityWithConstant(ICmpInst & Cmp,BinaryOperator * BO,const APInt & C)3117 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3118 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3119 // TODO: Some of these folds could work with arbitrary constants, but this
3120 // function is limited to scalar and vector splat constants.
3121 if (!Cmp.isEquality())
3122 return nullptr;
3123
3124 ICmpInst::Predicate Pred = Cmp.getPredicate();
3125 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3126 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3127 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3128
3129 switch (BO->getOpcode()) {
3130 case Instruction::SRem:
3131 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3132 if (C.isZero() && BO->hasOneUse()) {
3133 const APInt *BOC;
3134 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3135 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3136 return new ICmpInst(Pred, NewRem,
3137 Constant::getNullValue(BO->getType()));
3138 }
3139 }
3140 break;
3141 case Instruction::Add: {
3142 // (A + C2) == C --> A == (C - C2)
3143 // (A + C2) != C --> A != (C - C2)
3144 // TODO: Remove the one-use limitation? See discussion in D58633.
3145 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3146 if (BO->hasOneUse())
3147 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3148 } else if (C.isZero()) {
3149 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3150 // efficiently invertible, or if the add has just this one use.
3151 if (Value *NegVal = dyn_castNegVal(BOp1))
3152 return new ICmpInst(Pred, BOp0, NegVal);
3153 if (Value *NegVal = dyn_castNegVal(BOp0))
3154 return new ICmpInst(Pred, NegVal, BOp1);
3155 if (BO->hasOneUse()) {
3156 Value *Neg = Builder.CreateNeg(BOp1);
3157 Neg->takeName(BO);
3158 return new ICmpInst(Pred, BOp0, Neg);
3159 }
3160 }
3161 break;
3162 }
3163 case Instruction::Xor:
3164 if (BO->hasOneUse()) {
3165 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3166 // For the xor case, we can xor two constants together, eliminating
3167 // the explicit xor.
3168 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3169 } else if (C.isZero()) {
3170 // Replace ((xor A, B) != 0) with (A != B)
3171 return new ICmpInst(Pred, BOp0, BOp1);
3172 }
3173 }
3174 break;
3175 case Instruction::Or: {
3176 const APInt *BOC;
3177 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3178 // Comparing if all bits outside of a constant mask are set?
3179 // Replace (X | C) == -1 with (X & ~C) == ~C.
3180 // This removes the -1 constant.
3181 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
3182 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3183 return new ICmpInst(Pred, And, NotBOC);
3184 }
3185 break;
3186 }
3187 case Instruction::And: {
3188 const APInt *BOC;
3189 if (match(BOp1, m_APInt(BOC))) {
3190 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3191 if (C == *BOC && C.isPowerOf2())
3192 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
3193 BO, Constant::getNullValue(RHS->getType()));
3194 }
3195 break;
3196 }
3197 case Instruction::UDiv:
3198 if (C.isZero()) {
3199 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3200 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3201 return new ICmpInst(NewPred, BOp1, BOp0);
3202 }
3203 break;
3204 default:
3205 break;
3206 }
3207 return nullptr;
3208 }
3209
3210 /// Fold an equality icmp with LLVM intrinsic and constant operand.
foldICmpEqIntrinsicWithConstant(ICmpInst & Cmp,IntrinsicInst * II,const APInt & C)3211 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3212 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3213 Type *Ty = II->getType();
3214 unsigned BitWidth = C.getBitWidth();
3215 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3216
3217 switch (II->getIntrinsicID()) {
3218 case Intrinsic::abs:
3219 // abs(A) == 0 -> A == 0
3220 // abs(A) == INT_MIN -> A == INT_MIN
3221 if (C.isZero() || C.isMinSignedValue())
3222 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3223 break;
3224
3225 case Intrinsic::bswap:
3226 // bswap(A) == C -> A == bswap(C)
3227 return new ICmpInst(Pred, II->getArgOperand(0),
3228 ConstantInt::get(Ty, C.byteSwap()));
3229
3230 case Intrinsic::ctlz:
3231 case Intrinsic::cttz: {
3232 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3233 if (C == BitWidth)
3234 return new ICmpInst(Pred, II->getArgOperand(0),
3235 ConstantInt::getNullValue(Ty));
3236
3237 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3238 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3239 // Limit to one use to ensure we don't increase instruction count.
3240 unsigned Num = C.getLimitedValue(BitWidth);
3241 if (Num != BitWidth && II->hasOneUse()) {
3242 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3243 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3244 : APInt::getHighBitsSet(BitWidth, Num + 1);
3245 APInt Mask2 = IsTrailing
3246 ? APInt::getOneBitSet(BitWidth, Num)
3247 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3248 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3249 ConstantInt::get(Ty, Mask2));
3250 }
3251 break;
3252 }
3253
3254 case Intrinsic::ctpop: {
3255 // popcount(A) == 0 -> A == 0 and likewise for !=
3256 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3257 bool IsZero = C.isZero();
3258 if (IsZero || C == BitWidth)
3259 return new ICmpInst(Pred, II->getArgOperand(0),
3260 IsZero ? Constant::getNullValue(Ty)
3261 : Constant::getAllOnesValue(Ty));
3262
3263 break;
3264 }
3265
3266 case Intrinsic::fshl:
3267 case Intrinsic::fshr:
3268 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3269 const APInt *RotAmtC;
3270 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3271 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3272 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3273 return new ICmpInst(Pred, II->getArgOperand(0),
3274 II->getIntrinsicID() == Intrinsic::fshl
3275 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3276 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3277 }
3278 break;
3279
3280 case Intrinsic::uadd_sat: {
3281 // uadd.sat(a, b) == 0 -> (a | b) == 0
3282 if (C.isZero()) {
3283 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
3284 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
3285 }
3286 break;
3287 }
3288
3289 case Intrinsic::usub_sat: {
3290 // usub.sat(a, b) == 0 -> a <= b
3291 if (C.isZero()) {
3292 ICmpInst::Predicate NewPred =
3293 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3294 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
3295 }
3296 break;
3297 }
3298 default:
3299 break;
3300 }
3301
3302 return nullptr;
3303 }
3304
3305 /// Fold an icmp with LLVM intrinsics
foldICmpIntrinsicWithIntrinsic(ICmpInst & Cmp)3306 static Instruction *foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp) {
3307 assert(Cmp.isEquality());
3308
3309 ICmpInst::Predicate Pred = Cmp.getPredicate();
3310 Value *Op0 = Cmp.getOperand(0);
3311 Value *Op1 = Cmp.getOperand(1);
3312 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
3313 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
3314 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
3315 return nullptr;
3316
3317 switch (IIOp0->getIntrinsicID()) {
3318 case Intrinsic::bswap:
3319 case Intrinsic::bitreverse:
3320 // If both operands are byte-swapped or bit-reversed, just compare the
3321 // original values.
3322 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3323 case Intrinsic::fshl:
3324 case Intrinsic::fshr:
3325 // If both operands are rotated by same amount, just compare the
3326 // original values.
3327 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
3328 break;
3329 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
3330 break;
3331 if (IIOp0->getOperand(2) != IIOp1->getOperand(2))
3332 break;
3333 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
3334 default:
3335 break;
3336 }
3337
3338 return nullptr;
3339 }
3340
3341 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3342 /// where X is some kind of instruction and C is AllowUndef.
3343 /// TODO: Move more folds which allow undef to this function.
3344 Instruction *
foldICmpInstWithConstantAllowUndef(ICmpInst & Cmp,const APInt & C)3345 InstCombinerImpl::foldICmpInstWithConstantAllowUndef(ICmpInst &Cmp,
3346 const APInt &C) {
3347 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3348 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
3349 switch (II->getIntrinsicID()) {
3350 default:
3351 break;
3352 case Intrinsic::fshl:
3353 case Intrinsic::fshr:
3354 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
3355 // (rot X, ?) == 0/-1 --> X == 0/-1
3356 if (C.isZero() || C.isAllOnes())
3357 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
3358 }
3359 break;
3360 }
3361 }
3362
3363 return nullptr;
3364 }
3365
3366 /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
foldICmpBinOpWithConstant(ICmpInst & Cmp,BinaryOperator * BO,const APInt & C)3367 Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
3368 BinaryOperator *BO,
3369 const APInt &C) {
3370 switch (BO->getOpcode()) {
3371 case Instruction::Xor:
3372 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
3373 return I;
3374 break;
3375 case Instruction::And:
3376 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
3377 return I;
3378 break;
3379 case Instruction::Or:
3380 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
3381 return I;
3382 break;
3383 case Instruction::Mul:
3384 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
3385 return I;
3386 break;
3387 case Instruction::Shl:
3388 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
3389 return I;
3390 break;
3391 case Instruction::LShr:
3392 case Instruction::AShr:
3393 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
3394 return I;
3395 break;
3396 case Instruction::SRem:
3397 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
3398 return I;
3399 break;
3400 case Instruction::UDiv:
3401 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
3402 return I;
3403 [[fallthrough]];
3404 case Instruction::SDiv:
3405 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
3406 return I;
3407 break;
3408 case Instruction::Sub:
3409 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
3410 return I;
3411 break;
3412 case Instruction::Add:
3413 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
3414 return I;
3415 break;
3416 default:
3417 break;
3418 }
3419
3420 // TODO: These folds could be refactored to be part of the above calls.
3421 return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
3422 }
3423
3424 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
foldICmpIntrinsicWithConstant(ICmpInst & Cmp,IntrinsicInst * II,const APInt & C)3425 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
3426 IntrinsicInst *II,
3427 const APInt &C) {
3428 if (Cmp.isEquality())
3429 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
3430
3431 Type *Ty = II->getType();
3432 unsigned BitWidth = C.getBitWidth();
3433 ICmpInst::Predicate Pred = Cmp.getPredicate();
3434 switch (II->getIntrinsicID()) {
3435 case Intrinsic::ctpop: {
3436 // (ctpop X > BitWidth - 1) --> X == -1
3437 Value *X = II->getArgOperand(0);
3438 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
3439 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
3440 ConstantInt::getAllOnesValue(Ty));
3441 // (ctpop X < BitWidth) --> X != -1
3442 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
3443 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
3444 ConstantInt::getAllOnesValue(Ty));
3445 break;
3446 }
3447 case Intrinsic::ctlz: {
3448 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
3449 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3450 unsigned Num = C.getLimitedValue();
3451 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
3452 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
3453 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3454 }
3455
3456 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
3457 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3458 unsigned Num = C.getLimitedValue();
3459 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
3460 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
3461 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
3462 }
3463 break;
3464 }
3465 case Intrinsic::cttz: {
3466 // Limit to one use to ensure we don't increase instruction count.
3467 if (!II->hasOneUse())
3468 return nullptr;
3469
3470 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
3471 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
3472 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
3473 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
3474 Builder.CreateAnd(II->getArgOperand(0), Mask),
3475 ConstantInt::getNullValue(Ty));
3476 }
3477
3478 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
3479 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
3480 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
3481 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
3482 Builder.CreateAnd(II->getArgOperand(0), Mask),
3483 ConstantInt::getNullValue(Ty));
3484 }
3485 break;
3486 }
3487 default:
3488 break;
3489 }
3490
3491 return nullptr;
3492 }
3493
3494 /// Handle icmp with constant (but not simple integer constant) RHS.
foldICmpInstWithConstantNotInt(ICmpInst & I)3495 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
3496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3497 Constant *RHSC = dyn_cast<Constant>(Op1);
3498 Instruction *LHSI = dyn_cast<Instruction>(Op0);
3499 if (!RHSC || !LHSI)
3500 return nullptr;
3501
3502 switch (LHSI->getOpcode()) {
3503 case Instruction::GetElementPtr:
3504 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
3505 if (RHSC->isNullValue() &&
3506 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
3507 return new ICmpInst(
3508 I.getPredicate(), LHSI->getOperand(0),
3509 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3510 break;
3511 case Instruction::PHI:
3512 // Only fold icmp into the PHI if the phi and icmp are in the same
3513 // block. If in the same block, we're encouraging jump threading. If
3514 // not, we are just pessimizing the code by making an i1 phi.
3515 if (LHSI->getParent() == I.getParent())
3516 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
3517 return NV;
3518 break;
3519 case Instruction::IntToPtr:
3520 // icmp pred inttoptr(X), null -> icmp pred X, 0
3521 if (RHSC->isNullValue() &&
3522 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
3523 return new ICmpInst(
3524 I.getPredicate(), LHSI->getOperand(0),
3525 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3526 break;
3527
3528 case Instruction::Load:
3529 // Try to optimize things like "A[i] > 4" to index computations.
3530 if (GetElementPtrInst *GEP =
3531 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
3532 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
3533 if (Instruction *Res =
3534 foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
3535 return Res;
3536 break;
3537 }
3538
3539 return nullptr;
3540 }
3541
foldSelectICmp(ICmpInst::Predicate Pred,SelectInst * SI,Value * RHS,const ICmpInst & I)3542 Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred,
3543 SelectInst *SI, Value *RHS,
3544 const ICmpInst &I) {
3545 // Try to fold the comparison into the select arms, which will cause the
3546 // select to be converted into a logical and/or.
3547 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
3548 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
3549 return Res;
3550 if (std::optional<bool> Impl = isImpliedCondition(
3551 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
3552 return ConstantInt::get(I.getType(), *Impl);
3553 return nullptr;
3554 };
3555
3556 ConstantInt *CI = nullptr;
3557 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
3558 if (Op1)
3559 CI = dyn_cast<ConstantInt>(Op1);
3560
3561 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
3562 if (Op2)
3563 CI = dyn_cast<ConstantInt>(Op2);
3564
3565 // We only want to perform this transformation if it will not lead to
3566 // additional code. This is true if either both sides of the select
3567 // fold to a constant (in which case the icmp is replaced with a select
3568 // which will usually simplify) or this is the only user of the
3569 // select (in which case we are trading a select+icmp for a simpler
3570 // select+icmp) or all uses of the select can be replaced based on
3571 // dominance information ("Global cases").
3572 bool Transform = false;
3573 if (Op1 && Op2)
3574 Transform = true;
3575 else if (Op1 || Op2) {
3576 // Local case
3577 if (SI->hasOneUse())
3578 Transform = true;
3579 // Global cases
3580 else if (CI && !CI->isZero())
3581 // When Op1 is constant try replacing select with second operand.
3582 // Otherwise Op2 is constant and try replacing select with first
3583 // operand.
3584 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
3585 }
3586 if (Transform) {
3587 if (!Op1)
3588 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
3589 if (!Op2)
3590 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
3591 return SelectInst::Create(SI->getOperand(0), Op1, Op2);
3592 }
3593
3594 return nullptr;
3595 }
3596
3597 /// Some comparisons can be simplified.
3598 /// In this case, we are looking for comparisons that look like
3599 /// a check for a lossy truncation.
3600 /// Folds:
3601 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
3602 /// Where Mask is some pattern that produces all-ones in low bits:
3603 /// (-1 >> y)
3604 /// ((-1 << y) >> y) <- non-canonical, has extra uses
3605 /// ~(-1 << y)
3606 /// ((1 << y) + (-1)) <- non-canonical, has extra uses
3607 /// The Mask can be a constant, too.
3608 /// For some predicates, the operands are commutative.
3609 /// For others, x can only be on a specific side.
foldICmpWithLowBitMaskedVal(ICmpInst & I,InstCombiner::BuilderTy & Builder)3610 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
3611 InstCombiner::BuilderTy &Builder) {
3612 ICmpInst::Predicate SrcPred;
3613 Value *X, *M, *Y;
3614 auto m_VariableMask = m_CombineOr(
3615 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
3616 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
3617 m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
3618 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
3619 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
3620 if (!match(&I, m_c_ICmp(SrcPred,
3621 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
3622 m_Deferred(X))))
3623 return nullptr;
3624
3625 ICmpInst::Predicate DstPred;
3626 switch (SrcPred) {
3627 case ICmpInst::Predicate::ICMP_EQ:
3628 // x & (-1 >> y) == x -> x u<= (-1 >> y)
3629 DstPred = ICmpInst::Predicate::ICMP_ULE;
3630 break;
3631 case ICmpInst::Predicate::ICMP_NE:
3632 // x & (-1 >> y) != x -> x u> (-1 >> y)
3633 DstPred = ICmpInst::Predicate::ICMP_UGT;
3634 break;
3635 case ICmpInst::Predicate::ICMP_ULT:
3636 // x & (-1 >> y) u< x -> x u> (-1 >> y)
3637 // x u> x & (-1 >> y) -> x u> (-1 >> y)
3638 DstPred = ICmpInst::Predicate::ICMP_UGT;
3639 break;
3640 case ICmpInst::Predicate::ICMP_UGE:
3641 // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
3642 // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
3643 DstPred = ICmpInst::Predicate::ICMP_ULE;
3644 break;
3645 case ICmpInst::Predicate::ICMP_SLT:
3646 // x & (-1 >> y) s< x -> x s> (-1 >> y)
3647 // x s> x & (-1 >> y) -> x s> (-1 >> y)
3648 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3649 return nullptr;
3650 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3651 return nullptr;
3652 DstPred = ICmpInst::Predicate::ICMP_SGT;
3653 break;
3654 case ICmpInst::Predicate::ICMP_SGE:
3655 // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
3656 // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
3657 if (!match(M, m_Constant())) // Can not do this fold with non-constant.
3658 return nullptr;
3659 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
3660 return nullptr;
3661 DstPred = ICmpInst::Predicate::ICMP_SLE;
3662 break;
3663 case ICmpInst::Predicate::ICMP_SGT:
3664 case ICmpInst::Predicate::ICMP_SLE:
3665 return nullptr;
3666 case ICmpInst::Predicate::ICMP_UGT:
3667 case ICmpInst::Predicate::ICMP_ULE:
3668 llvm_unreachable("Instsimplify took care of commut. variant");
3669 break;
3670 default:
3671 llvm_unreachable("All possible folds are handled.");
3672 }
3673
3674 // The mask value may be a vector constant that has undefined elements. But it
3675 // may not be safe to propagate those undefs into the new compare, so replace
3676 // those elements by copying an existing, defined, and safe scalar constant.
3677 Type *OpTy = M->getType();
3678 auto *VecC = dyn_cast<Constant>(M);
3679 auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
3680 if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
3681 Constant *SafeReplacementConstant = nullptr;
3682 for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
3683 if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
3684 SafeReplacementConstant = VecC->getAggregateElement(i);
3685 break;
3686 }
3687 }
3688 assert(SafeReplacementConstant && "Failed to find undef replacement");
3689 M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
3690 }
3691
3692 return Builder.CreateICmp(DstPred, X, M);
3693 }
3694
3695 /// Some comparisons can be simplified.
3696 /// In this case, we are looking for comparisons that look like
3697 /// a check for a lossy signed truncation.
3698 /// Folds: (MaskedBits is a constant.)
3699 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
3700 /// Into:
3701 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
3702 /// Where KeptBits = bitwidth(%x) - MaskedBits
3703 static Value *
foldICmpWithTruncSignExtendedVal(ICmpInst & I,InstCombiner::BuilderTy & Builder)3704 foldICmpWithTruncSignExtendedVal(ICmpInst &I,
3705 InstCombiner::BuilderTy &Builder) {
3706 ICmpInst::Predicate SrcPred;
3707 Value *X;
3708 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
3709 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
3710 if (!match(&I, m_c_ICmp(SrcPred,
3711 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
3712 m_APInt(C1))),
3713 m_Deferred(X))))
3714 return nullptr;
3715
3716 // Potential handling of non-splats: for each element:
3717 // * if both are undef, replace with constant 0.
3718 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
3719 // * if both are not undef, and are different, bailout.
3720 // * else, only one is undef, then pick the non-undef one.
3721
3722 // The shift amount must be equal.
3723 if (*C0 != *C1)
3724 return nullptr;
3725 const APInt &MaskedBits = *C0;
3726 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
3727
3728 ICmpInst::Predicate DstPred;
3729 switch (SrcPred) {
3730 case ICmpInst::Predicate::ICMP_EQ:
3731 // ((%x << MaskedBits) a>> MaskedBits) == %x
3732 // =>
3733 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
3734 DstPred = ICmpInst::Predicate::ICMP_ULT;
3735 break;
3736 case ICmpInst::Predicate::ICMP_NE:
3737 // ((%x << MaskedBits) a>> MaskedBits) != %x
3738 // =>
3739 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
3740 DstPred = ICmpInst::Predicate::ICMP_UGE;
3741 break;
3742 // FIXME: are more folds possible?
3743 default:
3744 return nullptr;
3745 }
3746
3747 auto *XType = X->getType();
3748 const unsigned XBitWidth = XType->getScalarSizeInBits();
3749 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
3750 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
3751
3752 // KeptBits = bitwidth(%x) - MaskedBits
3753 const APInt KeptBits = BitWidth - MaskedBits;
3754 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
3755 // ICmpCst = (1 << KeptBits)
3756 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
3757 assert(ICmpCst.isPowerOf2());
3758 // AddCst = (1 << (KeptBits-1))
3759 const APInt AddCst = ICmpCst.lshr(1);
3760 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
3761
3762 // T0 = add %x, AddCst
3763 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
3764 // T1 = T0 DstPred ICmpCst
3765 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
3766
3767 return T1;
3768 }
3769
3770 // Given pattern:
3771 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3772 // we should move shifts to the same hand of 'and', i.e. rewrite as
3773 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3774 // We are only interested in opposite logical shifts here.
3775 // One of the shifts can be truncated.
3776 // If we can, we want to end up creating 'lshr' shift.
3777 static Value *
foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst & I,const SimplifyQuery SQ,InstCombiner::BuilderTy & Builder)3778 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
3779 InstCombiner::BuilderTy &Builder) {
3780 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
3781 !I.getOperand(0)->hasOneUse())
3782 return nullptr;
3783
3784 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
3785
3786 // Look for an 'and' of two logical shifts, one of which may be truncated.
3787 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
3788 Instruction *XShift, *MaybeTruncation, *YShift;
3789 if (!match(
3790 I.getOperand(0),
3791 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
3792 m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
3793 m_AnyLogicalShift, m_Instruction(YShift))),
3794 m_Instruction(MaybeTruncation)))))
3795 return nullptr;
3796
3797 // We potentially looked past 'trunc', but only when matching YShift,
3798 // therefore YShift must have the widest type.
3799 Instruction *WidestShift = YShift;
3800 // Therefore XShift must have the shallowest type.
3801 // Or they both have identical types if there was no truncation.
3802 Instruction *NarrowestShift = XShift;
3803
3804 Type *WidestTy = WidestShift->getType();
3805 Type *NarrowestTy = NarrowestShift->getType();
3806 assert(NarrowestTy == I.getOperand(0)->getType() &&
3807 "We did not look past any shifts while matching XShift though.");
3808 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
3809
3810 // If YShift is a 'lshr', swap the shifts around.
3811 if (match(YShift, m_LShr(m_Value(), m_Value())))
3812 std::swap(XShift, YShift);
3813
3814 // The shifts must be in opposite directions.
3815 auto XShiftOpcode = XShift->getOpcode();
3816 if (XShiftOpcode == YShift->getOpcode())
3817 return nullptr; // Do not care about same-direction shifts here.
3818
3819 Value *X, *XShAmt, *Y, *YShAmt;
3820 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
3821 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
3822
3823 // If one of the values being shifted is a constant, then we will end with
3824 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
3825 // however, we will need to ensure that we won't increase instruction count.
3826 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
3827 // At least one of the hands of the 'and' should be one-use shift.
3828 if (!match(I.getOperand(0),
3829 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
3830 return nullptr;
3831 if (HadTrunc) {
3832 // Due to the 'trunc', we will need to widen X. For that either the old
3833 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
3834 if (!MaybeTruncation->hasOneUse() &&
3835 !NarrowestShift->getOperand(1)->hasOneUse())
3836 return nullptr;
3837 }
3838 }
3839
3840 // We have two shift amounts from two different shifts. The types of those
3841 // shift amounts may not match. If that's the case let's bailout now.
3842 if (XShAmt->getType() != YShAmt->getType())
3843 return nullptr;
3844
3845 // As input, we have the following pattern:
3846 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
3847 // We want to rewrite that as:
3848 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
3849 // While we know that originally (Q+K) would not overflow
3850 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
3851 // shift amounts. so it may now overflow in smaller bitwidth.
3852 // To ensure that does not happen, we need to ensure that the total maximal
3853 // shift amount is still representable in that smaller bit width.
3854 unsigned MaximalPossibleTotalShiftAmount =
3855 (WidestTy->getScalarSizeInBits() - 1) +
3856 (NarrowestTy->getScalarSizeInBits() - 1);
3857 APInt MaximalRepresentableShiftAmount =
3858 APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());
3859 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
3860 return nullptr;
3861
3862 // Can we fold (XShAmt+YShAmt) ?
3863 auto *NewShAmt = dyn_cast_or_null<Constant>(
3864 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
3865 /*isNUW=*/false, SQ.getWithInstruction(&I)));
3866 if (!NewShAmt)
3867 return nullptr;
3868 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
3869 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
3870
3871 // Is the new shift amount smaller than the bit width?
3872 // FIXME: could also rely on ConstantRange.
3873 if (!match(NewShAmt,
3874 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
3875 APInt(WidestBitWidth, WidestBitWidth))))
3876 return nullptr;
3877
3878 // An extra legality check is needed if we had trunc-of-lshr.
3879 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
3880 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
3881 WidestShift]() {
3882 // It isn't obvious whether it's worth it to analyze non-constants here.
3883 // Also, let's basically give up on non-splat cases, pessimizing vectors.
3884 // If *any* of these preconditions matches we can perform the fold.
3885 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
3886 ? NewShAmt->getSplatValue()
3887 : NewShAmt;
3888 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
3889 if (NewShAmtSplat &&
3890 (NewShAmtSplat->isNullValue() ||
3891 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
3892 return true;
3893 // We consider *min* leading zeros so a single outlier
3894 // blocks the transform as opposed to allowing it.
3895 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
3896 KnownBits Known = computeKnownBits(C, SQ.DL);
3897 unsigned MinLeadZero = Known.countMinLeadingZeros();
3898 // If the value being shifted has at most lowest bit set we can fold.
3899 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3900 if (MaxActiveBits <= 1)
3901 return true;
3902 // Precondition: NewShAmt u<= countLeadingZeros(C)
3903 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
3904 return true;
3905 }
3906 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
3907 KnownBits Known = computeKnownBits(C, SQ.DL);
3908 unsigned MinLeadZero = Known.countMinLeadingZeros();
3909 // If the value being shifted has at most lowest bit set we can fold.
3910 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
3911 if (MaxActiveBits <= 1)
3912 return true;
3913 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
3914 if (NewShAmtSplat) {
3915 APInt AdjNewShAmt =
3916 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
3917 if (AdjNewShAmt.ule(MinLeadZero))
3918 return true;
3919 }
3920 }
3921 return false; // Can't tell if it's ok.
3922 };
3923 if (!CanFold())
3924 return nullptr;
3925 }
3926
3927 // All good, we can do this fold.
3928 X = Builder.CreateZExt(X, WidestTy);
3929 Y = Builder.CreateZExt(Y, WidestTy);
3930 // The shift is the same that was for X.
3931 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
3932 ? Builder.CreateLShr(X, NewShAmt)
3933 : Builder.CreateShl(X, NewShAmt);
3934 Value *T1 = Builder.CreateAnd(T0, Y);
3935 return Builder.CreateICmp(I.getPredicate(), T1,
3936 Constant::getNullValue(WidestTy));
3937 }
3938
3939 /// Fold
3940 /// (-1 u/ x) u< y
3941 /// ((x * y) ?/ x) != y
3942 /// to
3943 /// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
3944 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
3945 /// will mean that we are looking for the opposite answer.
foldMultiplicationOverflowCheck(ICmpInst & I)3946 Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
3947 ICmpInst::Predicate Pred;
3948 Value *X, *Y;
3949 Instruction *Mul;
3950 Instruction *Div;
3951 bool NeedNegation;
3952 // Look for: (-1 u/ x) u</u>= y
3953 if (!I.isEquality() &&
3954 match(&I, m_c_ICmp(Pred,
3955 m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
3956 m_Instruction(Div)),
3957 m_Value(Y)))) {
3958 Mul = nullptr;
3959
3960 // Are we checking that overflow does not happen, or does happen?
3961 switch (Pred) {
3962 case ICmpInst::Predicate::ICMP_ULT:
3963 NeedNegation = false;
3964 break; // OK
3965 case ICmpInst::Predicate::ICMP_UGE:
3966 NeedNegation = true;
3967 break; // OK
3968 default:
3969 return nullptr; // Wrong predicate.
3970 }
3971 } else // Look for: ((x * y) / x) !=/== y
3972 if (I.isEquality() &&
3973 match(&I,
3974 m_c_ICmp(Pred, m_Value(Y),
3975 m_CombineAnd(
3976 m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),
3977 m_Value(X)),
3978 m_Instruction(Mul)),
3979 m_Deferred(X))),
3980 m_Instruction(Div))))) {
3981 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
3982 } else
3983 return nullptr;
3984
3985 BuilderTy::InsertPointGuard Guard(Builder);
3986 // If the pattern included (x * y), we'll want to insert new instructions
3987 // right before that original multiplication so that we can replace it.
3988 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
3989 if (MulHadOtherUses)
3990 Builder.SetInsertPoint(Mul);
3991
3992 Function *F = Intrinsic::getDeclaration(I.getModule(),
3993 Div->getOpcode() == Instruction::UDiv
3994 ? Intrinsic::umul_with_overflow
3995 : Intrinsic::smul_with_overflow,
3996 X->getType());
3997 CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
3998
3999 // If the multiplication was used elsewhere, to ensure that we don't leave
4000 // "duplicate" instructions, replace uses of that original multiplication
4001 // with the multiplication result from the with.overflow intrinsic.
4002 if (MulHadOtherUses)
4003 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
4004
4005 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
4006 if (NeedNegation) // This technically increases instruction count.
4007 Res = Builder.CreateNot(Res, "mul.not.ov");
4008
4009 // If we replaced the mul, erase it. Do this after all uses of Builder,
4010 // as the mul is used as insertion point.
4011 if (MulHadOtherUses)
4012 eraseInstFromFunction(*Mul);
4013
4014 return Res;
4015 }
4016
foldICmpXNegX(ICmpInst & I)4017 static Instruction *foldICmpXNegX(ICmpInst &I) {
4018 CmpInst::Predicate Pred;
4019 Value *X;
4020 if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X))))
4021 return nullptr;
4022
4023 if (ICmpInst::isSigned(Pred))
4024 Pred = ICmpInst::getSwappedPredicate(Pred);
4025 else if (ICmpInst::isUnsigned(Pred))
4026 Pred = ICmpInst::getSignedPredicate(Pred);
4027 // else for equality-comparisons just keep the predicate.
4028
4029 return ICmpInst::Create(Instruction::ICmp, Pred, X,
4030 Constant::getNullValue(X->getType()), I.getName());
4031 }
4032
4033 /// Try to fold icmp (binop), X or icmp X, (binop).
4034 /// TODO: A large part of this logic is duplicated in InstSimplify's
4035 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
4036 /// duplication.
foldICmpBinOp(ICmpInst & I,const SimplifyQuery & SQ)4037 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
4038 const SimplifyQuery &SQ) {
4039 const SimplifyQuery Q = SQ.getWithInstruction(&I);
4040 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4041
4042 // Special logic for binary operators.
4043 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
4044 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
4045 if (!BO0 && !BO1)
4046 return nullptr;
4047
4048 if (Instruction *NewICmp = foldICmpXNegX(I))
4049 return NewICmp;
4050
4051 const CmpInst::Predicate Pred = I.getPredicate();
4052 Value *X;
4053
4054 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
4055 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
4056 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
4057 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4058 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
4059 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
4060 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
4061 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4062 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
4063
4064 {
4065 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
4066 Constant *C;
4067 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
4068 m_ImmConstant(C)))) &&
4069 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
4070 Constant *C2 = ConstantExpr::getNot(C);
4071 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
4072 }
4073 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
4074 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
4075 m_ImmConstant(C)))) &&
4076 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
4077 Constant *C2 = ConstantExpr::getNot(C);
4078 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
4079 }
4080 }
4081
4082 {
4083 // Similar to above: an unsigned overflow comparison may use offset + mask:
4084 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
4085 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
4086 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
4087 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
4088 BinaryOperator *BO;
4089 const APInt *C;
4090 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
4091 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4092 match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowUndef(*C)))) {
4093 CmpInst::Predicate NewPred =
4094 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4095 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4096 return new ICmpInst(NewPred, Op1, Zero);
4097 }
4098
4099 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
4100 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
4101 match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowUndef(*C)))) {
4102 CmpInst::Predicate NewPred =
4103 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
4104 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
4105 return new ICmpInst(NewPred, Op0, Zero);
4106 }
4107 }
4108
4109 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
4110 if (BO0 && isa<OverflowingBinaryOperator>(BO0))
4111 NoOp0WrapProblem =
4112 ICmpInst::isEquality(Pred) ||
4113 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
4114 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
4115 if (BO1 && isa<OverflowingBinaryOperator>(BO1))
4116 NoOp1WrapProblem =
4117 ICmpInst::isEquality(Pred) ||
4118 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
4119 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
4120
4121 // Analyze the case when either Op0 or Op1 is an add instruction.
4122 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
4123 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
4124 if (BO0 && BO0->getOpcode() == Instruction::Add) {
4125 A = BO0->getOperand(0);
4126 B = BO0->getOperand(1);
4127 }
4128 if (BO1 && BO1->getOpcode() == Instruction::Add) {
4129 C = BO1->getOperand(0);
4130 D = BO1->getOperand(1);
4131 }
4132
4133 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
4134 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
4135 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
4136 return new ICmpInst(Pred, A == Op1 ? B : A,
4137 Constant::getNullValue(Op1->getType()));
4138
4139 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
4140 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
4141 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
4142 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
4143 C == Op0 ? D : C);
4144
4145 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
4146 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
4147 NoOp1WrapProblem) {
4148 // Determine Y and Z in the form icmp (X+Y), (X+Z).
4149 Value *Y, *Z;
4150 if (A == C) {
4151 // C + B == C + D -> B == D
4152 Y = B;
4153 Z = D;
4154 } else if (A == D) {
4155 // D + B == C + D -> B == C
4156 Y = B;
4157 Z = C;
4158 } else if (B == C) {
4159 // A + C == C + D -> A == D
4160 Y = A;
4161 Z = D;
4162 } else {
4163 assert(B == D);
4164 // A + D == C + D -> A == C
4165 Y = A;
4166 Z = C;
4167 }
4168 return new ICmpInst(Pred, Y, Z);
4169 }
4170
4171 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
4172 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
4173 match(B, m_AllOnes()))
4174 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
4175
4176 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
4177 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
4178 match(B, m_AllOnes()))
4179 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
4180
4181 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
4182 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
4183 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
4184
4185 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
4186 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
4187 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
4188
4189 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
4190 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
4191 match(D, m_AllOnes()))
4192 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
4193
4194 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
4195 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
4196 match(D, m_AllOnes()))
4197 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
4198
4199 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
4200 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
4201 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
4202
4203 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
4204 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
4205 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
4206
4207 // TODO: The subtraction-related identities shown below also hold, but
4208 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
4209 // wouldn't happen even if they were implemented.
4210 //
4211 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
4212 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
4213 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
4214 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
4215
4216 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
4217 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
4218 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
4219
4220 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
4221 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
4222 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
4223
4224 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
4225 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
4226 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
4227
4228 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
4229 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
4230 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
4231
4232 // if C1 has greater magnitude than C2:
4233 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
4234 // s.t. C3 = C1 - C2
4235 //
4236 // if C2 has greater magnitude than C1:
4237 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
4238 // s.t. C3 = C2 - C1
4239 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
4240 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
4241 const APInt *AP1, *AP2;
4242 // TODO: Support non-uniform vectors.
4243 // TODO: Allow undef passthrough if B AND D's element is undef.
4244 if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) &&
4245 AP1->isNegative() == AP2->isNegative()) {
4246 APInt AP1Abs = AP1->abs();
4247 APInt AP2Abs = AP2->abs();
4248 if (AP1Abs.uge(AP2Abs)) {
4249 APInt Diff = *AP1 - *AP2;
4250 bool HasNUW = BO0->hasNoUnsignedWrap() && Diff.ule(*AP1);
4251 bool HasNSW = BO0->hasNoSignedWrap();
4252 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4253 Value *NewAdd = Builder.CreateAdd(A, C3, "", HasNUW, HasNSW);
4254 return new ICmpInst(Pred, NewAdd, C);
4255 } else {
4256 APInt Diff = *AP2 - *AP1;
4257 bool HasNUW = BO1->hasNoUnsignedWrap() && Diff.ule(*AP2);
4258 bool HasNSW = BO1->hasNoSignedWrap();
4259 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
4260 Value *NewAdd = Builder.CreateAdd(C, C3, "", HasNUW, HasNSW);
4261 return new ICmpInst(Pred, A, NewAdd);
4262 }
4263 }
4264 Constant *Cst1, *Cst2;
4265 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
4266 ICmpInst::isEquality(Pred)) {
4267 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
4268 Value *NewAdd = Builder.CreateAdd(C, Diff);
4269 return new ICmpInst(Pred, A, NewAdd);
4270 }
4271 }
4272
4273 // Analyze the case when either Op0 or Op1 is a sub instruction.
4274 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
4275 A = nullptr;
4276 B = nullptr;
4277 C = nullptr;
4278 D = nullptr;
4279 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
4280 A = BO0->getOperand(0);
4281 B = BO0->getOperand(1);
4282 }
4283 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
4284 C = BO1->getOperand(0);
4285 D = BO1->getOperand(1);
4286 }
4287
4288 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
4289 if (A == Op1 && NoOp0WrapProblem)
4290 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
4291 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
4292 if (C == Op0 && NoOp1WrapProblem)
4293 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
4294
4295 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
4296 // (A - B) u>/u<= A --> B u>/u<= A
4297 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
4298 return new ICmpInst(Pred, B, A);
4299 // C u</u>= (C - D) --> C u</u>= D
4300 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
4301 return new ICmpInst(Pred, C, D);
4302 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
4303 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
4304 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4305 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
4306 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
4307 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
4308 isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
4309 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
4310
4311 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
4312 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
4313 return new ICmpInst(Pred, A, C);
4314
4315 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
4316 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
4317 return new ICmpInst(Pred, D, B);
4318
4319 // icmp (0-X) < cst --> x > -cst
4320 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
4321 Value *X;
4322 if (match(BO0, m_Neg(m_Value(X))))
4323 if (Constant *RHSC = dyn_cast<Constant>(Op1))
4324 if (RHSC->isNotMinSignedValue())
4325 return new ICmpInst(I.getSwappedPredicate(), X,
4326 ConstantExpr::getNeg(RHSC));
4327 }
4328
4329 {
4330 // Try to remove shared constant multiplier from equality comparison:
4331 // X * C == Y * C (with no overflowing/aliasing) --> X == Y
4332 Value *X, *Y;
4333 const APInt *C;
4334 if (match(Op0, m_Mul(m_Value(X), m_APInt(C))) && *C != 0 &&
4335 match(Op1, m_Mul(m_Value(Y), m_SpecificInt(*C))) && I.isEquality())
4336 if (!C->countTrailingZeros() ||
4337 (BO0 && BO1 && BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap()) ||
4338 (BO0 && BO1 && BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap()))
4339 return new ICmpInst(Pred, X, Y);
4340 }
4341
4342 BinaryOperator *SRem = nullptr;
4343 // icmp (srem X, Y), Y
4344 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
4345 SRem = BO0;
4346 // icmp Y, (srem X, Y)
4347 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
4348 Op0 == BO1->getOperand(1))
4349 SRem = BO1;
4350 if (SRem) {
4351 // We don't check hasOneUse to avoid increasing register pressure because
4352 // the value we use is the same value this instruction was already using.
4353 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
4354 default:
4355 break;
4356 case ICmpInst::ICMP_EQ:
4357 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
4358 case ICmpInst::ICMP_NE:
4359 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
4360 case ICmpInst::ICMP_SGT:
4361 case ICmpInst::ICMP_SGE:
4362 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
4363 Constant::getAllOnesValue(SRem->getType()));
4364 case ICmpInst::ICMP_SLT:
4365 case ICmpInst::ICMP_SLE:
4366 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
4367 Constant::getNullValue(SRem->getType()));
4368 }
4369 }
4370
4371 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
4372 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
4373 switch (BO0->getOpcode()) {
4374 default:
4375 break;
4376 case Instruction::Add:
4377 case Instruction::Sub:
4378 case Instruction::Xor: {
4379 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
4380 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4381
4382 const APInt *C;
4383 if (match(BO0->getOperand(1), m_APInt(C))) {
4384 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
4385 if (C->isSignMask()) {
4386 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4387 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4388 }
4389
4390 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
4391 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
4392 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
4393 NewPred = I.getSwappedPredicate(NewPred);
4394 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
4395 }
4396 }
4397 break;
4398 }
4399 case Instruction::Mul: {
4400 if (!I.isEquality())
4401 break;
4402
4403 const APInt *C;
4404 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
4405 !C->isOne()) {
4406 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
4407 // Mask = -1 >> count-trailing-zeros(C).
4408 if (unsigned TZs = C->countTrailingZeros()) {
4409 Constant *Mask = ConstantInt::get(
4410 BO0->getType(),
4411 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
4412 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
4413 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
4414 return new ICmpInst(Pred, And1, And2);
4415 }
4416 }
4417 break;
4418 }
4419 case Instruction::UDiv:
4420 case Instruction::LShr:
4421 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
4422 break;
4423 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4424
4425 case Instruction::SDiv:
4426 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
4427 break;
4428 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4429
4430 case Instruction::AShr:
4431 if (!BO0->isExact() || !BO1->isExact())
4432 break;
4433 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4434
4435 case Instruction::Shl: {
4436 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
4437 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
4438 if (!NUW && !NSW)
4439 break;
4440 if (!NSW && I.isSigned())
4441 break;
4442 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
4443 }
4444 }
4445 }
4446
4447 if (BO0) {
4448 // Transform A & (L - 1) `ult` L --> L != 0
4449 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
4450 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
4451
4452 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
4453 auto *Zero = Constant::getNullValue(BO0->getType());
4454 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
4455 }
4456 }
4457
4458 // For unsigned predicates / eq / ne:
4459 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
4460 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
4461 if (!ICmpInst::isSigned(Pred)) {
4462 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
4463 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
4464 Constant::getNullValue(Op1->getType()));
4465 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
4466 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
4467 Constant::getNullValue(Op0->getType()), Op0);
4468 }
4469
4470 if (Value *V = foldMultiplicationOverflowCheck(I))
4471 return replaceInstUsesWith(I, V);
4472
4473 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
4474 return replaceInstUsesWith(I, V);
4475
4476 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
4477 return replaceInstUsesWith(I, V);
4478
4479 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
4480 return replaceInstUsesWith(I, V);
4481
4482 return nullptr;
4483 }
4484
4485 /// Fold icmp Pred min|max(X, Y), X.
foldICmpWithMinMax(ICmpInst & Cmp)4486 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
4487 ICmpInst::Predicate Pred = Cmp.getPredicate();
4488 Value *Op0 = Cmp.getOperand(0);
4489 Value *X = Cmp.getOperand(1);
4490
4491 // Canonicalize minimum or maximum operand to LHS of the icmp.
4492 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
4493 match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
4494 match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
4495 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
4496 std::swap(Op0, X);
4497 Pred = Cmp.getSwappedPredicate();
4498 }
4499
4500 Value *Y;
4501 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
4502 // smin(X, Y) == X --> X s<= Y
4503 // smin(X, Y) s>= X --> X s<= Y
4504 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
4505 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
4506
4507 // smin(X, Y) != X --> X s> Y
4508 // smin(X, Y) s< X --> X s> Y
4509 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
4510 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
4511
4512 // These cases should be handled in InstSimplify:
4513 // smin(X, Y) s<= X --> true
4514 // smin(X, Y) s> X --> false
4515 return nullptr;
4516 }
4517
4518 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
4519 // smax(X, Y) == X --> X s>= Y
4520 // smax(X, Y) s<= X --> X s>= Y
4521 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
4522 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
4523
4524 // smax(X, Y) != X --> X s< Y
4525 // smax(X, Y) s> X --> X s< Y
4526 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
4527 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
4528
4529 // These cases should be handled in InstSimplify:
4530 // smax(X, Y) s>= X --> true
4531 // smax(X, Y) s< X --> false
4532 return nullptr;
4533 }
4534
4535 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
4536 // umin(X, Y) == X --> X u<= Y
4537 // umin(X, Y) u>= X --> X u<= Y
4538 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
4539 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
4540
4541 // umin(X, Y) != X --> X u> Y
4542 // umin(X, Y) u< X --> X u> Y
4543 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
4544 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
4545
4546 // These cases should be handled in InstSimplify:
4547 // umin(X, Y) u<= X --> true
4548 // umin(X, Y) u> X --> false
4549 return nullptr;
4550 }
4551
4552 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
4553 // umax(X, Y) == X --> X u>= Y
4554 // umax(X, Y) u<= X --> X u>= Y
4555 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
4556 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
4557
4558 // umax(X, Y) != X --> X u< Y
4559 // umax(X, Y) u> X --> X u< Y
4560 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
4561 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
4562
4563 // These cases should be handled in InstSimplify:
4564 // umax(X, Y) u>= X --> true
4565 // umax(X, Y) u< X --> false
4566 return nullptr;
4567 }
4568
4569 return nullptr;
4570 }
4571
foldICmpEquality(ICmpInst & I)4572 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
4573 if (!I.isEquality())
4574 return nullptr;
4575
4576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4577 const CmpInst::Predicate Pred = I.getPredicate();
4578 Value *A, *B, *C, *D;
4579 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4580 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4581 Value *OtherVal = A == Op1 ? B : A;
4582 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
4583 }
4584
4585 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4586 // A^c1 == C^c2 --> A == C^(c1^c2)
4587 ConstantInt *C1, *C2;
4588 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
4589 Op1->hasOneUse()) {
4590 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
4591 Value *Xor = Builder.CreateXor(C, NC);
4592 return new ICmpInst(Pred, A, Xor);
4593 }
4594
4595 // A^B == A^D -> B == D
4596 if (A == C)
4597 return new ICmpInst(Pred, B, D);
4598 if (A == D)
4599 return new ICmpInst(Pred, B, C);
4600 if (B == C)
4601 return new ICmpInst(Pred, A, D);
4602 if (B == D)
4603 return new ICmpInst(Pred, A, C);
4604 }
4605 }
4606
4607 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
4608 // A == (A^B) -> B == 0
4609 Value *OtherVal = A == Op0 ? B : A;
4610 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
4611 }
4612
4613 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4614 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
4615 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
4616 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
4617
4618 if (A == C) {
4619 X = B;
4620 Y = D;
4621 Z = A;
4622 } else if (A == D) {
4623 X = B;
4624 Y = C;
4625 Z = A;
4626 } else if (B == C) {
4627 X = A;
4628 Y = D;
4629 Z = B;
4630 } else if (B == D) {
4631 X = A;
4632 Y = C;
4633 Z = B;
4634 }
4635
4636 if (X) { // Build (X^Y) & Z
4637 Op1 = Builder.CreateXor(X, Y);
4638 Op1 = Builder.CreateAnd(Op1, Z);
4639 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
4640 }
4641 }
4642
4643 {
4644 // Similar to above, but specialized for constant because invert is needed:
4645 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
4646 Value *X, *Y;
4647 Constant *C;
4648 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
4649 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
4650 Value *Xor = Builder.CreateXor(X, Y);
4651 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
4652 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
4653 }
4654 }
4655
4656 if (match(Op1, m_ZExt(m_Value(A))) &&
4657 (Op0->hasOneUse() || Op1->hasOneUse())) {
4658 // (B & (Pow2C-1)) == zext A --> A == trunc B
4659 // (B & (Pow2C-1)) != zext A --> A != trunc B
4660 const APInt *MaskC;
4661 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
4662 MaskC->countTrailingOnes() == A->getType()->getScalarSizeInBits())
4663 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
4664
4665 // Test if 2 values have different or same signbits:
4666 // (X u>> BitWidth - 1) == zext (Y s> -1) --> (X ^ Y) < 0
4667 // (X u>> BitWidth - 1) != zext (Y s> -1) --> (X ^ Y) > -1
4668 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
4669 Value *X, *Y;
4670 ICmpInst::Predicate Pred2;
4671 if (match(Op0, m_LShr(m_Value(X), m_SpecificIntAllowUndef(OpWidth - 1))) &&
4672 match(A, m_ICmp(Pred2, m_Value(Y), m_AllOnes())) &&
4673 Pred2 == ICmpInst::ICMP_SGT && X->getType() == Y->getType()) {
4674 Value *Xor = Builder.CreateXor(X, Y, "xor.signbits");
4675 Value *R = (Pred == ICmpInst::ICMP_EQ) ? Builder.CreateIsNeg(Xor) :
4676 Builder.CreateIsNotNeg(Xor);
4677 return replaceInstUsesWith(I, R);
4678 }
4679 }
4680
4681 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
4682 // For lshr and ashr pairs.
4683 const APInt *AP1, *AP2;
4684 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
4685 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) ||
4686 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
4687 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) {
4688 if (AP1 != AP2)
4689 return nullptr;
4690 unsigned TypeBits = AP1->getBitWidth();
4691 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
4692 if (ShAmt < TypeBits && ShAmt != 0) {
4693 ICmpInst::Predicate NewPred =
4694 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
4695 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4696 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
4697 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
4698 }
4699 }
4700
4701 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
4702 ConstantInt *Cst1;
4703 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
4704 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
4705 unsigned TypeBits = Cst1->getBitWidth();
4706 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
4707 if (ShAmt < TypeBits && ShAmt != 0) {
4708 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
4709 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
4710 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
4711 I.getName() + ".mask");
4712 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
4713 }
4714 }
4715
4716 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
4717 // "icmp (and X, mask), cst"
4718 uint64_t ShAmt = 0;
4719 if (Op0->hasOneUse() &&
4720 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
4721 match(Op1, m_ConstantInt(Cst1)) &&
4722 // Only do this when A has multiple uses. This is most important to do
4723 // when it exposes other optimizations.
4724 !A->hasOneUse()) {
4725 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
4726
4727 if (ShAmt < ASize) {
4728 APInt MaskV =
4729 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
4730 MaskV <<= ShAmt;
4731
4732 APInt CmpV = Cst1->getValue().zext(ASize);
4733 CmpV <<= ShAmt;
4734
4735 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
4736 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
4737 }
4738 }
4739
4740 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I))
4741 return ICmp;
4742
4743 // Canonicalize checking for a power-of-2-or-zero value:
4744 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
4745 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
4746 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
4747 m_Deferred(A)))) ||
4748 !match(Op1, m_ZeroInt()))
4749 A = nullptr;
4750
4751 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
4752 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
4753 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
4754 A = Op1;
4755 else if (match(Op1,
4756 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
4757 A = Op0;
4758
4759 if (A) {
4760 Type *Ty = A->getType();
4761 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
4762 return Pred == ICmpInst::ICMP_EQ
4763 ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2))
4764 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1));
4765 }
4766
4767 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the
4768 // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",
4769 // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps
4770 // of instcombine.
4771 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
4772 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
4773 match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
4774 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
4775 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
4776 APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
4777 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
4778 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
4779 : ICmpInst::ICMP_UGE,
4780 Add, ConstantInt::get(A->getType(), C.shl(1)));
4781 }
4782
4783 // Canonicalize:
4784 // Assume B_Pow2 != 0
4785 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
4786 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
4787 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
4788 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
4789 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
4790 ConstantInt::getNullValue(Op0->getType()));
4791
4792 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
4793 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
4794 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
4795 ConstantInt::getNullValue(Op1->getType()));
4796
4797 return nullptr;
4798 }
4799
foldICmpWithTrunc(ICmpInst & ICmp,InstCombiner::BuilderTy & Builder)4800 static Instruction *foldICmpWithTrunc(ICmpInst &ICmp,
4801 InstCombiner::BuilderTy &Builder) {
4802 ICmpInst::Predicate Pred = ICmp.getPredicate();
4803 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
4804
4805 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
4806 // The trunc masks high bits while the compare may effectively mask low bits.
4807 Value *X;
4808 const APInt *C;
4809 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
4810 return nullptr;
4811
4812 // This matches patterns corresponding to tests of the signbit as well as:
4813 // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)
4814 // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)
4815 APInt Mask;
4816 if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {
4817 Value *And = Builder.CreateAnd(X, Mask);
4818 Constant *Zero = ConstantInt::getNullValue(X->getType());
4819 return new ICmpInst(Pred, And, Zero);
4820 }
4821
4822 unsigned SrcBits = X->getType()->getScalarSizeInBits();
4823 if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {
4824 // If C is a negative power-of-2 (high-bit mask):
4825 // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)
4826 Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));
4827 Value *And = Builder.CreateAnd(X, MaskC);
4828 return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);
4829 }
4830
4831 if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {
4832 // If C is not-of-power-of-2 (one clear bit):
4833 // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)
4834 Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));
4835 Value *And = Builder.CreateAnd(X, MaskC);
4836 return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);
4837 }
4838
4839 return nullptr;
4840 }
4841
foldICmpWithZextOrSext(ICmpInst & ICmp)4842 Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
4843 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
4844 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
4845 Value *X;
4846 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
4847 return nullptr;
4848
4849 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
4850 bool IsSignedCmp = ICmp.isSigned();
4851
4852 // icmp Pred (ext X), (ext Y)
4853 Value *Y;
4854 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
4855 bool IsZext0 = isa<ZExtOperator>(ICmp.getOperand(0));
4856 bool IsZext1 = isa<ZExtOperator>(ICmp.getOperand(1));
4857
4858 // If we have mismatched casts, treat the zext of a non-negative source as
4859 // a sext to simulate matching casts. Otherwise, we are done.
4860 // TODO: Can we handle some predicates (equality) without non-negative?
4861 if (IsZext0 != IsZext1) {
4862 if ((IsZext0 && isKnownNonNegative(X, DL, 0, &AC, &ICmp, &DT)) ||
4863 (IsZext1 && isKnownNonNegative(Y, DL, 0, &AC, &ICmp, &DT)))
4864 IsSignedExt = true;
4865 else
4866 return nullptr;
4867 }
4868
4869 // Not an extension from the same type?
4870 Type *XTy = X->getType(), *YTy = Y->getType();
4871 if (XTy != YTy) {
4872 // One of the casts must have one use because we are creating a new cast.
4873 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
4874 return nullptr;
4875 // Extend the narrower operand to the type of the wider operand.
4876 CastInst::CastOps CastOpcode =
4877 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
4878 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
4879 X = Builder.CreateCast(CastOpcode, X, YTy);
4880 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
4881 Y = Builder.CreateCast(CastOpcode, Y, XTy);
4882 else
4883 return nullptr;
4884 }
4885
4886 // (zext X) == (zext Y) --> X == Y
4887 // (sext X) == (sext Y) --> X == Y
4888 if (ICmp.isEquality())
4889 return new ICmpInst(ICmp.getPredicate(), X, Y);
4890
4891 // A signed comparison of sign extended values simplifies into a
4892 // signed comparison.
4893 if (IsSignedCmp && IsSignedExt)
4894 return new ICmpInst(ICmp.getPredicate(), X, Y);
4895
4896 // The other three cases all fold into an unsigned comparison.
4897 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
4898 }
4899
4900 // Below here, we are only folding a compare with constant.
4901 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
4902 if (!C)
4903 return nullptr;
4904
4905 // Compute the constant that would happen if we truncated to SrcTy then
4906 // re-extended to DestTy.
4907 Type *SrcTy = CastOp0->getSrcTy();
4908 Type *DestTy = CastOp0->getDestTy();
4909 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
4910 Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy);
4911
4912 // If the re-extended constant didn't change...
4913 if (Res2 == C) {
4914 if (ICmp.isEquality())
4915 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4916
4917 // A signed comparison of sign extended values simplifies into a
4918 // signed comparison.
4919 if (IsSignedExt && IsSignedCmp)
4920 return new ICmpInst(ICmp.getPredicate(), X, Res1);
4921
4922 // The other three cases all fold into an unsigned comparison.
4923 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1);
4924 }
4925
4926 // The re-extended constant changed, partly changed (in the case of a vector),
4927 // or could not be determined to be equal (in the case of a constant
4928 // expression), so the constant cannot be represented in the shorter type.
4929 // All the cases that fold to true or false will have already been handled
4930 // by simplifyICmpInst, so only deal with the tricky case.
4931 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
4932 return nullptr;
4933
4934 // Is source op positive?
4935 // icmp ult (sext X), C --> icmp sgt X, -1
4936 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
4937 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
4938
4939 // Is source op negative?
4940 // icmp ugt (sext X), C --> icmp slt X, 0
4941 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
4942 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
4943 }
4944
4945 /// Handle icmp (cast x), (cast or constant).
foldICmpWithCastOp(ICmpInst & ICmp)4946 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
4947 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
4948 // icmp compares only pointer's value.
4949 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
4950 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
4951 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
4952 if (SimplifiedOp0 || SimplifiedOp1)
4953 return new ICmpInst(ICmp.getPredicate(),
4954 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
4955 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
4956
4957 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
4958 if (!CastOp0)
4959 return nullptr;
4960 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
4961 return nullptr;
4962
4963 Value *Op0Src = CastOp0->getOperand(0);
4964 Type *SrcTy = CastOp0->getSrcTy();
4965 Type *DestTy = CastOp0->getDestTy();
4966
4967 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
4968 // integer type is the same size as the pointer type.
4969 auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
4970 if (isa<VectorType>(SrcTy)) {
4971 SrcTy = cast<VectorType>(SrcTy)->getElementType();
4972 DestTy = cast<VectorType>(DestTy)->getElementType();
4973 }
4974 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
4975 };
4976 if (CastOp0->getOpcode() == Instruction::PtrToInt &&
4977 CompatibleSizes(SrcTy, DestTy)) {
4978 Value *NewOp1 = nullptr;
4979 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
4980 Value *PtrSrc = PtrToIntOp1->getOperand(0);
4981 if (PtrSrc->getType()->getPointerAddressSpace() ==
4982 Op0Src->getType()->getPointerAddressSpace()) {
4983 NewOp1 = PtrToIntOp1->getOperand(0);
4984 // If the pointer types don't match, insert a bitcast.
4985 if (Op0Src->getType() != NewOp1->getType())
4986 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType());
4987 }
4988 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
4989 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
4990 }
4991
4992 if (NewOp1)
4993 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
4994 }
4995
4996 if (Instruction *R = foldICmpWithTrunc(ICmp, Builder))
4997 return R;
4998
4999 return foldICmpWithZextOrSext(ICmp);
5000 }
5001
isNeutralValue(Instruction::BinaryOps BinaryOp,Value * RHS,bool IsSigned)5002 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {
5003 switch (BinaryOp) {
5004 default:
5005 llvm_unreachable("Unsupported binary op");
5006 case Instruction::Add:
5007 case Instruction::Sub:
5008 return match(RHS, m_Zero());
5009 case Instruction::Mul:
5010 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
5011 match(RHS, m_One());
5012 }
5013 }
5014
5015 OverflowResult
computeOverflow(Instruction::BinaryOps BinaryOp,bool IsSigned,Value * LHS,Value * RHS,Instruction * CxtI) const5016 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
5017 bool IsSigned, Value *LHS, Value *RHS,
5018 Instruction *CxtI) const {
5019 switch (BinaryOp) {
5020 default:
5021 llvm_unreachable("Unsupported binary op");
5022 case Instruction::Add:
5023 if (IsSigned)
5024 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
5025 else
5026 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
5027 case Instruction::Sub:
5028 if (IsSigned)
5029 return computeOverflowForSignedSub(LHS, RHS, CxtI);
5030 else
5031 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
5032 case Instruction::Mul:
5033 if (IsSigned)
5034 return computeOverflowForSignedMul(LHS, RHS, CxtI);
5035 else
5036 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
5037 }
5038 }
5039
OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,bool IsSigned,Value * LHS,Value * RHS,Instruction & OrigI,Value * & Result,Constant * & Overflow)5040 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
5041 bool IsSigned, Value *LHS,
5042 Value *RHS, Instruction &OrigI,
5043 Value *&Result,
5044 Constant *&Overflow) {
5045 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
5046 std::swap(LHS, RHS);
5047
5048 // If the overflow check was an add followed by a compare, the insertion point
5049 // may be pointing to the compare. We want to insert the new instructions
5050 // before the add in case there are uses of the add between the add and the
5051 // compare.
5052 Builder.SetInsertPoint(&OrigI);
5053
5054 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
5055 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
5056 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
5057
5058 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
5059 Result = LHS;
5060 Overflow = ConstantInt::getFalse(OverflowTy);
5061 return true;
5062 }
5063
5064 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
5065 case OverflowResult::MayOverflow:
5066 return false;
5067 case OverflowResult::AlwaysOverflowsLow:
5068 case OverflowResult::AlwaysOverflowsHigh:
5069 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5070 Result->takeName(&OrigI);
5071 Overflow = ConstantInt::getTrue(OverflowTy);
5072 return true;
5073 case OverflowResult::NeverOverflows:
5074 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
5075 Result->takeName(&OrigI);
5076 Overflow = ConstantInt::getFalse(OverflowTy);
5077 if (auto *Inst = dyn_cast<Instruction>(Result)) {
5078 if (IsSigned)
5079 Inst->setHasNoSignedWrap();
5080 else
5081 Inst->setHasNoUnsignedWrap();
5082 }
5083 return true;
5084 }
5085
5086 llvm_unreachable("Unexpected overflow result");
5087 }
5088
5089 /// Recognize and process idiom involving test for multiplication
5090 /// overflow.
5091 ///
5092 /// The caller has matched a pattern of the form:
5093 /// I = cmp u (mul(zext A, zext B), V
5094 /// The function checks if this is a test for overflow and if so replaces
5095 /// multiplication with call to 'mul.with.overflow' intrinsic.
5096 ///
5097 /// \param I Compare instruction.
5098 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of
5099 /// the compare instruction. Must be of integer type.
5100 /// \param OtherVal The other argument of compare instruction.
5101 /// \returns Instruction which must replace the compare instruction, NULL if no
5102 /// replacement required.
processUMulZExtIdiom(ICmpInst & I,Value * MulVal,Value * OtherVal,InstCombinerImpl & IC)5103 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
5104 Value *OtherVal,
5105 InstCombinerImpl &IC) {
5106 // Don't bother doing this transformation for pointers, don't do it for
5107 // vectors.
5108 if (!isa<IntegerType>(MulVal->getType()))
5109 return nullptr;
5110
5111 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
5112 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
5113 auto *MulInstr = dyn_cast<Instruction>(MulVal);
5114 if (!MulInstr)
5115 return nullptr;
5116 assert(MulInstr->getOpcode() == Instruction::Mul);
5117
5118 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
5119 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
5120 assert(LHS->getOpcode() == Instruction::ZExt);
5121 assert(RHS->getOpcode() == Instruction::ZExt);
5122 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
5123
5124 // Calculate type and width of the result produced by mul.with.overflow.
5125 Type *TyA = A->getType(), *TyB = B->getType();
5126 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
5127 WidthB = TyB->getPrimitiveSizeInBits();
5128 unsigned MulWidth;
5129 Type *MulType;
5130 if (WidthB > WidthA) {
5131 MulWidth = WidthB;
5132 MulType = TyB;
5133 } else {
5134 MulWidth = WidthA;
5135 MulType = TyA;
5136 }
5137
5138 // In order to replace the original mul with a narrower mul.with.overflow,
5139 // all uses must ignore upper bits of the product. The number of used low
5140 // bits must be not greater than the width of mul.with.overflow.
5141 if (MulVal->hasNUsesOrMore(2))
5142 for (User *U : MulVal->users()) {
5143 if (U == &I)
5144 continue;
5145 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5146 // Check if truncation ignores bits above MulWidth.
5147 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
5148 if (TruncWidth > MulWidth)
5149 return nullptr;
5150 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5151 // Check if AND ignores bits above MulWidth.
5152 if (BO->getOpcode() != Instruction::And)
5153 return nullptr;
5154 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5155 const APInt &CVal = CI->getValue();
5156 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
5157 return nullptr;
5158 } else {
5159 // In this case we could have the operand of the binary operation
5160 // being defined in another block, and performing the replacement
5161 // could break the dominance relation.
5162 return nullptr;
5163 }
5164 } else {
5165 // Other uses prohibit this transformation.
5166 return nullptr;
5167 }
5168 }
5169
5170 // Recognize patterns
5171 switch (I.getPredicate()) {
5172 case ICmpInst::ICMP_EQ:
5173 case ICmpInst::ICMP_NE:
5174 // Recognize pattern:
5175 // mulval = mul(zext A, zext B)
5176 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
5177 ConstantInt *CI;
5178 Value *ValToMask;
5179 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
5180 if (ValToMask != MulVal)
5181 return nullptr;
5182 const APInt &CVal = CI->getValue() + 1;
5183 if (CVal.isPowerOf2()) {
5184 unsigned MaskWidth = CVal.logBase2();
5185 if (MaskWidth == MulWidth)
5186 break; // Recognized
5187 }
5188 }
5189 return nullptr;
5190
5191 case ICmpInst::ICMP_UGT:
5192 // Recognize pattern:
5193 // mulval = mul(zext A, zext B)
5194 // cmp ugt mulval, max
5195 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5196 APInt MaxVal = APInt::getMaxValue(MulWidth);
5197 MaxVal = MaxVal.zext(CI->getBitWidth());
5198 if (MaxVal.eq(CI->getValue()))
5199 break; // Recognized
5200 }
5201 return nullptr;
5202
5203 case ICmpInst::ICMP_UGE:
5204 // Recognize pattern:
5205 // mulval = mul(zext A, zext B)
5206 // cmp uge mulval, max+1
5207 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5208 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
5209 if (MaxVal.eq(CI->getValue()))
5210 break; // Recognized
5211 }
5212 return nullptr;
5213
5214 case ICmpInst::ICMP_ULE:
5215 // Recognize pattern:
5216 // mulval = mul(zext A, zext B)
5217 // cmp ule mulval, max
5218 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5219 APInt MaxVal = APInt::getMaxValue(MulWidth);
5220 MaxVal = MaxVal.zext(CI->getBitWidth());
5221 if (MaxVal.eq(CI->getValue()))
5222 break; // Recognized
5223 }
5224 return nullptr;
5225
5226 case ICmpInst::ICMP_ULT:
5227 // Recognize pattern:
5228 // mulval = mul(zext A, zext B)
5229 // cmp ule mulval, max + 1
5230 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
5231 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
5232 if (MaxVal.eq(CI->getValue()))
5233 break; // Recognized
5234 }
5235 return nullptr;
5236
5237 default:
5238 return nullptr;
5239 }
5240
5241 InstCombiner::BuilderTy &Builder = IC.Builder;
5242 Builder.SetInsertPoint(MulInstr);
5243
5244 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
5245 Value *MulA = A, *MulB = B;
5246 if (WidthA < MulWidth)
5247 MulA = Builder.CreateZExt(A, MulType);
5248 if (WidthB < MulWidth)
5249 MulB = Builder.CreateZExt(B, MulType);
5250 Function *F = Intrinsic::getDeclaration(
5251 I.getModule(), Intrinsic::umul_with_overflow, MulType);
5252 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
5253 IC.addToWorklist(MulInstr);
5254
5255 // If there are uses of mul result other than the comparison, we know that
5256 // they are truncation or binary AND. Change them to use result of
5257 // mul.with.overflow and adjust properly mask/size.
5258 if (MulVal->hasNUsesOrMore(2)) {
5259 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
5260 for (User *U : make_early_inc_range(MulVal->users())) {
5261 if (U == &I || U == OtherVal)
5262 continue;
5263 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
5264 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
5265 IC.replaceInstUsesWith(*TI, Mul);
5266 else
5267 TI->setOperand(0, Mul);
5268 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
5269 assert(BO->getOpcode() == Instruction::And);
5270 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
5271 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
5272 APInt ShortMask = CI->getValue().trunc(MulWidth);
5273 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
5274 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
5275 IC.replaceInstUsesWith(*BO, Zext);
5276 } else {
5277 llvm_unreachable("Unexpected Binary operation");
5278 }
5279 IC.addToWorklist(cast<Instruction>(U));
5280 }
5281 }
5282 if (isa<Instruction>(OtherVal))
5283 IC.addToWorklist(cast<Instruction>(OtherVal));
5284
5285 // The original icmp gets replaced with the overflow value, maybe inverted
5286 // depending on predicate.
5287 bool Inverse = false;
5288 switch (I.getPredicate()) {
5289 case ICmpInst::ICMP_NE:
5290 break;
5291 case ICmpInst::ICMP_EQ:
5292 Inverse = true;
5293 break;
5294 case ICmpInst::ICMP_UGT:
5295 case ICmpInst::ICMP_UGE:
5296 if (I.getOperand(0) == MulVal)
5297 break;
5298 Inverse = true;
5299 break;
5300 case ICmpInst::ICMP_ULT:
5301 case ICmpInst::ICMP_ULE:
5302 if (I.getOperand(1) == MulVal)
5303 break;
5304 Inverse = true;
5305 break;
5306 default:
5307 llvm_unreachable("Unexpected predicate");
5308 }
5309 if (Inverse) {
5310 Value *Res = Builder.CreateExtractValue(Call, 1);
5311 return BinaryOperator::CreateNot(Res);
5312 }
5313
5314 return ExtractValueInst::Create(Call, 1);
5315 }
5316
5317 /// When performing a comparison against a constant, it is possible that not all
5318 /// the bits in the LHS are demanded. This helper method computes the mask that
5319 /// IS demanded.
getDemandedBitsLHSMask(ICmpInst & I,unsigned BitWidth)5320 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
5321 const APInt *RHS;
5322 if (!match(I.getOperand(1), m_APInt(RHS)))
5323 return APInt::getAllOnes(BitWidth);
5324
5325 // If this is a normal comparison, it demands all bits. If it is a sign bit
5326 // comparison, it only demands the sign bit.
5327 bool UnusedBit;
5328 if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
5329 return APInt::getSignMask(BitWidth);
5330
5331 switch (I.getPredicate()) {
5332 // For a UGT comparison, we don't care about any bits that
5333 // correspond to the trailing ones of the comparand. The value of these
5334 // bits doesn't impact the outcome of the comparison, because any value
5335 // greater than the RHS must differ in a bit higher than these due to carry.
5336 case ICmpInst::ICMP_UGT:
5337 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes());
5338
5339 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
5340 // Any value less than the RHS must differ in a higher bit because of carries.
5341 case ICmpInst::ICMP_ULT:
5342 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros());
5343
5344 default:
5345 return APInt::getAllOnes(BitWidth);
5346 }
5347 }
5348
5349 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst
5350 /// should be swapped.
5351 /// The decision is based on how many times these two operands are reused
5352 /// as subtract operands and their positions in those instructions.
5353 /// The rationale is that several architectures use the same instruction for
5354 /// both subtract and cmp. Thus, it is better if the order of those operands
5355 /// match.
5356 /// \return true if Op0 and Op1 should be swapped.
swapMayExposeCSEOpportunities(const Value * Op0,const Value * Op1)5357 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) {
5358 // Filter out pointer values as those cannot appear directly in subtract.
5359 // FIXME: we may want to go through inttoptrs or bitcasts.
5360 if (Op0->getType()->isPointerTy())
5361 return false;
5362 // If a subtract already has the same operands as a compare, swapping would be
5363 // bad. If a subtract has the same operands as a compare but in reverse order,
5364 // then swapping is good.
5365 int GoodToSwap = 0;
5366 for (const User *U : Op0->users()) {
5367 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
5368 GoodToSwap++;
5369 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
5370 GoodToSwap--;
5371 }
5372 return GoodToSwap > 0;
5373 }
5374
5375 /// Check that one use is in the same block as the definition and all
5376 /// other uses are in blocks dominated by a given block.
5377 ///
5378 /// \param DI Definition
5379 /// \param UI Use
5380 /// \param DB Block that must dominate all uses of \p DI outside
5381 /// the parent block
5382 /// \return true when \p UI is the only use of \p DI in the parent block
5383 /// and all other uses of \p DI are in blocks dominated by \p DB.
5384 ///
dominatesAllUses(const Instruction * DI,const Instruction * UI,const BasicBlock * DB) const5385 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
5386 const Instruction *UI,
5387 const BasicBlock *DB) const {
5388 assert(DI && UI && "Instruction not defined\n");
5389 // Ignore incomplete definitions.
5390 if (!DI->getParent())
5391 return false;
5392 // DI and UI must be in the same block.
5393 if (DI->getParent() != UI->getParent())
5394 return false;
5395 // Protect from self-referencing blocks.
5396 if (DI->getParent() == DB)
5397 return false;
5398 for (const User *U : DI->users()) {
5399 auto *Usr = cast<Instruction>(U);
5400 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
5401 return false;
5402 }
5403 return true;
5404 }
5405
5406 /// Return true when the instruction sequence within a block is select-cmp-br.
isChainSelectCmpBranch(const SelectInst * SI)5407 static bool isChainSelectCmpBranch(const SelectInst *SI) {
5408 const BasicBlock *BB = SI->getParent();
5409 if (!BB)
5410 return false;
5411 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
5412 if (!BI || BI->getNumSuccessors() != 2)
5413 return false;
5414 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
5415 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
5416 return false;
5417 return true;
5418 }
5419
5420 /// True when a select result is replaced by one of its operands
5421 /// in select-icmp sequence. This will eventually result in the elimination
5422 /// of the select.
5423 ///
5424 /// \param SI Select instruction
5425 /// \param Icmp Compare instruction
5426 /// \param SIOpd Operand that replaces the select
5427 ///
5428 /// Notes:
5429 /// - The replacement is global and requires dominator information
5430 /// - The caller is responsible for the actual replacement
5431 ///
5432 /// Example:
5433 ///
5434 /// entry:
5435 /// %4 = select i1 %3, %C* %0, %C* null
5436 /// %5 = icmp eq %C* %4, null
5437 /// br i1 %5, label %9, label %7
5438 /// ...
5439 /// ; <label>:7 ; preds = %entry
5440 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
5441 /// ...
5442 ///
5443 /// can be transformed to
5444 ///
5445 /// %5 = icmp eq %C* %0, null
5446 /// %6 = select i1 %3, i1 %5, i1 true
5447 /// br i1 %6, label %9, label %7
5448 /// ...
5449 /// ; <label>:7 ; preds = %entry
5450 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
5451 ///
5452 /// Similar when the first operand of the select is a constant or/and
5453 /// the compare is for not equal rather than equal.
5454 ///
5455 /// NOTE: The function is only called when the select and compare constants
5456 /// are equal, the optimization can work only for EQ predicates. This is not a
5457 /// major restriction since a NE compare should be 'normalized' to an equal
5458 /// compare, which usually happens in the combiner and test case
5459 /// select-cmp-br.ll checks for it.
replacedSelectWithOperand(SelectInst * SI,const ICmpInst * Icmp,const unsigned SIOpd)5460 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
5461 const ICmpInst *Icmp,
5462 const unsigned SIOpd) {
5463 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
5464 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
5465 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
5466 // The check for the single predecessor is not the best that can be
5467 // done. But it protects efficiently against cases like when SI's
5468 // home block has two successors, Succ and Succ1, and Succ1 predecessor
5469 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
5470 // replaced can be reached on either path. So the uniqueness check
5471 // guarantees that the path all uses of SI (outside SI's parent) are on
5472 // is disjoint from all other paths out of SI. But that information
5473 // is more expensive to compute, and the trade-off here is in favor
5474 // of compile-time. It should also be noticed that we check for a single
5475 // predecessor and not only uniqueness. This to handle the situation when
5476 // Succ and Succ1 points to the same basic block.
5477 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
5478 NumSel++;
5479 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
5480 return true;
5481 }
5482 }
5483 return false;
5484 }
5485
5486 /// Try to fold the comparison based on range information we can get by checking
5487 /// whether bits are known to be zero or one in the inputs.
foldICmpUsingKnownBits(ICmpInst & I)5488 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
5489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5490 Type *Ty = Op0->getType();
5491 ICmpInst::Predicate Pred = I.getPredicate();
5492
5493 // Get scalar or pointer size.
5494 unsigned BitWidth = Ty->isIntOrIntVectorTy()
5495 ? Ty->getScalarSizeInBits()
5496 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
5497
5498 if (!BitWidth)
5499 return nullptr;
5500
5501 KnownBits Op0Known(BitWidth);
5502 KnownBits Op1Known(BitWidth);
5503
5504 if (SimplifyDemandedBits(&I, 0,
5505 getDemandedBitsLHSMask(I, BitWidth),
5506 Op0Known, 0))
5507 return &I;
5508
5509 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0))
5510 return &I;
5511
5512 // Given the known and unknown bits, compute a range that the LHS could be
5513 // in. Compute the Min, Max and RHS values based on the known bits. For the
5514 // EQ and NE we use unsigned values.
5515 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5516 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5517 if (I.isSigned()) {
5518 Op0Min = Op0Known.getSignedMinValue();
5519 Op0Max = Op0Known.getSignedMaxValue();
5520 Op1Min = Op1Known.getSignedMinValue();
5521 Op1Max = Op1Known.getSignedMaxValue();
5522 } else {
5523 Op0Min = Op0Known.getMinValue();
5524 Op0Max = Op0Known.getMaxValue();
5525 Op1Min = Op1Known.getMinValue();
5526 Op1Max = Op1Known.getMaxValue();
5527 }
5528
5529 // If Min and Max are known to be the same, then SimplifyDemandedBits figured
5530 // out that the LHS or RHS is a constant. Constant fold this now, so that
5531 // code below can assume that Min != Max.
5532 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5533 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
5534 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5535 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
5536
5537 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
5538 // min/max canonical compare with some other compare. That could lead to
5539 // conflict with select canonicalization and infinite looping.
5540 // FIXME: This constraint may go away if min/max intrinsics are canonical.
5541 auto isMinMaxCmp = [&](Instruction &Cmp) {
5542 if (!Cmp.hasOneUse())
5543 return false;
5544 Value *A, *B;
5545 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
5546 if (!SelectPatternResult::isMinOrMax(SPF))
5547 return false;
5548 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
5549 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
5550 };
5551 if (!isMinMaxCmp(I)) {
5552 switch (Pred) {
5553 default:
5554 break;
5555 case ICmpInst::ICMP_ULT: {
5556 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
5557 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5558 const APInt *CmpC;
5559 if (match(Op1, m_APInt(CmpC))) {
5560 // A <u C -> A == C-1 if min(A)+1 == C
5561 if (*CmpC == Op0Min + 1)
5562 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5563 ConstantInt::get(Op1->getType(), *CmpC - 1));
5564 // X <u C --> X == 0, if the number of zero bits in the bottom of X
5565 // exceeds the log2 of C.
5566 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
5567 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5568 Constant::getNullValue(Op1->getType()));
5569 }
5570 break;
5571 }
5572 case ICmpInst::ICMP_UGT: {
5573 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
5574 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5575 const APInt *CmpC;
5576 if (match(Op1, m_APInt(CmpC))) {
5577 // A >u C -> A == C+1 if max(a)-1 == C
5578 if (*CmpC == Op0Max - 1)
5579 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5580 ConstantInt::get(Op1->getType(), *CmpC + 1));
5581 // X >u C --> X != 0, if the number of zero bits in the bottom of X
5582 // exceeds the log2 of C.
5583 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
5584 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
5585 Constant::getNullValue(Op1->getType()));
5586 }
5587 break;
5588 }
5589 case ICmpInst::ICMP_SLT: {
5590 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
5591 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5592 const APInt *CmpC;
5593 if (match(Op1, m_APInt(CmpC))) {
5594 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
5595 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5596 ConstantInt::get(Op1->getType(), *CmpC - 1));
5597 }
5598 break;
5599 }
5600 case ICmpInst::ICMP_SGT: {
5601 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
5602 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5603 const APInt *CmpC;
5604 if (match(Op1, m_APInt(CmpC))) {
5605 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
5606 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
5607 ConstantInt::get(Op1->getType(), *CmpC + 1));
5608 }
5609 break;
5610 }
5611 }
5612 }
5613
5614 // Based on the range information we know about the LHS, see if we can
5615 // simplify this comparison. For example, (x&4) < 8 is always true.
5616 switch (Pred) {
5617 default:
5618 llvm_unreachable("Unknown icmp opcode!");
5619 case ICmpInst::ICMP_EQ:
5620 case ICmpInst::ICMP_NE: {
5621 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5622 return replaceInstUsesWith(
5623 I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));
5624
5625 // If all bits are known zero except for one, then we know at most one bit
5626 // is set. If the comparison is against zero, then this is a check to see if
5627 // *that* bit is set.
5628 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
5629 if (Op1Known.isZero()) {
5630 // If the LHS is an AND with the same constant, look through it.
5631 Value *LHS = nullptr;
5632 const APInt *LHSC;
5633 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
5634 *LHSC != Op0KnownZeroInverted)
5635 LHS = Op0;
5636
5637 Value *X;
5638 const APInt *C1;
5639 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
5640 Type *XTy = X->getType();
5641 unsigned Log2C1 = C1->countTrailingZeros();
5642 APInt C2 = Op0KnownZeroInverted;
5643 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
5644 if (C2Pow2.isPowerOf2()) {
5645 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
5646 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
5647 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
5648 unsigned Log2C2 = C2Pow2.countTrailingZeros();
5649 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
5650 auto NewPred =
5651 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
5652 return new ICmpInst(NewPred, X, CmpC);
5653 }
5654 }
5655 }
5656 break;
5657 }
5658 case ICmpInst::ICMP_ULT: {
5659 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
5660 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5661 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
5662 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5663 break;
5664 }
5665 case ICmpInst::ICMP_UGT: {
5666 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
5667 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5668 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
5669 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5670 break;
5671 }
5672 case ICmpInst::ICMP_SLT: {
5673 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
5674 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5675 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
5676 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5677 break;
5678 }
5679 case ICmpInst::ICMP_SGT: {
5680 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
5681 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5682 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
5683 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5684 break;
5685 }
5686 case ICmpInst::ICMP_SGE:
5687 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
5688 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
5689 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5690 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
5691 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5692 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
5693 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5694 break;
5695 case ICmpInst::ICMP_SLE:
5696 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
5697 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
5698 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5699 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
5700 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5701 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
5702 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5703 break;
5704 case ICmpInst::ICMP_UGE:
5705 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
5706 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
5707 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5708 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
5709 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5710 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
5711 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5712 break;
5713 case ICmpInst::ICMP_ULE:
5714 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
5715 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
5716 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5717 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
5718 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5719 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
5720 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5721 break;
5722 }
5723
5724 // Turn a signed comparison into an unsigned one if both operands are known to
5725 // have the same sign.
5726 if (I.isSigned() &&
5727 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
5728 (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
5729 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
5730
5731 return nullptr;
5732 }
5733
5734 /// If one operand of an icmp is effectively a bool (value range of {0,1}),
5735 /// then try to reduce patterns based on that limit.
foldICmpUsingBoolRange(ICmpInst & I,InstCombiner::BuilderTy & Builder)5736 static Instruction *foldICmpUsingBoolRange(ICmpInst &I,
5737 InstCombiner::BuilderTy &Builder) {
5738 Value *X, *Y;
5739 ICmpInst::Predicate Pred;
5740
5741 // X must be 0 and bool must be true for "ULT":
5742 // X <u (zext i1 Y) --> (X == 0) & Y
5743 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
5744 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
5745 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
5746
5747 // X must be 0 or bool must be true for "ULE":
5748 // X <=u (sext i1 Y) --> (X == 0) | Y
5749 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
5750 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
5751 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
5752
5753 return nullptr;
5754 }
5755
5756 std::optional<std::pair<CmpInst::Predicate, Constant *>>
getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,Constant * C)5757 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
5758 Constant *C) {
5759 assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
5760 "Only for relational integer predicates.");
5761
5762 Type *Type = C->getType();
5763 bool IsSigned = ICmpInst::isSigned(Pred);
5764
5765 CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
5766 bool WillIncrement =
5767 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
5768
5769 // Check if the constant operand can be safely incremented/decremented
5770 // without overflowing/underflowing.
5771 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
5772 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
5773 };
5774
5775 Constant *SafeReplacementConstant = nullptr;
5776 if (auto *CI = dyn_cast<ConstantInt>(C)) {
5777 // Bail out if the constant can't be safely incremented/decremented.
5778 if (!ConstantIsOk(CI))
5779 return std::nullopt;
5780 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
5781 unsigned NumElts = FVTy->getNumElements();
5782 for (unsigned i = 0; i != NumElts; ++i) {
5783 Constant *Elt = C->getAggregateElement(i);
5784 if (!Elt)
5785 return std::nullopt;
5786
5787 if (isa<UndefValue>(Elt))
5788 continue;
5789
5790 // Bail out if we can't determine if this constant is min/max or if we
5791 // know that this constant is min/max.
5792 auto *CI = dyn_cast<ConstantInt>(Elt);
5793 if (!CI || !ConstantIsOk(CI))
5794 return std::nullopt;
5795
5796 if (!SafeReplacementConstant)
5797 SafeReplacementConstant = CI;
5798 }
5799 } else {
5800 // ConstantExpr?
5801 return std::nullopt;
5802 }
5803
5804 // It may not be safe to change a compare predicate in the presence of
5805 // undefined elements, so replace those elements with the first safe constant
5806 // that we found.
5807 // TODO: in case of poison, it is safe; let's replace undefs only.
5808 if (C->containsUndefOrPoisonElement()) {
5809 assert(SafeReplacementConstant && "Replacement constant not set");
5810 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
5811 }
5812
5813 CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
5814
5815 // Increment or decrement the constant.
5816 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
5817 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
5818
5819 return std::make_pair(NewPred, NewC);
5820 }
5821
5822 /// If we have an icmp le or icmp ge instruction with a constant operand, turn
5823 /// it into the appropriate icmp lt or icmp gt instruction. This transform
5824 /// allows them to be folded in visitICmpInst.
canonicalizeCmpWithConstant(ICmpInst & I)5825 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
5826 ICmpInst::Predicate Pred = I.getPredicate();
5827 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
5828 InstCombiner::isCanonicalPredicate(Pred))
5829 return nullptr;
5830
5831 Value *Op0 = I.getOperand(0);
5832 Value *Op1 = I.getOperand(1);
5833 auto *Op1C = dyn_cast<Constant>(Op1);
5834 if (!Op1C)
5835 return nullptr;
5836
5837 auto FlippedStrictness =
5838 InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
5839 if (!FlippedStrictness)
5840 return nullptr;
5841
5842 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
5843 }
5844
5845 /// If we have a comparison with a non-canonical predicate, if we can update
5846 /// all the users, invert the predicate and adjust all the users.
canonicalizeICmpPredicate(CmpInst & I)5847 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
5848 // Is the predicate already canonical?
5849 CmpInst::Predicate Pred = I.getPredicate();
5850 if (InstCombiner::isCanonicalPredicate(Pred))
5851 return nullptr;
5852
5853 // Can all users be adjusted to predicate inversion?
5854 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
5855 return nullptr;
5856
5857 // Ok, we can canonicalize comparison!
5858 // Let's first invert the comparison's predicate.
5859 I.setPredicate(CmpInst::getInversePredicate(Pred));
5860 I.setName(I.getName() + ".not");
5861
5862 // And, adapt users.
5863 freelyInvertAllUsersOf(&I);
5864
5865 return &I;
5866 }
5867
5868 /// Integer compare with boolean values can always be turned into bitwise ops.
canonicalizeICmpBool(ICmpInst & I,InstCombiner::BuilderTy & Builder)5869 static Instruction *canonicalizeICmpBool(ICmpInst &I,
5870 InstCombiner::BuilderTy &Builder) {
5871 Value *A = I.getOperand(0), *B = I.getOperand(1);
5872 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
5873
5874 // A boolean compared to true/false can be simplified to Op0/true/false in
5875 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
5876 // Cases not handled by InstSimplify are always 'not' of Op0.
5877 if (match(B, m_Zero())) {
5878 switch (I.getPredicate()) {
5879 case CmpInst::ICMP_EQ: // A == 0 -> !A
5880 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
5881 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
5882 return BinaryOperator::CreateNot(A);
5883 default:
5884 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
5885 }
5886 } else if (match(B, m_One())) {
5887 switch (I.getPredicate()) {
5888 case CmpInst::ICMP_NE: // A != 1 -> !A
5889 case CmpInst::ICMP_ULT: // A <u 1 -> !A
5890 case CmpInst::ICMP_SGT: // A >s -1 -> !A
5891 return BinaryOperator::CreateNot(A);
5892 default:
5893 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
5894 }
5895 }
5896
5897 switch (I.getPredicate()) {
5898 default:
5899 llvm_unreachable("Invalid icmp instruction!");
5900 case ICmpInst::ICMP_EQ:
5901 // icmp eq i1 A, B -> ~(A ^ B)
5902 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
5903
5904 case ICmpInst::ICMP_NE:
5905 // icmp ne i1 A, B -> A ^ B
5906 return BinaryOperator::CreateXor(A, B);
5907
5908 case ICmpInst::ICMP_UGT:
5909 // icmp ugt -> icmp ult
5910 std::swap(A, B);
5911 [[fallthrough]];
5912 case ICmpInst::ICMP_ULT:
5913 // icmp ult i1 A, B -> ~A & B
5914 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
5915
5916 case ICmpInst::ICMP_SGT:
5917 // icmp sgt -> icmp slt
5918 std::swap(A, B);
5919 [[fallthrough]];
5920 case ICmpInst::ICMP_SLT:
5921 // icmp slt i1 A, B -> A & ~B
5922 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
5923
5924 case ICmpInst::ICMP_UGE:
5925 // icmp uge -> icmp ule
5926 std::swap(A, B);
5927 [[fallthrough]];
5928 case ICmpInst::ICMP_ULE:
5929 // icmp ule i1 A, B -> ~A | B
5930 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
5931
5932 case ICmpInst::ICMP_SGE:
5933 // icmp sge -> icmp sle
5934 std::swap(A, B);
5935 [[fallthrough]];
5936 case ICmpInst::ICMP_SLE:
5937 // icmp sle i1 A, B -> A | ~B
5938 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
5939 }
5940 }
5941
5942 // Transform pattern like:
5943 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
5944 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
5945 // Into:
5946 // (X l>> Y) != 0
5947 // (X l>> Y) == 0
foldICmpWithHighBitMask(ICmpInst & Cmp,InstCombiner::BuilderTy & Builder)5948 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
5949 InstCombiner::BuilderTy &Builder) {
5950 ICmpInst::Predicate Pred, NewPred;
5951 Value *X, *Y;
5952 if (match(&Cmp,
5953 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
5954 switch (Pred) {
5955 case ICmpInst::ICMP_ULE:
5956 NewPred = ICmpInst::ICMP_NE;
5957 break;
5958 case ICmpInst::ICMP_UGT:
5959 NewPred = ICmpInst::ICMP_EQ;
5960 break;
5961 default:
5962 return nullptr;
5963 }
5964 } else if (match(&Cmp, m_c_ICmp(Pred,
5965 m_OneUse(m_CombineOr(
5966 m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
5967 m_Add(m_Shl(m_One(), m_Value(Y)),
5968 m_AllOnes()))),
5969 m_Value(X)))) {
5970 // The variant with 'add' is not canonical, (the variant with 'not' is)
5971 // we only get it because it has extra uses, and can't be canonicalized,
5972
5973 switch (Pred) {
5974 case ICmpInst::ICMP_ULT:
5975 NewPred = ICmpInst::ICMP_NE;
5976 break;
5977 case ICmpInst::ICMP_UGE:
5978 NewPred = ICmpInst::ICMP_EQ;
5979 break;
5980 default:
5981 return nullptr;
5982 }
5983 } else
5984 return nullptr;
5985
5986 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
5987 Constant *Zero = Constant::getNullValue(NewX->getType());
5988 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
5989 }
5990
foldVectorCmp(CmpInst & Cmp,InstCombiner::BuilderTy & Builder)5991 static Instruction *foldVectorCmp(CmpInst &Cmp,
5992 InstCombiner::BuilderTy &Builder) {
5993 const CmpInst::Predicate Pred = Cmp.getPredicate();
5994 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
5995 Value *V1, *V2;
5996
5997 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
5998 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
5999 if (auto *I = dyn_cast<Instruction>(V))
6000 I->copyIRFlags(&Cmp);
6001 Module *M = Cmp.getModule();
6002 Function *F = Intrinsic::getDeclaration(
6003 M, Intrinsic::experimental_vector_reverse, V->getType());
6004 return CallInst::Create(F, V);
6005 };
6006
6007 if (match(LHS, m_VecReverse(m_Value(V1)))) {
6008 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
6009 if (match(RHS, m_VecReverse(m_Value(V2))) &&
6010 (LHS->hasOneUse() || RHS->hasOneUse()))
6011 return createCmpReverse(Pred, V1, V2);
6012
6013 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
6014 if (LHS->hasOneUse() && isSplatValue(RHS))
6015 return createCmpReverse(Pred, V1, RHS);
6016 }
6017 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
6018 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
6019 return createCmpReverse(Pred, LHS, V2);
6020
6021 ArrayRef<int> M;
6022 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
6023 return nullptr;
6024
6025 // If both arguments of the cmp are shuffles that use the same mask and
6026 // shuffle within a single vector, move the shuffle after the cmp:
6027 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
6028 Type *V1Ty = V1->getType();
6029 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
6030 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
6031 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
6032 return new ShuffleVectorInst(NewCmp, M);
6033 }
6034
6035 // Try to canonicalize compare with splatted operand and splat constant.
6036 // TODO: We could generalize this for more than splats. See/use the code in
6037 // InstCombiner::foldVectorBinop().
6038 Constant *C;
6039 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
6040 return nullptr;
6041
6042 // Length-changing splats are ok, so adjust the constants as needed:
6043 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
6044 Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true);
6045 int MaskSplatIndex;
6046 if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) {
6047 // We allow undefs in matching, but this transform removes those for safety.
6048 // Demanded elements analysis should be able to recover some/all of that.
6049 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
6050 ScalarC);
6051 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
6052 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
6053 return new ShuffleVectorInst(NewCmp, NewM);
6054 }
6055
6056 return nullptr;
6057 }
6058
6059 // extract(uadd.with.overflow(A, B), 0) ult A
6060 // -> extract(uadd.with.overflow(A, B), 1)
foldICmpOfUAddOv(ICmpInst & I)6061 static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
6062 CmpInst::Predicate Pred = I.getPredicate();
6063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6064
6065 Value *UAddOv;
6066 Value *A, *B;
6067 auto UAddOvResultPat = m_ExtractValue<0>(
6068 m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
6069 if (match(Op0, UAddOvResultPat) &&
6070 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
6071 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
6072 (match(A, m_One()) || match(B, m_One()))) ||
6073 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
6074 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
6075 // extract(uadd.with.overflow(A, B), 0) < A
6076 // extract(uadd.with.overflow(A, 1), 0) == 0
6077 // extract(uadd.with.overflow(A, -1), 0) != -1
6078 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
6079 else if (match(Op1, UAddOvResultPat) &&
6080 Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))
6081 // A > extract(uadd.with.overflow(A, B), 0)
6082 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
6083 else
6084 return nullptr;
6085
6086 return ExtractValueInst::Create(UAddOv, 1);
6087 }
6088
foldICmpInvariantGroup(ICmpInst & I)6089 static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
6090 if (!I.getOperand(0)->getType()->isPointerTy() ||
6091 NullPointerIsDefined(
6092 I.getParent()->getParent(),
6093 I.getOperand(0)->getType()->getPointerAddressSpace())) {
6094 return nullptr;
6095 }
6096 Instruction *Op;
6097 if (match(I.getOperand(0), m_Instruction(Op)) &&
6098 match(I.getOperand(1), m_Zero()) &&
6099 Op->isLaunderOrStripInvariantGroup()) {
6100 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
6101 Op->getOperand(0), I.getOperand(1));
6102 }
6103 return nullptr;
6104 }
6105
6106 /// This function folds patterns produced by lowering of reduce idioms, such as
6107 /// llvm.vector.reduce.and which are lowered into instruction chains. This code
6108 /// attempts to generate fewer number of scalar comparisons instead of vector
6109 /// comparisons when possible.
foldReductionIdiom(ICmpInst & I,InstCombiner::BuilderTy & Builder,const DataLayout & DL)6110 static Instruction *foldReductionIdiom(ICmpInst &I,
6111 InstCombiner::BuilderTy &Builder,
6112 const DataLayout &DL) {
6113 if (I.getType()->isVectorTy())
6114 return nullptr;
6115 ICmpInst::Predicate OuterPred, InnerPred;
6116 Value *LHS, *RHS;
6117
6118 // Match lowering of @llvm.vector.reduce.and. Turn
6119 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
6120 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
6121 /// %res = icmp <pred> i8 %scalar_ne, 0
6122 ///
6123 /// into
6124 ///
6125 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
6126 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
6127 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
6128 ///
6129 /// for <pred> in {ne, eq}.
6130 if (!match(&I, m_ICmp(OuterPred,
6131 m_OneUse(m_BitCast(m_OneUse(
6132 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
6133 m_Zero())))
6134 return nullptr;
6135 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
6136 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
6137 return nullptr;
6138 unsigned NumBits =
6139 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
6140 // TODO: Relax this to "not wider than max legal integer type"?
6141 if (!DL.isLegalInteger(NumBits))
6142 return nullptr;
6143
6144 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
6145 auto *ScalarTy = Builder.getIntNTy(NumBits);
6146 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
6147 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
6148 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
6149 I.getName());
6150 }
6151
6152 return nullptr;
6153 }
6154
visitICmpInst(ICmpInst & I)6155 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
6156 bool Changed = false;
6157 const SimplifyQuery Q = SQ.getWithInstruction(&I);
6158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6159 unsigned Op0Cplxity = getComplexity(Op0);
6160 unsigned Op1Cplxity = getComplexity(Op1);
6161
6162 /// Orders the operands of the compare so that they are listed from most
6163 /// complex to least complex. This puts constants before unary operators,
6164 /// before binary operators.
6165 if (Op0Cplxity < Op1Cplxity ||
6166 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
6167 I.swapOperands();
6168 std::swap(Op0, Op1);
6169 Changed = true;
6170 }
6171
6172 if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
6173 return replaceInstUsesWith(I, V);
6174
6175 // Comparing -val or val with non-zero is the same as just comparing val
6176 // ie, abs(val) != 0 -> val != 0
6177 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
6178 Value *Cond, *SelectTrue, *SelectFalse;
6179 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
6180 m_Value(SelectFalse)))) {
6181 if (Value *V = dyn_castNegVal(SelectTrue)) {
6182 if (V == SelectFalse)
6183 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6184 }
6185 else if (Value *V = dyn_castNegVal(SelectFalse)) {
6186 if (V == SelectTrue)
6187 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
6188 }
6189 }
6190 }
6191
6192 if (Op0->getType()->isIntOrIntVectorTy(1))
6193 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
6194 return Res;
6195
6196 if (Instruction *Res = canonicalizeCmpWithConstant(I))
6197 return Res;
6198
6199 if (Instruction *Res = canonicalizeICmpPredicate(I))
6200 return Res;
6201
6202 if (Instruction *Res = foldICmpWithConstant(I))
6203 return Res;
6204
6205 if (Instruction *Res = foldICmpWithDominatingICmp(I))
6206 return Res;
6207
6208 if (Instruction *Res = foldICmpUsingBoolRange(I, Builder))
6209 return Res;
6210
6211 if (Instruction *Res = foldICmpUsingKnownBits(I))
6212 return Res;
6213
6214 // Test if the ICmpInst instruction is used exclusively by a select as
6215 // part of a minimum or maximum operation. If so, refrain from doing
6216 // any other folding. This helps out other analyses which understand
6217 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6218 // and CodeGen. And in this case, at least one of the comparison
6219 // operands has at least one user besides the compare (the select),
6220 // which would often largely negate the benefit of folding anyway.
6221 //
6222 // Do the same for the other patterns recognized by matchSelectPattern.
6223 if (I.hasOneUse())
6224 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
6225 Value *A, *B;
6226 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
6227 if (SPR.Flavor != SPF_UNKNOWN)
6228 return nullptr;
6229 }
6230
6231 // Do this after checking for min/max to prevent infinite looping.
6232 if (Instruction *Res = foldICmpWithZero(I))
6233 return Res;
6234
6235 // FIXME: We only do this after checking for min/max to prevent infinite
6236 // looping caused by a reverse canonicalization of these patterns for min/max.
6237 // FIXME: The organization of folds is a mess. These would naturally go into
6238 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
6239 // down here after the min/max restriction.
6240 ICmpInst::Predicate Pred = I.getPredicate();
6241 const APInt *C;
6242 if (match(Op1, m_APInt(C))) {
6243 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
6244 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
6245 Constant *Zero = Constant::getNullValue(Op0->getType());
6246 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
6247 }
6248
6249 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
6250 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
6251 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
6252 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
6253 }
6254 }
6255
6256 // The folds in here may rely on wrapping flags and special constants, so
6257 // they can break up min/max idioms in some cases but not seemingly similar
6258 // patterns.
6259 // FIXME: It may be possible to enhance select folding to make this
6260 // unnecessary. It may also be moot if we canonicalize to min/max
6261 // intrinsics.
6262 if (Instruction *Res = foldICmpBinOp(I, Q))
6263 return Res;
6264
6265 if (Instruction *Res = foldICmpInstWithConstant(I))
6266 return Res;
6267
6268 // Try to match comparison as a sign bit test. Intentionally do this after
6269 // foldICmpInstWithConstant() to potentially let other folds to happen first.
6270 if (Instruction *New = foldSignBitTest(I))
6271 return New;
6272
6273 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
6274 return Res;
6275
6276 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
6277 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
6278 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
6279 return NI;
6280 if (auto *GEP = dyn_cast<GEPOperator>(Op1))
6281 if (Instruction *NI = foldGEPICmp(GEP, Op0, I.getSwappedPredicate(), I))
6282 return NI;
6283
6284 if (auto *SI = dyn_cast<SelectInst>(Op0))
6285 if (Instruction *NI = foldSelectICmp(I.getPredicate(), SI, Op1, I))
6286 return NI;
6287 if (auto *SI = dyn_cast<SelectInst>(Op1))
6288 if (Instruction *NI = foldSelectICmp(I.getSwappedPredicate(), SI, Op0, I))
6289 return NI;
6290
6291 // Try to optimize equality comparisons against alloca-based pointers.
6292 if (Op0->getType()->isPointerTy() && I.isEquality()) {
6293 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
6294 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
6295 if (Instruction *New = foldAllocaCmp(I, Alloca))
6296 return New;
6297 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
6298 if (Instruction *New = foldAllocaCmp(I, Alloca))
6299 return New;
6300 }
6301
6302 if (Instruction *Res = foldICmpBitCast(I))
6303 return Res;
6304
6305 // TODO: Hoist this above the min/max bailout.
6306 if (Instruction *R = foldICmpWithCastOp(I))
6307 return R;
6308
6309 if (Instruction *Res = foldICmpWithMinMax(I))
6310 return Res;
6311
6312 {
6313 Value *A, *B;
6314 // Transform (A & ~B) == 0 --> (A & B) != 0
6315 // and (A & ~B) != 0 --> (A & B) == 0
6316 // if A is a power of 2.
6317 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
6318 match(Op1, m_Zero()) &&
6319 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
6320 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
6321 Op1);
6322
6323 // ~X < ~Y --> Y < X
6324 // ~X < C --> X > ~C
6325 if (match(Op0, m_Not(m_Value(A)))) {
6326 if (match(Op1, m_Not(m_Value(B))))
6327 return new ICmpInst(I.getPredicate(), B, A);
6328
6329 const APInt *C;
6330 if (match(Op1, m_APInt(C)))
6331 return new ICmpInst(I.getSwappedPredicate(), A,
6332 ConstantInt::get(Op1->getType(), ~(*C)));
6333 }
6334
6335 Instruction *AddI = nullptr;
6336 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
6337 m_Instruction(AddI))) &&
6338 isa<IntegerType>(A->getType())) {
6339 Value *Result;
6340 Constant *Overflow;
6341 // m_UAddWithOverflow can match patterns that do not include an explicit
6342 // "add" instruction, so check the opcode of the matched op.
6343 if (AddI->getOpcode() == Instruction::Add &&
6344 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, A, B, *AddI,
6345 Result, Overflow)) {
6346 replaceInstUsesWith(*AddI, Result);
6347 eraseInstFromFunction(*AddI);
6348 return replaceInstUsesWith(I, Overflow);
6349 }
6350 }
6351
6352 // (zext a) * (zext b) --> llvm.umul.with.overflow.
6353 if (match(Op0, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
6354 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
6355 return R;
6356 }
6357 if (match(Op1, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
6358 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
6359 return R;
6360 }
6361 }
6362
6363 if (Instruction *Res = foldICmpEquality(I))
6364 return Res;
6365
6366 if (Instruction *Res = foldICmpOfUAddOv(I))
6367 return Res;
6368
6369 // The 'cmpxchg' instruction returns an aggregate containing the old value and
6370 // an i1 which indicates whether or not we successfully did the swap.
6371 //
6372 // Replace comparisons between the old value and the expected value with the
6373 // indicator that 'cmpxchg' returns.
6374 //
6375 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
6376 // spuriously fail. In those cases, the old value may equal the expected
6377 // value but it is possible for the swap to not occur.
6378 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6379 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
6380 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
6381 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
6382 !ACXI->isWeak())
6383 return ExtractValueInst::Create(ACXI, 1);
6384
6385 {
6386 Value *X;
6387 const APInt *C;
6388 // icmp X+Cst, X
6389 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
6390 return foldICmpAddOpConst(X, *C, I.getPredicate());
6391
6392 // icmp X, X+Cst
6393 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
6394 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
6395 }
6396
6397 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
6398 return Res;
6399
6400 if (I.getType()->isVectorTy())
6401 if (Instruction *Res = foldVectorCmp(I, Builder))
6402 return Res;
6403
6404 if (Instruction *Res = foldICmpInvariantGroup(I))
6405 return Res;
6406
6407 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
6408 return Res;
6409
6410 return Changed ? &I : nullptr;
6411 }
6412
6413 /// Fold fcmp ([us]itofp x, cst) if possible.
foldFCmpIntToFPConst(FCmpInst & I,Instruction * LHSI,Constant * RHSC)6414 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
6415 Instruction *LHSI,
6416 Constant *RHSC) {
6417 if (!isa<ConstantFP>(RHSC)) return nullptr;
6418 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
6419
6420 // Get the width of the mantissa. We don't want to hack on conversions that
6421 // might lose information from the integer, e.g. "i64 -> float"
6422 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
6423 if (MantissaWidth == -1) return nullptr; // Unknown.
6424
6425 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
6426
6427 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
6428
6429 if (I.isEquality()) {
6430 FCmpInst::Predicate P = I.getPredicate();
6431 bool IsExact = false;
6432 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
6433 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
6434
6435 // If the floating point constant isn't an integer value, we know if we will
6436 // ever compare equal / not equal to it.
6437 if (!IsExact) {
6438 // TODO: Can never be -0.0 and other non-representable values
6439 APFloat RHSRoundInt(RHS);
6440 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
6441 if (RHS != RHSRoundInt) {
6442 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
6443 return replaceInstUsesWith(I, Builder.getFalse());
6444
6445 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
6446 return replaceInstUsesWith(I, Builder.getTrue());
6447 }
6448 }
6449
6450 // TODO: If the constant is exactly representable, is it always OK to do
6451 // equality compares as integer?
6452 }
6453
6454 // Check to see that the input is converted from an integer type that is small
6455 // enough that preserves all bits. TODO: check here for "known" sign bits.
6456 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
6457 unsigned InputSize = IntTy->getScalarSizeInBits();
6458
6459 // Following test does NOT adjust InputSize downwards for signed inputs,
6460 // because the most negative value still requires all the mantissa bits
6461 // to distinguish it from one less than that value.
6462 if ((int)InputSize > MantissaWidth) {
6463 // Conversion would lose accuracy. Check if loss can impact comparison.
6464 int Exp = ilogb(RHS);
6465 if (Exp == APFloat::IEK_Inf) {
6466 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
6467 if (MaxExponent < (int)InputSize - !LHSUnsigned)
6468 // Conversion could create infinity.
6469 return nullptr;
6470 } else {
6471 // Note that if RHS is zero or NaN, then Exp is negative
6472 // and first condition is trivially false.
6473 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
6474 // Conversion could affect comparison.
6475 return nullptr;
6476 }
6477 }
6478
6479 // Otherwise, we can potentially simplify the comparison. We know that it
6480 // will always come through as an integer value and we know the constant is
6481 // not a NAN (it would have been previously simplified).
6482 assert(!RHS.isNaN() && "NaN comparison not already folded!");
6483
6484 ICmpInst::Predicate Pred;
6485 switch (I.getPredicate()) {
6486 default: llvm_unreachable("Unexpected predicate!");
6487 case FCmpInst::FCMP_UEQ:
6488 case FCmpInst::FCMP_OEQ:
6489 Pred = ICmpInst::ICMP_EQ;
6490 break;
6491 case FCmpInst::FCMP_UGT:
6492 case FCmpInst::FCMP_OGT:
6493 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
6494 break;
6495 case FCmpInst::FCMP_UGE:
6496 case FCmpInst::FCMP_OGE:
6497 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
6498 break;
6499 case FCmpInst::FCMP_ULT:
6500 case FCmpInst::FCMP_OLT:
6501 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
6502 break;
6503 case FCmpInst::FCMP_ULE:
6504 case FCmpInst::FCMP_OLE:
6505 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
6506 break;
6507 case FCmpInst::FCMP_UNE:
6508 case FCmpInst::FCMP_ONE:
6509 Pred = ICmpInst::ICMP_NE;
6510 break;
6511 case FCmpInst::FCMP_ORD:
6512 return replaceInstUsesWith(I, Builder.getTrue());
6513 case FCmpInst::FCMP_UNO:
6514 return replaceInstUsesWith(I, Builder.getFalse());
6515 }
6516
6517 // Now we know that the APFloat is a normal number, zero or inf.
6518
6519 // See if the FP constant is too large for the integer. For example,
6520 // comparing an i8 to 300.0.
6521 unsigned IntWidth = IntTy->getScalarSizeInBits();
6522
6523 if (!LHSUnsigned) {
6524 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
6525 // and large values.
6526 APFloat SMax(RHS.getSemantics());
6527 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
6528 APFloat::rmNearestTiesToEven);
6529 if (SMax < RHS) { // smax < 13123.0
6530 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
6531 Pred == ICmpInst::ICMP_SLE)
6532 return replaceInstUsesWith(I, Builder.getTrue());
6533 return replaceInstUsesWith(I, Builder.getFalse());
6534 }
6535 } else {
6536 // If the RHS value is > UnsignedMax, fold the comparison. This handles
6537 // +INF and large values.
6538 APFloat UMax(RHS.getSemantics());
6539 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
6540 APFloat::rmNearestTiesToEven);
6541 if (UMax < RHS) { // umax < 13123.0
6542 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
6543 Pred == ICmpInst::ICMP_ULE)
6544 return replaceInstUsesWith(I, Builder.getTrue());
6545 return replaceInstUsesWith(I, Builder.getFalse());
6546 }
6547 }
6548
6549 if (!LHSUnsigned) {
6550 // See if the RHS value is < SignedMin.
6551 APFloat SMin(RHS.getSemantics());
6552 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
6553 APFloat::rmNearestTiesToEven);
6554 if (SMin > RHS) { // smin > 12312.0
6555 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
6556 Pred == ICmpInst::ICMP_SGE)
6557 return replaceInstUsesWith(I, Builder.getTrue());
6558 return replaceInstUsesWith(I, Builder.getFalse());
6559 }
6560 } else {
6561 // See if the RHS value is < UnsignedMin.
6562 APFloat UMin(RHS.getSemantics());
6563 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
6564 APFloat::rmNearestTiesToEven);
6565 if (UMin > RHS) { // umin > 12312.0
6566 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
6567 Pred == ICmpInst::ICMP_UGE)
6568 return replaceInstUsesWith(I, Builder.getTrue());
6569 return replaceInstUsesWith(I, Builder.getFalse());
6570 }
6571 }
6572
6573 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
6574 // [0, UMAX], but it may still be fractional. See if it is fractional by
6575 // casting the FP value to the integer value and back, checking for equality.
6576 // Don't do this for zero, because -0.0 is not fractional.
6577 Constant *RHSInt = LHSUnsigned
6578 ? ConstantExpr::getFPToUI(RHSC, IntTy)
6579 : ConstantExpr::getFPToSI(RHSC, IntTy);
6580 if (!RHS.isZero()) {
6581 bool Equal = LHSUnsigned
6582 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
6583 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
6584 if (!Equal) {
6585 // If we had a comparison against a fractional value, we have to adjust
6586 // the compare predicate and sometimes the value. RHSC is rounded towards
6587 // zero at this point.
6588 switch (Pred) {
6589 default: llvm_unreachable("Unexpected integer comparison!");
6590 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
6591 return replaceInstUsesWith(I, Builder.getTrue());
6592 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
6593 return replaceInstUsesWith(I, Builder.getFalse());
6594 case ICmpInst::ICMP_ULE:
6595 // (float)int <= 4.4 --> int <= 4
6596 // (float)int <= -4.4 --> false
6597 if (RHS.isNegative())
6598 return replaceInstUsesWith(I, Builder.getFalse());
6599 break;
6600 case ICmpInst::ICMP_SLE:
6601 // (float)int <= 4.4 --> int <= 4
6602 // (float)int <= -4.4 --> int < -4
6603 if (RHS.isNegative())
6604 Pred = ICmpInst::ICMP_SLT;
6605 break;
6606 case ICmpInst::ICMP_ULT:
6607 // (float)int < -4.4 --> false
6608 // (float)int < 4.4 --> int <= 4
6609 if (RHS.isNegative())
6610 return replaceInstUsesWith(I, Builder.getFalse());
6611 Pred = ICmpInst::ICMP_ULE;
6612 break;
6613 case ICmpInst::ICMP_SLT:
6614 // (float)int < -4.4 --> int < -4
6615 // (float)int < 4.4 --> int <= 4
6616 if (!RHS.isNegative())
6617 Pred = ICmpInst::ICMP_SLE;
6618 break;
6619 case ICmpInst::ICMP_UGT:
6620 // (float)int > 4.4 --> int > 4
6621 // (float)int > -4.4 --> true
6622 if (RHS.isNegative())
6623 return replaceInstUsesWith(I, Builder.getTrue());
6624 break;
6625 case ICmpInst::ICMP_SGT:
6626 // (float)int > 4.4 --> int > 4
6627 // (float)int > -4.4 --> int >= -4
6628 if (RHS.isNegative())
6629 Pred = ICmpInst::ICMP_SGE;
6630 break;
6631 case ICmpInst::ICMP_UGE:
6632 // (float)int >= -4.4 --> true
6633 // (float)int >= 4.4 --> int > 4
6634 if (RHS.isNegative())
6635 return replaceInstUsesWith(I, Builder.getTrue());
6636 Pred = ICmpInst::ICMP_UGT;
6637 break;
6638 case ICmpInst::ICMP_SGE:
6639 // (float)int >= -4.4 --> int >= -4
6640 // (float)int >= 4.4 --> int > 4
6641 if (!RHS.isNegative())
6642 Pred = ICmpInst::ICMP_SGT;
6643 break;
6644 }
6645 }
6646 }
6647
6648 // Lower this FP comparison into an appropriate integer version of the
6649 // comparison.
6650 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
6651 }
6652
6653 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
foldFCmpReciprocalAndZero(FCmpInst & I,Instruction * LHSI,Constant * RHSC)6654 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
6655 Constant *RHSC) {
6656 // When C is not 0.0 and infinities are not allowed:
6657 // (C / X) < 0.0 is a sign-bit test of X
6658 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
6659 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
6660 //
6661 // Proof:
6662 // Multiply (C / X) < 0.0 by X * X / C.
6663 // - X is non zero, if it is the flag 'ninf' is violated.
6664 // - C defines the sign of X * X * C. Thus it also defines whether to swap
6665 // the predicate. C is also non zero by definition.
6666 //
6667 // Thus X * X / C is non zero and the transformation is valid. [qed]
6668
6669 FCmpInst::Predicate Pred = I.getPredicate();
6670
6671 // Check that predicates are valid.
6672 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
6673 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
6674 return nullptr;
6675
6676 // Check that RHS operand is zero.
6677 if (!match(RHSC, m_AnyZeroFP()))
6678 return nullptr;
6679
6680 // Check fastmath flags ('ninf').
6681 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
6682 return nullptr;
6683
6684 // Check the properties of the dividend. It must not be zero to avoid a
6685 // division by zero (see Proof).
6686 const APFloat *C;
6687 if (!match(LHSI->getOperand(0), m_APFloat(C)))
6688 return nullptr;
6689
6690 if (C->isZero())
6691 return nullptr;
6692
6693 // Get swapped predicate if necessary.
6694 if (C->isNegative())
6695 Pred = I.getSwappedPredicate();
6696
6697 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
6698 }
6699
6700 /// Optimize fabs(X) compared with zero.
foldFabsWithFcmpZero(FCmpInst & I,InstCombinerImpl & IC)6701 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
6702 Value *X;
6703 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
6704 return nullptr;
6705
6706 const APFloat *C;
6707 if (!match(I.getOperand(1), m_APFloat(C)))
6708 return nullptr;
6709
6710 if (!C->isPosZero()) {
6711 if (!C->isSmallestNormalized())
6712 return nullptr;
6713
6714 const Function *F = I.getFunction();
6715 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
6716 if (Mode.Input == DenormalMode::PreserveSign ||
6717 Mode.Input == DenormalMode::PositiveZero) {
6718
6719 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
6720 Constant *Zero = ConstantFP::getNullValue(X->getType());
6721 return new FCmpInst(P, X, Zero, "", I);
6722 };
6723
6724 switch (I.getPredicate()) {
6725 case FCmpInst::FCMP_OLT:
6726 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
6727 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
6728 case FCmpInst::FCMP_UGE:
6729 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
6730 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
6731 case FCmpInst::FCMP_OGE:
6732 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
6733 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
6734 case FCmpInst::FCMP_ULT:
6735 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
6736 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
6737 default:
6738 break;
6739 }
6740 }
6741
6742 return nullptr;
6743 }
6744
6745 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
6746 I->setPredicate(P);
6747 return IC.replaceOperand(*I, 0, X);
6748 };
6749
6750 switch (I.getPredicate()) {
6751 case FCmpInst::FCMP_UGE:
6752 case FCmpInst::FCMP_OLT:
6753 // fabs(X) >= 0.0 --> true
6754 // fabs(X) < 0.0 --> false
6755 llvm_unreachable("fcmp should have simplified");
6756
6757 case FCmpInst::FCMP_OGT:
6758 // fabs(X) > 0.0 --> X != 0.0
6759 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
6760
6761 case FCmpInst::FCMP_UGT:
6762 // fabs(X) u> 0.0 --> X u!= 0.0
6763 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
6764
6765 case FCmpInst::FCMP_OLE:
6766 // fabs(X) <= 0.0 --> X == 0.0
6767 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
6768
6769 case FCmpInst::FCMP_ULE:
6770 // fabs(X) u<= 0.0 --> X u== 0.0
6771 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
6772
6773 case FCmpInst::FCMP_OGE:
6774 // fabs(X) >= 0.0 --> !isnan(X)
6775 assert(!I.hasNoNaNs() && "fcmp should have simplified");
6776 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
6777
6778 case FCmpInst::FCMP_ULT:
6779 // fabs(X) u< 0.0 --> isnan(X)
6780 assert(!I.hasNoNaNs() && "fcmp should have simplified");
6781 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
6782
6783 case FCmpInst::FCMP_OEQ:
6784 case FCmpInst::FCMP_UEQ:
6785 case FCmpInst::FCMP_ONE:
6786 case FCmpInst::FCMP_UNE:
6787 case FCmpInst::FCMP_ORD:
6788 case FCmpInst::FCMP_UNO:
6789 // Look through the fabs() because it doesn't change anything but the sign.
6790 // fabs(X) == 0.0 --> X == 0.0,
6791 // fabs(X) != 0.0 --> X != 0.0
6792 // isnan(fabs(X)) --> isnan(X)
6793 // !isnan(fabs(X) --> !isnan(X)
6794 return replacePredAndOp0(&I, I.getPredicate(), X);
6795
6796 default:
6797 return nullptr;
6798 }
6799 }
6800
foldFCmpFNegCommonOp(FCmpInst & I)6801 static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
6802 CmpInst::Predicate Pred = I.getPredicate();
6803 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6804
6805 // Canonicalize fneg as Op1.
6806 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
6807 std::swap(Op0, Op1);
6808 Pred = I.getSwappedPredicate();
6809 }
6810
6811 if (!match(Op1, m_FNeg(m_Specific(Op0))))
6812 return nullptr;
6813
6814 // Replace the negated operand with 0.0:
6815 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
6816 Constant *Zero = ConstantFP::getNullValue(Op0->getType());
6817 return new FCmpInst(Pred, Op0, Zero, "", &I);
6818 }
6819
visitFCmpInst(FCmpInst & I)6820 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
6821 bool Changed = false;
6822
6823 /// Orders the operands of the compare so that they are listed from most
6824 /// complex to least complex. This puts constants before unary operators,
6825 /// before binary operators.
6826 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6827 I.swapOperands();
6828 Changed = true;
6829 }
6830
6831 const CmpInst::Predicate Pred = I.getPredicate();
6832 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6833 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
6834 SQ.getWithInstruction(&I)))
6835 return replaceInstUsesWith(I, V);
6836
6837 // Simplify 'fcmp pred X, X'
6838 Type *OpType = Op0->getType();
6839 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
6840 if (Op0 == Op1) {
6841 switch (Pred) {
6842 default: break;
6843 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6844 case FCmpInst::FCMP_ULT: // True if unordered or less than
6845 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6846 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6847 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6848 I.setPredicate(FCmpInst::FCMP_UNO);
6849 I.setOperand(1, Constant::getNullValue(OpType));
6850 return &I;
6851
6852 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6853 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6854 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6855 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6856 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6857 I.setPredicate(FCmpInst::FCMP_ORD);
6858 I.setOperand(1, Constant::getNullValue(OpType));
6859 return &I;
6860 }
6861 }
6862
6863 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
6864 // then canonicalize the operand to 0.0.
6865 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
6866 if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI))
6867 return replaceOperand(I, 0, ConstantFP::getNullValue(OpType));
6868
6869 if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI))
6870 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType));
6871 }
6872
6873 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
6874 Value *X, *Y;
6875 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
6876 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
6877
6878 if (Instruction *R = foldFCmpFNegCommonOp(I))
6879 return R;
6880
6881 // Test if the FCmpInst instruction is used exclusively by a select as
6882 // part of a minimum or maximum operation. If so, refrain from doing
6883 // any other folding. This helps out other analyses which understand
6884 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6885 // and CodeGen. And in this case, at least one of the comparison
6886 // operands has at least one user besides the compare (the select),
6887 // which would often largely negate the benefit of folding anyway.
6888 if (I.hasOneUse())
6889 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
6890 Value *A, *B;
6891 SelectPatternResult SPR = matchSelectPattern(SI, A, B);
6892 if (SPR.Flavor != SPF_UNKNOWN)
6893 return nullptr;
6894 }
6895
6896 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
6897 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
6898 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
6899 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType));
6900
6901 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
6902 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
6903 if (match(Op1, m_PosZeroFP()) &&
6904 match(Op0, m_OneUse(m_BitCast(m_Value(X)))) &&
6905 X->getType()->isVectorTy() == OpType->isVectorTy() &&
6906 X->getType()->getScalarSizeInBits() == OpType->getScalarSizeInBits()) {
6907 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
6908 if (Pred == FCmpInst::FCMP_OEQ)
6909 IntPred = ICmpInst::ICMP_EQ;
6910 else if (Pred == FCmpInst::FCMP_UNE)
6911 IntPred = ICmpInst::ICMP_NE;
6912
6913 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
6914 Type *IntTy = X->getType();
6915 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
6916 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
6917 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
6918 }
6919 }
6920
6921 // Handle fcmp with instruction LHS and constant RHS.
6922 Instruction *LHSI;
6923 Constant *RHSC;
6924 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
6925 switch (LHSI->getOpcode()) {
6926 case Instruction::PHI:
6927 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6928 // block. If in the same block, we're encouraging jump threading. If
6929 // not, we are just pessimizing the code by making an i1 phi.
6930 if (LHSI->getParent() == I.getParent())
6931 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
6932 return NV;
6933 break;
6934 case Instruction::SIToFP:
6935 case Instruction::UIToFP:
6936 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
6937 return NV;
6938 break;
6939 case Instruction::FDiv:
6940 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
6941 return NV;
6942 break;
6943 case Instruction::Load:
6944 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
6945 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6946 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
6947 cast<LoadInst>(LHSI), GEP, GV, I))
6948 return Res;
6949 break;
6950 }
6951 }
6952
6953 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
6954 return R;
6955
6956 if (match(Op0, m_FNeg(m_Value(X)))) {
6957 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
6958 Constant *C;
6959 if (match(Op1, m_Constant(C)))
6960 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
6961 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
6962 }
6963
6964 if (match(Op0, m_FPExt(m_Value(X)))) {
6965 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
6966 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
6967 return new FCmpInst(Pred, X, Y, "", &I);
6968
6969 const APFloat *C;
6970 if (match(Op1, m_APFloat(C))) {
6971 const fltSemantics &FPSem =
6972 X->getType()->getScalarType()->getFltSemantics();
6973 bool Lossy;
6974 APFloat TruncC = *C;
6975 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
6976
6977 if (Lossy) {
6978 // X can't possibly equal the higher-precision constant, so reduce any
6979 // equality comparison.
6980 // TODO: Other predicates can be handled via getFCmpCode().
6981 switch (Pred) {
6982 case FCmpInst::FCMP_OEQ:
6983 // X is ordered and equal to an impossible constant --> false
6984 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6985 case FCmpInst::FCMP_ONE:
6986 // X is ordered and not equal to an impossible constant --> ordered
6987 return new FCmpInst(FCmpInst::FCMP_ORD, X,
6988 ConstantFP::getNullValue(X->getType()));
6989 case FCmpInst::FCMP_UEQ:
6990 // X is unordered or equal to an impossible constant --> unordered
6991 return new FCmpInst(FCmpInst::FCMP_UNO, X,
6992 ConstantFP::getNullValue(X->getType()));
6993 case FCmpInst::FCMP_UNE:
6994 // X is unordered or not equal to an impossible constant --> true
6995 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6996 default:
6997 break;
6998 }
6999 }
7000
7001 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
7002 // Avoid lossy conversions and denormals.
7003 // Zero is a special case that's OK to convert.
7004 APFloat Fabs = TruncC;
7005 Fabs.clearSign();
7006 if (!Lossy &&
7007 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
7008 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
7009 return new FCmpInst(Pred, X, NewC, "", &I);
7010 }
7011 }
7012 }
7013
7014 // Convert a sign-bit test of an FP value into a cast and integer compare.
7015 // TODO: Simplify if the copysign constant is 0.0 or NaN.
7016 // TODO: Handle non-zero compare constants.
7017 // TODO: Handle other predicates.
7018 const APFloat *C;
7019 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
7020 m_Value(X)))) &&
7021 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
7022 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
7023 if (auto *VecTy = dyn_cast<VectorType>(OpType))
7024 IntType = VectorType::get(IntType, VecTy->getElementCount());
7025
7026 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
7027 if (Pred == FCmpInst::FCMP_OLT) {
7028 Value *IntX = Builder.CreateBitCast(X, IntType);
7029 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
7030 ConstantInt::getNullValue(IntType));
7031 }
7032 }
7033
7034 {
7035 Value *CanonLHS = nullptr, *CanonRHS = nullptr;
7036 match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
7037 match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
7038
7039 // (canonicalize(x) == x) => (x == x)
7040 if (CanonLHS == Op1)
7041 return new FCmpInst(Pred, Op1, Op1, "", &I);
7042
7043 // (x == canonicalize(x)) => (x == x)
7044 if (CanonRHS == Op0)
7045 return new FCmpInst(Pred, Op0, Op0, "", &I);
7046
7047 // (canonicalize(x) == canonicalize(y)) => (x == y)
7048 if (CanonLHS && CanonRHS)
7049 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
7050 }
7051
7052 if (I.getType()->isVectorTy())
7053 if (Instruction *Res = foldVectorCmp(I, Builder))
7054 return Res;
7055
7056 return Changed ? &I : nullptr;
7057 }
7058