1//===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
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 Correlated Value Propagation pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
14#include "llvm/ADT/DepthFirstIterator.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/DomTreeUpdater.h"
18#include "llvm/Analysis/GlobalsModRef.h"
19#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/LazyValueInfo.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/IR/Attributes.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Operator.h"
37#include "llvm/IR/PassManager.h"
38#include "llvm/IR/PatternMatch.h"
39#include "llvm/IR/ProfDataUtils.h"
40#include "llvm/IR/Type.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include <cassert>
45#include <optional>
46#include <utility>
47
48using namespace llvm;
49
50#define DEBUG_TYPE "correlated-value-propagation"
51
52STATISTIC(NumPhis, "Number of phis propagated");
53STATISTIC(NumPhiCommon, "Number of phis deleted via common incoming value");
54STATISTIC(NumSelects, "Number of selects propagated");
55STATISTIC(NumCmps, "Number of comparisons propagated");
56STATISTIC(NumReturns, "Number of return values propagated");
57STATISTIC(NumDeadCases, "Number of switch cases removed");
58STATISTIC(NumSDivSRemsNarrowed,
59 "Number of sdivs/srems whose width was decreased");
60STATISTIC(NumSDivs, "Number of sdiv converted to udiv");
61STATISTIC(NumUDivURemsNarrowed,
62 "Number of udivs/urems whose width was decreased");
63STATISTIC(NumAShrsConverted, "Number of ashr converted to lshr");
64STATISTIC(NumAShrsRemoved, "Number of ashr removed");
65STATISTIC(NumSRems, "Number of srem converted to urem");
66STATISTIC(NumSExt, "Number of sext converted to zext");
67STATISTIC(NumSIToFP, "Number of sitofp converted to uitofp");
68STATISTIC(NumSICmps, "Number of signed icmp preds simplified to unsigned");
69STATISTIC(NumAnd, "Number of ands removed");
70STATISTIC(NumNW, "Number of no-wrap deductions");
71STATISTIC(NumNSW, "Number of no-signed-wrap deductions");
72STATISTIC(NumNUW, "Number of no-unsigned-wrap deductions");
73STATISTIC(NumAddNW, "Number of no-wrap deductions for add");
74STATISTIC(NumAddNSW, "Number of no-signed-wrap deductions for add");
75STATISTIC(NumAddNUW, "Number of no-unsigned-wrap deductions for add");
76STATISTIC(NumSubNW, "Number of no-wrap deductions for sub");
77STATISTIC(NumSubNSW, "Number of no-signed-wrap deductions for sub");
78STATISTIC(NumSubNUW, "Number of no-unsigned-wrap deductions for sub");
79STATISTIC(NumMulNW, "Number of no-wrap deductions for mul");
80STATISTIC(NumMulNSW, "Number of no-signed-wrap deductions for mul");
81STATISTIC(NumMulNUW, "Number of no-unsigned-wrap deductions for mul");
82STATISTIC(NumShlNW, "Number of no-wrap deductions for shl");
83STATISTIC(NumShlNSW, "Number of no-signed-wrap deductions for shl");
84STATISTIC(NumShlNUW, "Number of no-unsigned-wrap deductions for shl");
85STATISTIC(NumAbs, "Number of llvm.abs intrinsics removed");
86STATISTIC(NumOverflows, "Number of overflow checks removed");
87STATISTIC(NumSaturating,
88 "Number of saturating arithmetics converted to normal arithmetics");
89STATISTIC(NumNonNull, "Number of function pointer arguments marked non-null");
90STATISTIC(NumCmpIntr, "Number of llvm.[us]cmp intrinsics removed");
91STATISTIC(NumMinMax, "Number of llvm.[us]{min,max} intrinsics removed");
92STATISTIC(NumSMinMax,
93 "Number of llvm.s{min,max} intrinsics simplified to unsigned");
94STATISTIC(NumUDivURemsNarrowedExpanded,
95 "Number of bound udiv's/urem's expanded");
96STATISTIC(NumNNeg, "Number of zext/uitofp non-negative deductions");
97
98static Constant *getConstantAt(Value *V, Instruction *At, LazyValueInfo *LVI) {
99 if (Constant *C = LVI->getConstant(V, CxtI: At))
100 return C;
101
102 // TODO: The following really should be sunk inside LVI's core algorithm, or
103 // at least the outer shims around such.
104 auto *C = dyn_cast<CmpInst>(Val: V);
105 if (!C)
106 return nullptr;
107
108 Value *Op0 = C->getOperand(i_nocapture: 0);
109 Constant *Op1 = dyn_cast<Constant>(Val: C->getOperand(i_nocapture: 1));
110 if (!Op1)
111 return nullptr;
112
113 return LVI->getPredicateAt(Pred: C->getPredicate(), V: Op0, C: Op1, CxtI: At,
114 /*UseBlockValue=*/false);
115}
116
117static bool processSelect(SelectInst *S, LazyValueInfo *LVI) {
118 if (S->getType()->isVectorTy() || isa<Constant>(Val: S->getCondition()))
119 return false;
120
121 bool Changed = false;
122 for (Use &U : make_early_inc_range(Range: S->uses())) {
123 auto *I = cast<Instruction>(Val: U.getUser());
124 Constant *C;
125 if (auto *PN = dyn_cast<PHINode>(Val: I))
126 C = LVI->getConstantOnEdge(V: S->getCondition(), FromBB: PN->getIncomingBlock(U),
127 ToBB: I->getParent(), CxtI: I);
128 else
129 C = getConstantAt(V: S->getCondition(), At: I, LVI);
130
131 auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
132 if (!CI)
133 continue;
134
135 U.set(CI->isOne() ? S->getTrueValue() : S->getFalseValue());
136 Changed = true;
137 ++NumSelects;
138 }
139
140 if (Changed && S->use_empty())
141 S->eraseFromParent();
142
143 return Changed;
144}
145
146/// Try to simplify a phi with constant incoming values that match the edge
147/// values of a non-constant value on all other edges:
148/// bb0:
149/// %isnull = icmp eq i8* %x, null
150/// br i1 %isnull, label %bb2, label %bb1
151/// bb1:
152/// br label %bb2
153/// bb2:
154/// %r = phi i8* [ %x, %bb1 ], [ null, %bb0 ]
155/// -->
156/// %r = %x
157static bool simplifyCommonValuePhi(PHINode *P, LazyValueInfo *LVI,
158 DominatorTree *DT) {
159 // Collect incoming constants and initialize possible common value.
160 SmallVector<std::pair<Constant *, unsigned>, 4> IncomingConstants;
161 Value *CommonValue = nullptr;
162 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
163 Value *Incoming = P->getIncomingValue(i);
164 if (auto *IncomingConstant = dyn_cast<Constant>(Val: Incoming)) {
165 IncomingConstants.push_back(Elt: std::make_pair(x&: IncomingConstant, y&: i));
166 } else if (!CommonValue) {
167 // The potential common value is initialized to the first non-constant.
168 CommonValue = Incoming;
169 } else if (Incoming != CommonValue) {
170 // There can be only one non-constant common value.
171 return false;
172 }
173 }
174
175 if (!CommonValue || IncomingConstants.empty())
176 return false;
177
178 // The common value must be valid in all incoming blocks.
179 BasicBlock *ToBB = P->getParent();
180 if (auto *CommonInst = dyn_cast<Instruction>(Val: CommonValue))
181 if (!DT->dominates(Def: CommonInst, BB: ToBB))
182 return false;
183
184 // We have a phi with exactly 1 variable incoming value and 1 or more constant
185 // incoming values. See if all constant incoming values can be mapped back to
186 // the same incoming variable value.
187 for (auto &IncomingConstant : IncomingConstants) {
188 Constant *C = IncomingConstant.first;
189 BasicBlock *IncomingBB = P->getIncomingBlock(i: IncomingConstant.second);
190 if (C != LVI->getConstantOnEdge(V: CommonValue, FromBB: IncomingBB, ToBB, CxtI: P))
191 return false;
192 }
193
194 // LVI only guarantees that the value matches a certain constant if the value
195 // is not poison. Make sure we don't replace a well-defined value with poison.
196 // This is usually satisfied due to a prior branch on the value.
197 if (!isGuaranteedNotToBePoison(V: CommonValue, AC: nullptr, CtxI: P, DT))
198 return false;
199
200 // All constant incoming values map to the same variable along the incoming
201 // edges of the phi. The phi is unnecessary.
202 P->replaceAllUsesWith(V: CommonValue);
203 P->eraseFromParent();
204 ++NumPhiCommon;
205 return true;
206}
207
208static Value *getValueOnEdge(LazyValueInfo *LVI, Value *Incoming,
209 BasicBlock *From, BasicBlock *To,
210 Instruction *CxtI) {
211 if (Constant *C = LVI->getConstantOnEdge(V: Incoming, FromBB: From, ToBB: To, CxtI))
212 return C;
213
214 // Look if the incoming value is a select with a scalar condition for which
215 // LVI can tells us the value. In that case replace the incoming value with
216 // the appropriate value of the select. This often allows us to remove the
217 // select later.
218 auto *SI = dyn_cast<SelectInst>(Val: Incoming);
219 if (!SI)
220 return nullptr;
221
222 // Once LVI learns to handle vector types, we could also add support
223 // for vector type constants that are not all zeroes or all ones.
224 Value *Condition = SI->getCondition();
225 if (!Condition->getType()->isVectorTy()) {
226 if (Constant *C = LVI->getConstantOnEdge(V: Condition, FromBB: From, ToBB: To, CxtI)) {
227 if (C->isOneValue())
228 return SI->getTrueValue();
229 if (C->isNullValue())
230 return SI->getFalseValue();
231 }
232 }
233
234 // Look if the select has a constant but LVI tells us that the incoming
235 // value can never be that constant. In that case replace the incoming
236 // value with the other value of the select. This often allows us to
237 // remove the select later.
238
239 // The "false" case
240 if (auto *C = dyn_cast<Constant>(Val: SI->getFalseValue()))
241 if (auto *Res = dyn_cast_or_null<ConstantInt>(
242 Val: LVI->getPredicateOnEdge(Pred: ICmpInst::ICMP_EQ, V: SI, C, FromBB: From, ToBB: To, CxtI));
243 Res && Res->isZero())
244 return SI->getTrueValue();
245
246 // The "true" case,
247 // similar to the select "false" case, but try the select "true" value
248 if (auto *C = dyn_cast<Constant>(Val: SI->getTrueValue()))
249 if (auto *Res = dyn_cast_or_null<ConstantInt>(
250 Val: LVI->getPredicateOnEdge(Pred: ICmpInst::ICMP_EQ, V: SI, C, FromBB: From, ToBB: To, CxtI));
251 Res && Res->isZero())
252 return SI->getFalseValue();
253
254 return nullptr;
255}
256
257static bool processPHI(PHINode *P, LazyValueInfo *LVI, DominatorTree *DT,
258 const SimplifyQuery &SQ) {
259 bool Changed = false;
260
261 BasicBlock *BB = P->getParent();
262 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
263 Value *Incoming = P->getIncomingValue(i);
264 if (isa<Constant>(Val: Incoming)) continue;
265
266 Value *V = getValueOnEdge(LVI, Incoming, From: P->getIncomingBlock(i), To: BB, CxtI: P);
267 if (V) {
268 P->setIncomingValue(i, V);
269 Changed = true;
270 }
271 }
272
273 if (Value *V = simplifyInstruction(I: P, Q: SQ)) {
274 P->replaceAllUsesWith(V);
275 P->eraseFromParent();
276 Changed = true;
277 }
278
279 if (!Changed)
280 Changed = simplifyCommonValuePhi(P, LVI, DT);
281
282 if (Changed)
283 ++NumPhis;
284
285 return Changed;
286}
287
288static bool processICmp(ICmpInst *Cmp, LazyValueInfo *LVI) {
289 // Only for signed relational comparisons of integers.
290 if (!Cmp->getOperand(i_nocapture: 0)->getType()->isIntOrIntVectorTy())
291 return false;
292
293 if (!Cmp->isSigned() && (!Cmp->isUnsigned() || Cmp->hasSameSign()))
294 return false;
295
296 bool Changed = false;
297
298 ConstantRange CR1 = LVI->getConstantRangeAtUse(U: Cmp->getOperandUse(i: 0),
299 /*UndefAllowed=*/false),
300 CR2 = LVI->getConstantRangeAtUse(U: Cmp->getOperandUse(i: 1),
301 /*UndefAllowed=*/false);
302
303 if (Cmp->isSigned()) {
304 ICmpInst::Predicate UnsignedPred =
305 ConstantRange::getEquivalentPredWithFlippedSignedness(
306 Pred: Cmp->getPredicate(), CR1, CR2);
307
308 if (UnsignedPred == ICmpInst::Predicate::BAD_ICMP_PREDICATE)
309 return false;
310
311 ++NumSICmps;
312 Cmp->setPredicate(UnsignedPred);
313 Changed = true;
314 }
315
316 if (ConstantRange::areInsensitiveToSignednessOfICmpPredicate(CR1, CR2)) {
317 Cmp->setSameSign();
318 Changed = true;
319 }
320
321 return Changed;
322}
323
324/// See if LazyValueInfo's ability to exploit edge conditions or range
325/// information is sufficient to prove this comparison. Even for local
326/// conditions, this can sometimes prove conditions instcombine can't by
327/// exploiting range information.
328static bool constantFoldCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
329 Value *Op0 = Cmp->getOperand(i_nocapture: 0);
330 Value *Op1 = Cmp->getOperand(i_nocapture: 1);
331 Constant *Res = LVI->getPredicateAt(Pred: Cmp->getPredicate(), LHS: Op0, RHS: Op1, CxtI: Cmp,
332 /*UseBlockValue=*/true);
333 if (!Res)
334 return false;
335
336 ++NumCmps;
337 Cmp->replaceAllUsesWith(V: Res);
338 Cmp->eraseFromParent();
339 return true;
340}
341
342static bool processCmp(CmpInst *Cmp, LazyValueInfo *LVI) {
343 if (constantFoldCmp(Cmp, LVI))
344 return true;
345
346 if (auto *ICmp = dyn_cast<ICmpInst>(Val: Cmp))
347 if (processICmp(Cmp: ICmp, LVI))
348 return true;
349
350 return false;
351}
352
353/// Simplify a switch instruction by removing cases which can never fire. If the
354/// uselessness of a case could be determined locally then constant propagation
355/// would already have figured it out. Instead, walk the predecessors and
356/// statically evaluate cases based on information available on that edge. Cases
357/// that cannot fire no matter what the incoming edge can safely be removed. If
358/// a case fires on every incoming edge then the entire switch can be removed
359/// and replaced with a branch to the case destination.
360static bool processSwitch(SwitchInst *I, LazyValueInfo *LVI,
361 DominatorTree *DT) {
362 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy);
363 Value *Cond = I->getCondition();
364 BasicBlock *BB = I->getParent();
365
366 // Analyse each switch case in turn.
367 bool Changed = false;
368 DenseMap<BasicBlock*, int> SuccessorsCount;
369 for (auto *Succ : successors(BB))
370 SuccessorsCount[Succ]++;
371
372 { // Scope for SwitchInstProfUpdateWrapper. It must not live during
373 // ConstantFoldTerminator() as the underlying SwitchInst can be changed.
374 SwitchInstProfUpdateWrapper SI(*I);
375 ConstantRange CR =
376 LVI->getConstantRangeAtUse(U: I->getOperandUse(i: 0), /*UndefAllowed=*/false);
377 unsigned ReachableCaseCount = 0;
378
379 for (auto CI = SI->case_begin(), CE = SI->case_end(); CI != CE;) {
380 ConstantInt *Case = CI->getCaseValue();
381 std::optional<bool> Predicate = std::nullopt;
382 if (!CR.contains(Val: Case->getValue()))
383 Predicate = false;
384 else if (CR.isSingleElement() &&
385 *CR.getSingleElement() == Case->getValue())
386 Predicate = true;
387 if (!Predicate) {
388 // Handle missing cases, e.g., the range has a hole.
389 auto *Res = dyn_cast_or_null<ConstantInt>(
390 Val: LVI->getPredicateAt(Pred: CmpInst::ICMP_EQ, V: Cond, C: Case, CxtI: I,
391 /* UseBlockValue=*/true));
392 if (Res && Res->isZero())
393 Predicate = false;
394 else if (Res && Res->isOne())
395 Predicate = true;
396 }
397
398 if (Predicate && !*Predicate) {
399 // This case never fires - remove it.
400 BasicBlock *Succ = CI->getCaseSuccessor();
401 Succ->removePredecessor(Pred: BB);
402 CI = SI.removeCase(I: CI);
403 CE = SI->case_end();
404
405 // The condition can be modified by removePredecessor's PHI simplification
406 // logic.
407 Cond = SI->getCondition();
408
409 ++NumDeadCases;
410 Changed = true;
411 if (--SuccessorsCount[Succ] == 0)
412 DTU.applyUpdatesPermissive(Updates: {{DominatorTree::Delete, BB, Succ}});
413 continue;
414 }
415 if (Predicate && *Predicate) {
416 // This case always fires. Arrange for the switch to be turned into an
417 // unconditional branch by replacing the switch condition with the case
418 // value.
419 SI->setCondition(Case);
420 NumDeadCases += SI->getNumCases();
421 Changed = true;
422 break;
423 }
424
425 // Increment the case iterator since we didn't delete it.
426 ++CI;
427 ++ReachableCaseCount;
428 }
429
430 // The default dest is unreachable if all cases are covered.
431 if (!SI->defaultDestUnreachable() &&
432 !CR.isSizeLargerThan(MaxSize: ReachableCaseCount)) {
433 BasicBlock *DefaultDest = SI->getDefaultDest();
434 BasicBlock *NewUnreachableBB =
435 BasicBlock::Create(Context&: BB->getContext(), Name: "default.unreachable",
436 Parent: BB->getParent(), InsertBefore: DefaultDest);
437 auto *UI = new UnreachableInst(BB->getContext(), NewUnreachableBB);
438 UI->setDebugLoc(DebugLoc::getTemporary());
439
440 DefaultDest->removePredecessor(Pred: BB);
441 SI->setDefaultDest(NewUnreachableBB);
442
443 if (SuccessorsCount[DefaultDest] == 1)
444 DTU.applyUpdates(Updates: {{DominatorTree::Delete, BB, DefaultDest}});
445 DTU.applyUpdates(Updates: {{DominatorTree::Insert, BB, NewUnreachableBB}});
446
447 ++NumDeadCases;
448 Changed = true;
449 }
450 }
451
452 if (Changed)
453 // If the switch has been simplified to the point where it can be replaced
454 // by a branch then do so now.
455 ConstantFoldTerminator(BB, /*DeleteDeadConditions = */ false,
456 /*TLI = */ nullptr, DTU: &DTU);
457 return Changed;
458}
459
460// See if we can prove that the given binary op intrinsic will not overflow.
461static bool willNotOverflow(BinaryOpIntrinsic *BO, LazyValueInfo *LVI) {
462 ConstantRange LRange =
463 LVI->getConstantRangeAtUse(U: BO->getOperandUse(i: 0), /*UndefAllowed*/ false);
464 ConstantRange RRange =
465 LVI->getConstantRangeAtUse(U: BO->getOperandUse(i: 1), /*UndefAllowed*/ false);
466 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
467 BinOp: BO->getBinaryOp(), Other: RRange, NoWrapKind: BO->getNoWrapKind());
468 return NWRegion.contains(CR: LRange);
469}
470
471static void setDeducedOverflowingFlags(Value *V, Instruction::BinaryOps Opcode,
472 bool NewNSW, bool NewNUW) {
473 Statistic *OpcNW, *OpcNSW, *OpcNUW;
474 switch (Opcode) {
475 case Instruction::Add:
476 OpcNW = &NumAddNW;
477 OpcNSW = &NumAddNSW;
478 OpcNUW = &NumAddNUW;
479 break;
480 case Instruction::Sub:
481 OpcNW = &NumSubNW;
482 OpcNSW = &NumSubNSW;
483 OpcNUW = &NumSubNUW;
484 break;
485 case Instruction::Mul:
486 OpcNW = &NumMulNW;
487 OpcNSW = &NumMulNSW;
488 OpcNUW = &NumMulNUW;
489 break;
490 case Instruction::Shl:
491 OpcNW = &NumShlNW;
492 OpcNSW = &NumShlNSW;
493 OpcNUW = &NumShlNUW;
494 break;
495 default:
496 llvm_unreachable("Will not be called with other binops");
497 }
498
499 auto *Inst = dyn_cast<Instruction>(Val: V);
500 if (NewNSW) {
501 ++NumNW;
502 ++*OpcNW;
503 ++NumNSW;
504 ++*OpcNSW;
505 if (Inst)
506 Inst->setHasNoSignedWrap();
507 }
508 if (NewNUW) {
509 ++NumNW;
510 ++*OpcNW;
511 ++NumNUW;
512 ++*OpcNUW;
513 if (Inst)
514 Inst->setHasNoUnsignedWrap();
515 }
516}
517
518static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI);
519
520// See if @llvm.abs argument is alays positive/negative, and simplify.
521// Notably, INT_MIN can belong to either range, regardless of the NSW,
522// because it is negation-invariant.
523static bool processAbsIntrinsic(IntrinsicInst *II, LazyValueInfo *LVI) {
524 Value *X = II->getArgOperand(i: 0);
525 bool IsIntMinPoison = cast<ConstantInt>(Val: II->getArgOperand(i: 1))->isOne();
526 APInt IntMin = APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
527 ConstantRange Range = LVI->getConstantRangeAtUse(
528 U: II->getOperandUse(i: 0), /*UndefAllowed*/ IsIntMinPoison);
529
530 // Is X in [0, IntMin]? NOTE: INT_MIN is fine!
531 if (Range.icmp(Pred: CmpInst::ICMP_ULE, Other: IntMin)) {
532 ++NumAbs;
533 II->replaceAllUsesWith(V: X);
534 II->eraseFromParent();
535 return true;
536 }
537
538 // Is X in [IntMin, 0]? NOTE: INT_MIN is fine!
539 if (Range.getSignedMax().isNonPositive()) {
540 IRBuilder<> B(II);
541 Value *NegX = B.CreateNeg(V: X, Name: II->getName(),
542 /*HasNSW=*/IsIntMinPoison);
543 ++NumAbs;
544 II->replaceAllUsesWith(V: NegX);
545 II->eraseFromParent();
546
547 // See if we can infer some no-wrap flags.
548 if (auto *BO = dyn_cast<BinaryOperator>(Val: NegX))
549 processBinOp(BinOp: BO, LVI);
550
551 return true;
552 }
553
554 // Argument's range crosses zero.
555 // Can we at least tell that the argument is never INT_MIN?
556 if (!IsIntMinPoison && !Range.contains(Val: IntMin)) {
557 ++NumNSW;
558 ++NumSubNSW;
559 II->setArgOperand(i: 1, v: ConstantInt::getTrue(Context&: II->getContext()));
560 return true;
561 }
562 return false;
563}
564
565static bool processCmpIntrinsic(CmpIntrinsic *CI, LazyValueInfo *LVI) {
566 ConstantRange LHS_CR =
567 LVI->getConstantRangeAtUse(U: CI->getOperandUse(i: 0), /*UndefAllowed*/ false);
568 ConstantRange RHS_CR =
569 LVI->getConstantRangeAtUse(U: CI->getOperandUse(i: 1), /*UndefAllowed*/ false);
570
571 if (LHS_CR.icmp(Pred: CI->getGTPredicate(), Other: RHS_CR)) {
572 ++NumCmpIntr;
573 CI->replaceAllUsesWith(V: ConstantInt::get(Ty: CI->getType(), V: 1));
574 CI->eraseFromParent();
575 return true;
576 }
577 if (LHS_CR.icmp(Pred: CI->getLTPredicate(), Other: RHS_CR)) {
578 ++NumCmpIntr;
579 CI->replaceAllUsesWith(V: ConstantInt::getSigned(Ty: CI->getType(), V: -1));
580 CI->eraseFromParent();
581 return true;
582 }
583 if (LHS_CR.icmp(Pred: ICmpInst::ICMP_EQ, Other: RHS_CR)) {
584 ++NumCmpIntr;
585 CI->replaceAllUsesWith(V: ConstantInt::get(Ty: CI->getType(), V: 0));
586 CI->eraseFromParent();
587 return true;
588 }
589
590 return false;
591}
592
593// See if this min/max intrinsic always picks it's one specific operand.
594// If not, check whether we can canonicalize signed minmax into unsigned version
595static bool processMinMaxIntrinsic(MinMaxIntrinsic *MM, LazyValueInfo *LVI) {
596 CmpInst::Predicate Pred = CmpInst::getNonStrictPredicate(pred: MM->getPredicate());
597 ConstantRange LHS_CR = LVI->getConstantRangeAtUse(U: MM->getOperandUse(i: 0),
598 /*UndefAllowed*/ false);
599 ConstantRange RHS_CR = LVI->getConstantRangeAtUse(U: MM->getOperandUse(i: 1),
600 /*UndefAllowed*/ false);
601 if (LHS_CR.icmp(Pred, Other: RHS_CR)) {
602 ++NumMinMax;
603 MM->replaceAllUsesWith(V: MM->getLHS());
604 MM->eraseFromParent();
605 return true;
606 }
607 if (RHS_CR.icmp(Pred, Other: LHS_CR)) {
608 ++NumMinMax;
609 MM->replaceAllUsesWith(V: MM->getRHS());
610 MM->eraseFromParent();
611 return true;
612 }
613
614 if (MM->isSigned() &&
615 ConstantRange::areInsensitiveToSignednessOfICmpPredicate(CR1: LHS_CR,
616 CR2: RHS_CR)) {
617 ++NumSMinMax;
618 IRBuilder<> B(MM);
619 MM->replaceAllUsesWith(V: B.CreateBinaryIntrinsic(
620 ID: MM->getIntrinsicID() == Intrinsic::smin ? Intrinsic::umin
621 : Intrinsic::umax,
622 LHS: MM->getLHS(), RHS: MM->getRHS()));
623 MM->eraseFromParent();
624 return true;
625 }
626
627 return false;
628}
629
630// Rewrite this with.overflow intrinsic as non-overflowing.
631static bool processOverflowIntrinsic(WithOverflowInst *WO, LazyValueInfo *LVI) {
632 IRBuilder<> B(WO);
633 Instruction::BinaryOps Opcode = WO->getBinaryOp();
634 bool NSW = WO->isSigned();
635 bool NUW = !WO->isSigned();
636
637 Value *NewOp =
638 B.CreateBinOp(Opc: Opcode, LHS: WO->getLHS(), RHS: WO->getRHS(), Name: WO->getName());
639 setDeducedOverflowingFlags(V: NewOp, Opcode, NewNSW: NSW, NewNUW: NUW);
640
641 StructType *ST = cast<StructType>(Val: WO->getType());
642 Constant *Struct = ConstantStruct::get(T: ST,
643 V: { PoisonValue::get(T: ST->getElementType(N: 0)),
644 ConstantInt::getFalse(Ty: ST->getElementType(N: 1)) });
645 Value *NewI = B.CreateInsertValue(Agg: Struct, Val: NewOp, Idxs: 0);
646 WO->replaceAllUsesWith(V: NewI);
647 WO->eraseFromParent();
648 ++NumOverflows;
649
650 // See if we can infer the other no-wrap too.
651 if (auto *BO = dyn_cast<BinaryOperator>(Val: NewOp))
652 processBinOp(BinOp: BO, LVI);
653
654 return true;
655}
656
657static bool processSaturatingInst(SaturatingInst *SI, LazyValueInfo *LVI) {
658 Instruction::BinaryOps Opcode = SI->getBinaryOp();
659 bool NSW = SI->isSigned();
660 bool NUW = !SI->isSigned();
661 BinaryOperator *BinOp = BinaryOperator::Create(
662 Op: Opcode, S1: SI->getLHS(), S2: SI->getRHS(), Name: SI->getName(), InsertBefore: SI->getIterator());
663 BinOp->setDebugLoc(SI->getDebugLoc());
664 setDeducedOverflowingFlags(V: BinOp, Opcode, NewNSW: NSW, NewNUW: NUW);
665
666 SI->replaceAllUsesWith(V: BinOp);
667 SI->eraseFromParent();
668 ++NumSaturating;
669
670 // See if we can infer the other no-wrap too.
671 if (auto *BO = dyn_cast<BinaryOperator>(Val: BinOp))
672 processBinOp(BinOp: BO, LVI);
673
674 return true;
675}
676
677/// Infer nonnull attributes for the arguments at the specified callsite.
678static bool processCallSite(CallBase &CB, LazyValueInfo *LVI) {
679
680 if (CB.getIntrinsicID() == Intrinsic::abs) {
681 return processAbsIntrinsic(II: &cast<IntrinsicInst>(Val&: CB), LVI);
682 }
683
684 if (auto *CI = dyn_cast<CmpIntrinsic>(Val: &CB)) {
685 return processCmpIntrinsic(CI, LVI);
686 }
687
688 if (auto *MM = dyn_cast<MinMaxIntrinsic>(Val: &CB)) {
689 return processMinMaxIntrinsic(MM, LVI);
690 }
691
692 if (auto *WO = dyn_cast<WithOverflowInst>(Val: &CB)) {
693 if (willNotOverflow(BO: WO, LVI))
694 return processOverflowIntrinsic(WO, LVI);
695 }
696
697 if (auto *SI = dyn_cast<SaturatingInst>(Val: &CB)) {
698 if (willNotOverflow(BO: SI, LVI))
699 return processSaturatingInst(SI, LVI);
700 }
701
702 bool Changed = false;
703
704 // Deopt bundle operands are intended to capture state with minimal
705 // perturbance of the code otherwise. If we can find a constant value for
706 // any such operand and remove a use of the original value, that's
707 // desireable since it may allow further optimization of that value (e.g. via
708 // single use rules in instcombine). Since deopt uses tend to,
709 // idiomatically, appear along rare conditional paths, it's reasonable likely
710 // we may have a conditional fact with which LVI can fold.
711 if (auto DeoptBundle = CB.getOperandBundle(ID: LLVMContext::OB_deopt)) {
712 for (const Use &ConstU : DeoptBundle->Inputs) {
713 Use &U = const_cast<Use&>(ConstU);
714 Value *V = U.get();
715 if (V->getType()->isVectorTy()) continue;
716 if (isa<Constant>(Val: V)) continue;
717
718 Constant *C = LVI->getConstant(V, CxtI: &CB);
719 if (!C) continue;
720 U.set(C);
721 Changed = true;
722 }
723 }
724
725 SmallVector<unsigned, 4> ArgNos;
726 unsigned ArgNo = 0;
727
728 for (Value *V : CB.args()) {
729 PointerType *Type = dyn_cast<PointerType>(Val: V->getType());
730 // Try to mark pointer typed parameters as non-null. We skip the
731 // relatively expensive analysis for constants which are obviously either
732 // null or non-null to start with.
733 if (Type && !CB.paramHasAttr(ArgNo, Kind: Attribute::NonNull) &&
734 !isa<Constant>(Val: V))
735 if (auto *Res = dyn_cast_or_null<ConstantInt>(Val: LVI->getPredicateAt(
736 Pred: ICmpInst::ICMP_EQ, V, C: ConstantPointerNull::get(T: Type), CxtI: &CB,
737 /*UseBlockValue=*/false));
738 Res && Res->isZero())
739 ArgNos.push_back(Elt: ArgNo);
740 ArgNo++;
741 }
742
743 assert(ArgNo == CB.arg_size() && "Call arguments not processed correctly.");
744
745 if (ArgNos.empty())
746 return Changed;
747
748 NumNonNull += ArgNos.size();
749 AttributeList AS = CB.getAttributes();
750 LLVMContext &Ctx = CB.getContext();
751 AS = AS.addParamAttribute(C&: Ctx, ArgNos,
752 A: Attribute::get(Context&: Ctx, Kind: Attribute::NonNull));
753 CB.setAttributes(AS);
754
755 return true;
756}
757
758enum class Domain { NonNegative, NonPositive, Unknown };
759
760static Domain getDomain(const ConstantRange &CR) {
761 if (CR.isAllNonNegative())
762 return Domain::NonNegative;
763 if (CR.icmp(Pred: ICmpInst::ICMP_SLE, Other: APInt::getZero(numBits: CR.getBitWidth())))
764 return Domain::NonPositive;
765 return Domain::Unknown;
766}
767
768/// Try to shrink a sdiv/srem's width down to the smallest power of two that's
769/// sufficient to contain its operands.
770static bool narrowSDivOrSRem(BinaryOperator *Instr, const ConstantRange &LCR,
771 const ConstantRange &RCR) {
772 assert(Instr->getOpcode() == Instruction::SDiv ||
773 Instr->getOpcode() == Instruction::SRem);
774
775 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
776 // operands.
777 unsigned OrigWidth = Instr->getType()->getScalarSizeInBits();
778
779 // What is the smallest bit width that can accommodate the entire value ranges
780 // of both of the operands?
781 unsigned MinSignedBits =
782 std::max(a: LCR.getMinSignedBits(), b: RCR.getMinSignedBits());
783
784 // sdiv/srem is UB if divisor is -1 and divident is INT_MIN, so unless we can
785 // prove that such a combination is impossible, we need to bump the bitwidth.
786 if (RCR.contains(Val: APInt::getAllOnes(numBits: OrigWidth)) &&
787 LCR.contains(Val: APInt::getSignedMinValue(numBits: MinSignedBits).sext(width: OrigWidth)))
788 ++MinSignedBits;
789
790 // Don't shrink below 8 bits wide.
791 unsigned NewWidth = std::max<unsigned>(a: PowerOf2Ceil(A: MinSignedBits), b: 8);
792
793 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
794 // two.
795 if (NewWidth >= OrigWidth)
796 return false;
797
798 ++NumSDivSRemsNarrowed;
799 IRBuilder<> B{Instr};
800 auto *TruncTy = Instr->getType()->getWithNewBitWidth(NewBitWidth: NewWidth);
801 auto *LHS = B.CreateTruncOrBitCast(V: Instr->getOperand(i_nocapture: 0), DestTy: TruncTy,
802 Name: Instr->getName() + ".lhs.trunc");
803 auto *RHS = B.CreateTruncOrBitCast(V: Instr->getOperand(i_nocapture: 1), DestTy: TruncTy,
804 Name: Instr->getName() + ".rhs.trunc");
805 auto *BO = B.CreateBinOp(Opc: Instr->getOpcode(), LHS, RHS, Name: Instr->getName());
806 auto *Sext = B.CreateSExt(V: BO, DestTy: Instr->getType(), Name: Instr->getName() + ".sext");
807 if (auto *BinOp = dyn_cast<BinaryOperator>(Val: BO))
808 if (BinOp->getOpcode() == Instruction::SDiv)
809 BinOp->setIsExact(Instr->isExact());
810
811 Instr->replaceAllUsesWith(V: Sext);
812 Instr->eraseFromParent();
813 return true;
814}
815
816static bool expandUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
817 const ConstantRange &YCR) {
818 Type *Ty = Instr->getType();
819 assert(Instr->getOpcode() == Instruction::UDiv ||
820 Instr->getOpcode() == Instruction::URem);
821 bool IsRem = Instr->getOpcode() == Instruction::URem;
822
823 Value *X = Instr->getOperand(i_nocapture: 0);
824 Value *Y = Instr->getOperand(i_nocapture: 1);
825
826 // X u/ Y -> 0 iff X u< Y
827 // X u% Y -> X iff X u< Y
828 if (XCR.icmp(Pred: ICmpInst::ICMP_ULT, Other: YCR)) {
829 Instr->replaceAllUsesWith(V: IsRem ? X : Constant::getNullValue(Ty));
830 Instr->eraseFromParent();
831 ++NumUDivURemsNarrowedExpanded;
832 return true;
833 }
834
835 // Given
836 // R = X u% Y
837 // We can represent the modulo operation as a loop/self-recursion:
838 // urem_rec(X, Y):
839 // Z = X - Y
840 // if X u< Y
841 // ret X
842 // else
843 // ret urem_rec(Z, Y)
844 // which isn't better, but if we only need a single iteration
845 // to compute the answer, this becomes quite good:
846 // R = X < Y ? X : X - Y iff X u< 2*Y (w/ unsigned saturation)
847 // Now, we do not care about all full multiples of Y in X, they do not change
848 // the answer, thus we could rewrite the expression as:
849 // X* = X - (Y * |_ X / Y _|)
850 // R = X* % Y
851 // so we don't need the *first* iteration to return, we just need to
852 // know *which* iteration will always return, so we could also rewrite it as:
853 // X* = X - (Y * |_ X / Y _|)
854 // R = X* % Y iff X* u< 2*Y (w/ unsigned saturation)
855 // but that does not seem profitable here.
856
857 // Even if we don't know X's range, the divisor may be so large, X can't ever
858 // be 2x larger than that. I.e. if divisor is always negative.
859 if (!XCR.icmp(Pred: ICmpInst::ICMP_ULT, Other: YCR.uadd_sat(Other: YCR)) && !YCR.isAllNegative())
860 return false;
861
862 IRBuilder<> B(Instr);
863 Value *ExpandedOp;
864 if (XCR.icmp(Pred: ICmpInst::ICMP_UGE, Other: YCR)) {
865 // If X is between Y and 2*Y the result is known.
866 if (IsRem)
867 ExpandedOp = B.CreateNUWSub(LHS: X, RHS: Y);
868 else
869 ExpandedOp = ConstantInt::get(Ty: Instr->getType(), V: 1);
870 } else if (IsRem) {
871 // NOTE: this transformation introduces two uses of X,
872 // but it may be undef so we must freeze it first.
873 Value *FrozenX = X;
874 if (!isGuaranteedNotToBeUndef(V: X))
875 FrozenX = B.CreateFreeze(V: X, Name: X->getName() + ".frozen");
876 Value *FrozenY = Y;
877 if (!isGuaranteedNotToBeUndef(V: Y))
878 FrozenY = B.CreateFreeze(V: Y, Name: Y->getName() + ".frozen");
879 auto *AdjX = B.CreateNUWSub(LHS: FrozenX, RHS: FrozenY, Name: Instr->getName() + ".urem");
880 auto *Cmp = B.CreateICmp(P: ICmpInst::ICMP_ULT, LHS: FrozenX, RHS: FrozenY,
881 Name: Instr->getName() + ".cmp");
882 ExpandedOp =
883 B.CreateSelectWithUnknownProfile(C: Cmp, True: FrozenX, False: AdjX, DEBUG_TYPE);
884 } else {
885 auto *Cmp =
886 B.CreateICmp(P: ICmpInst::ICMP_UGE, LHS: X, RHS: Y, Name: Instr->getName() + ".cmp");
887 ExpandedOp = B.CreateZExt(V: Cmp, DestTy: Ty, Name: Instr->getName() + ".udiv");
888 }
889 ExpandedOp->takeName(V: Instr);
890 Instr->replaceAllUsesWith(V: ExpandedOp);
891 Instr->eraseFromParent();
892 ++NumUDivURemsNarrowedExpanded;
893 return true;
894}
895
896/// Try to shrink a udiv/urem's width down to the smallest power of two that's
897/// sufficient to contain its operands.
898static bool narrowUDivOrURem(BinaryOperator *Instr, const ConstantRange &XCR,
899 const ConstantRange &YCR) {
900 assert(Instr->getOpcode() == Instruction::UDiv ||
901 Instr->getOpcode() == Instruction::URem);
902
903 // Find the smallest power of two bitwidth that's sufficient to hold Instr's
904 // operands.
905
906 // What is the smallest bit width that can accommodate the entire value ranges
907 // of both of the operands?
908 unsigned MaxActiveBits = std::max(a: XCR.getActiveBits(), b: YCR.getActiveBits());
909 // Don't shrink below 8 bits wide.
910 unsigned NewWidth = std::max<unsigned>(a: PowerOf2Ceil(A: MaxActiveBits), b: 8);
911
912 // NewWidth might be greater than OrigWidth if OrigWidth is not a power of
913 // two.
914 if (NewWidth >= Instr->getType()->getScalarSizeInBits())
915 return false;
916
917 ++NumUDivURemsNarrowed;
918 IRBuilder<> B{Instr};
919 auto *TruncTy = Instr->getType()->getWithNewBitWidth(NewBitWidth: NewWidth);
920 auto *LHS = B.CreateTruncOrBitCast(V: Instr->getOperand(i_nocapture: 0), DestTy: TruncTy,
921 Name: Instr->getName() + ".lhs.trunc");
922 auto *RHS = B.CreateTruncOrBitCast(V: Instr->getOperand(i_nocapture: 1), DestTy: TruncTy,
923 Name: Instr->getName() + ".rhs.trunc");
924 auto *BO = B.CreateBinOp(Opc: Instr->getOpcode(), LHS, RHS, Name: Instr->getName());
925 auto *Zext = B.CreateZExt(V: BO, DestTy: Instr->getType(), Name: Instr->getName() + ".zext");
926 if (auto *BinOp = dyn_cast<BinaryOperator>(Val: BO))
927 if (BinOp->getOpcode() == Instruction::UDiv)
928 BinOp->setIsExact(Instr->isExact());
929
930 Instr->replaceAllUsesWith(V: Zext);
931 Instr->eraseFromParent();
932 return true;
933}
934
935static bool processUDivOrURem(BinaryOperator *Instr, LazyValueInfo *LVI) {
936 assert(Instr->getOpcode() == Instruction::UDiv ||
937 Instr->getOpcode() == Instruction::URem);
938 ConstantRange XCR = LVI->getConstantRangeAtUse(U: Instr->getOperandUse(i: 0),
939 /*UndefAllowed*/ false);
940 // Allow undef for RHS, as we can assume it is division by zero UB.
941 ConstantRange YCR = LVI->getConstantRangeAtUse(U: Instr->getOperandUse(i: 1),
942 /*UndefAllowed*/ true);
943 if (expandUDivOrURem(Instr, XCR, YCR))
944 return true;
945
946 return narrowUDivOrURem(Instr, XCR, YCR);
947}
948
949static bool processSRem(BinaryOperator *SDI, const ConstantRange &LCR,
950 const ConstantRange &RCR, LazyValueInfo *LVI) {
951 assert(SDI->getOpcode() == Instruction::SRem);
952
953 if (LCR.abs().icmp(Pred: CmpInst::ICMP_ULT, Other: RCR.abs())) {
954 SDI->replaceAllUsesWith(V: SDI->getOperand(i_nocapture: 0));
955 SDI->eraseFromParent();
956 return true;
957 }
958
959 struct Operand {
960 Value *V;
961 Domain D;
962 };
963 std::array<Operand, 2> Ops = {._M_elems: {{.V: SDI->getOperand(i_nocapture: 0), .D: getDomain(CR: LCR)},
964 {.V: SDI->getOperand(i_nocapture: 1), .D: getDomain(CR: RCR)}}};
965 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
966 return false;
967
968 // We know domains of both of the operands!
969 ++NumSRems;
970
971 // We need operands to be non-negative, so negate each one that isn't.
972 for (Operand &Op : Ops) {
973 if (Op.D == Domain::NonNegative)
974 continue;
975 auto *BO = BinaryOperator::CreateNeg(Op: Op.V, Name: Op.V->getName() + ".nonneg",
976 InsertBefore: SDI->getIterator());
977 BO->setDebugLoc(SDI->getDebugLoc());
978 Op.V = BO;
979 }
980
981 auto *URem = BinaryOperator::CreateURem(V1: Ops[0].V, V2: Ops[1].V, Name: SDI->getName(),
982 InsertBefore: SDI->getIterator());
983 URem->setDebugLoc(SDI->getDebugLoc());
984
985 auto *Res = URem;
986
987 // If the divident was non-positive, we need to negate the result.
988 if (Ops[0].D == Domain::NonPositive) {
989 Res = BinaryOperator::CreateNeg(Op: Res, Name: Res->getName() + ".neg",
990 InsertBefore: SDI->getIterator());
991 Res->setDebugLoc(SDI->getDebugLoc());
992 }
993
994 SDI->replaceAllUsesWith(V: Res);
995 SDI->eraseFromParent();
996
997 // Try to simplify our new urem.
998 processUDivOrURem(Instr: URem, LVI);
999
1000 return true;
1001}
1002
1003/// See if LazyValueInfo's ability to exploit edge conditions or range
1004/// information is sufficient to prove the signs of both operands of this SDiv.
1005/// If this is the case, replace the SDiv with a UDiv. Even for local
1006/// conditions, this can sometimes prove conditions instcombine can't by
1007/// exploiting range information.
1008static bool processSDiv(BinaryOperator *SDI, const ConstantRange &LCR,
1009 const ConstantRange &RCR, LazyValueInfo *LVI) {
1010 assert(SDI->getOpcode() == Instruction::SDiv);
1011
1012 // Check whether the division folds to a constant.
1013 ConstantRange DivCR = LCR.sdiv(Other: RCR);
1014 if (const APInt *Elem = DivCR.getSingleElement()) {
1015 SDI->replaceAllUsesWith(V: ConstantInt::get(Ty: SDI->getType(), V: *Elem));
1016 SDI->eraseFromParent();
1017 return true;
1018 }
1019
1020 struct Operand {
1021 Value *V;
1022 Domain D;
1023 };
1024 std::array<Operand, 2> Ops = {._M_elems: {{.V: SDI->getOperand(i_nocapture: 0), .D: getDomain(CR: LCR)},
1025 {.V: SDI->getOperand(i_nocapture: 1), .D: getDomain(CR: RCR)}}};
1026 if (Ops[0].D == Domain::Unknown || Ops[1].D == Domain::Unknown)
1027 return false;
1028
1029 // We know domains of both of the operands!
1030 ++NumSDivs;
1031
1032 // We need operands to be non-negative, so negate each one that isn't.
1033 for (Operand &Op : Ops) {
1034 if (Op.D == Domain::NonNegative)
1035 continue;
1036 auto *BO = BinaryOperator::CreateNeg(Op: Op.V, Name: Op.V->getName() + ".nonneg",
1037 InsertBefore: SDI->getIterator());
1038 BO->setDebugLoc(SDI->getDebugLoc());
1039 Op.V = BO;
1040 }
1041
1042 auto *UDiv = BinaryOperator::CreateUDiv(V1: Ops[0].V, V2: Ops[1].V, Name: SDI->getName(),
1043 InsertBefore: SDI->getIterator());
1044 UDiv->setDebugLoc(SDI->getDebugLoc());
1045 UDiv->setIsExact(SDI->isExact());
1046
1047 auto *Res = UDiv;
1048
1049 // If the operands had two different domains, we need to negate the result.
1050 if (Ops[0].D != Ops[1].D) {
1051 Res = BinaryOperator::CreateNeg(Op: Res, Name: Res->getName() + ".neg",
1052 InsertBefore: SDI->getIterator());
1053 Res->setDebugLoc(SDI->getDebugLoc());
1054 }
1055
1056 SDI->replaceAllUsesWith(V: Res);
1057 SDI->eraseFromParent();
1058
1059 // Try to simplify our new udiv.
1060 processUDivOrURem(Instr: UDiv, LVI);
1061
1062 return true;
1063}
1064
1065static bool processSDivOrSRem(BinaryOperator *Instr, LazyValueInfo *LVI) {
1066 assert(Instr->getOpcode() == Instruction::SDiv ||
1067 Instr->getOpcode() == Instruction::SRem);
1068 ConstantRange LCR =
1069 LVI->getConstantRangeAtUse(U: Instr->getOperandUse(i: 0), /*AllowUndef*/ UndefAllowed: false);
1070 // Allow undef for RHS, as we can assume it is division by zero UB.
1071 ConstantRange RCR =
1072 LVI->getConstantRangeAtUse(U: Instr->getOperandUse(i: 1), /*AlloweUndef*/ UndefAllowed: true);
1073 if (Instr->getOpcode() == Instruction::SDiv)
1074 if (processSDiv(SDI: Instr, LCR, RCR, LVI))
1075 return true;
1076
1077 if (Instr->getOpcode() == Instruction::SRem) {
1078 if (processSRem(SDI: Instr, LCR, RCR, LVI))
1079 return true;
1080 }
1081
1082 return narrowSDivOrSRem(Instr, LCR, RCR);
1083}
1084
1085static bool processAShr(BinaryOperator *SDI, LazyValueInfo *LVI) {
1086 ConstantRange LRange =
1087 LVI->getConstantRangeAtUse(U: SDI->getOperandUse(i: 0), /*UndefAllowed*/ false);
1088 unsigned OrigWidth = SDI->getType()->getScalarSizeInBits();
1089 ConstantRange NegOneOrZero =
1090 ConstantRange(APInt(OrigWidth, (uint64_t)-1, true), APInt(OrigWidth, 1));
1091 if (NegOneOrZero.contains(CR: LRange)) {
1092 // ashr of -1 or 0 never changes the value, so drop the whole instruction
1093 ++NumAShrsRemoved;
1094 SDI->replaceAllUsesWith(V: SDI->getOperand(i_nocapture: 0));
1095 SDI->eraseFromParent();
1096 return true;
1097 }
1098
1099 if (!LRange.isAllNonNegative())
1100 return false;
1101
1102 ++NumAShrsConverted;
1103 auto *BO = BinaryOperator::CreateLShr(V1: SDI->getOperand(i_nocapture: 0), V2: SDI->getOperand(i_nocapture: 1),
1104 Name: "", InsertBefore: SDI->getIterator());
1105 BO->takeName(V: SDI);
1106 BO->setDebugLoc(SDI->getDebugLoc());
1107 BO->setIsExact(SDI->isExact());
1108 SDI->replaceAllUsesWith(V: BO);
1109 SDI->eraseFromParent();
1110
1111 return true;
1112}
1113
1114static bool processSExt(SExtInst *SDI, LazyValueInfo *LVI) {
1115 const Use &Base = SDI->getOperandUse(i: 0);
1116 if (!LVI->getConstantRangeAtUse(U: Base, /*UndefAllowed*/ false)
1117 .isAllNonNegative())
1118 return false;
1119
1120 ++NumSExt;
1121 auto *ZExt = CastInst::CreateZExtOrBitCast(S: Base, Ty: SDI->getType(), Name: "",
1122 InsertBefore: SDI->getIterator());
1123 ZExt->takeName(V: SDI);
1124 ZExt->setDebugLoc(SDI->getDebugLoc());
1125 ZExt->setNonNeg();
1126 SDI->replaceAllUsesWith(V: ZExt);
1127 SDI->eraseFromParent();
1128
1129 return true;
1130}
1131
1132static bool processPossibleNonNeg(PossiblyNonNegInst *I, LazyValueInfo *LVI) {
1133 if (I->hasNonNeg())
1134 return false;
1135
1136 const Use &Base = I->getOperandUse(i: 0);
1137 if (!LVI->getConstantRangeAtUse(U: Base, /*UndefAllowed*/ false)
1138 .isAllNonNegative())
1139 return false;
1140
1141 ++NumNNeg;
1142 I->setNonNeg();
1143
1144 return true;
1145}
1146
1147static bool processZExt(ZExtInst *ZExt, LazyValueInfo *LVI) {
1148 return processPossibleNonNeg(I: cast<PossiblyNonNegInst>(Val: ZExt), LVI);
1149}
1150
1151static bool processUIToFP(UIToFPInst *UIToFP, LazyValueInfo *LVI) {
1152 return processPossibleNonNeg(I: cast<PossiblyNonNegInst>(Val: UIToFP), LVI);
1153}
1154
1155static bool processSIToFP(SIToFPInst *SIToFP, LazyValueInfo *LVI) {
1156 const Use &Base = SIToFP->getOperandUse(i: 0);
1157 if (!LVI->getConstantRangeAtUse(U: Base, /*UndefAllowed*/ false)
1158 .isAllNonNegative())
1159 return false;
1160
1161 ++NumSIToFP;
1162 auto *UIToFP = CastInst::Create(Instruction::UIToFP, S: Base, Ty: SIToFP->getType(),
1163 Name: "", InsertBefore: SIToFP->getIterator());
1164 UIToFP->takeName(V: SIToFP);
1165 UIToFP->setDebugLoc(SIToFP->getDebugLoc());
1166 UIToFP->setNonNeg();
1167 SIToFP->replaceAllUsesWith(V: UIToFP);
1168 SIToFP->eraseFromParent();
1169
1170 return true;
1171}
1172
1173static bool processBinOp(BinaryOperator *BinOp, LazyValueInfo *LVI) {
1174 using OBO = OverflowingBinaryOperator;
1175
1176 bool NSW = BinOp->hasNoSignedWrap();
1177 bool NUW = BinOp->hasNoUnsignedWrap();
1178 if (NSW && NUW)
1179 return false;
1180
1181 Instruction::BinaryOps Opcode = BinOp->getOpcode();
1182 ConstantRange LRange = LVI->getConstantRangeAtUse(U: BinOp->getOperandUse(i: 0),
1183 /*UndefAllowed=*/false);
1184 ConstantRange RRange = LVI->getConstantRangeAtUse(U: BinOp->getOperandUse(i: 1),
1185 /*UndefAllowed=*/false);
1186
1187 bool Changed = false;
1188 bool NewNUW = false, NewNSW = false;
1189 if (!NUW) {
1190 ConstantRange NUWRange = ConstantRange::makeGuaranteedNoWrapRegion(
1191 BinOp: Opcode, Other: RRange, NoWrapKind: OBO::NoUnsignedWrap);
1192 NewNUW = NUWRange.contains(CR: LRange);
1193 Changed |= NewNUW;
1194 }
1195 if (!NSW) {
1196 ConstantRange NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(
1197 BinOp: Opcode, Other: RRange, NoWrapKind: OBO::NoSignedWrap);
1198 NewNSW = NSWRange.contains(CR: LRange);
1199 Changed |= NewNSW;
1200 }
1201
1202 setDeducedOverflowingFlags(V: BinOp, Opcode, NewNSW, NewNUW);
1203
1204 return Changed;
1205}
1206
1207static bool processAnd(BinaryOperator *BinOp, LazyValueInfo *LVI) {
1208 using namespace llvm::PatternMatch;
1209
1210 // Pattern match (and lhs, C) where C includes a superset of bits which might
1211 // be set in lhs. This is a common truncation idiom created by instcombine.
1212 const Use &LHS = BinOp->getOperandUse(i: 0);
1213 const APInt *RHS;
1214 if (!match(V: BinOp->getOperand(i_nocapture: 1), P: m_LowBitMask(V&: RHS)))
1215 return false;
1216
1217 // We can only replace the AND with LHS based on range info if the range does
1218 // not include undef.
1219 ConstantRange LRange =
1220 LVI->getConstantRangeAtUse(U: LHS, /*UndefAllowed=*/false);
1221 if (!LRange.getUnsignedMax().ule(RHS: *RHS))
1222 return false;
1223
1224 BinOp->replaceAllUsesWith(V: LHS);
1225 BinOp->eraseFromParent();
1226 NumAnd++;
1227 return true;
1228}
1229
1230static bool processTrunc(TruncInst *TI, LazyValueInfo *LVI) {
1231 if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap())
1232 return false;
1233
1234 ConstantRange Range =
1235 LVI->getConstantRangeAtUse(U: TI->getOperandUse(i: 0), /*UndefAllowed=*/false);
1236 uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits();
1237 bool Changed = false;
1238
1239 if (!TI->hasNoUnsignedWrap()) {
1240 if (Range.getActiveBits() <= DestWidth) {
1241 TI->setHasNoUnsignedWrap(true);
1242 ++NumNUW;
1243 Changed = true;
1244 }
1245 }
1246
1247 if (!TI->hasNoSignedWrap()) {
1248 if (Range.getMinSignedBits() <= DestWidth) {
1249 TI->setHasNoSignedWrap(true);
1250 ++NumNSW;
1251 Changed = true;
1252 }
1253 }
1254
1255 return Changed;
1256}
1257
1258static bool runImpl(Function &F, LazyValueInfo *LVI, DominatorTree *DT,
1259 const SimplifyQuery &SQ) {
1260 bool FnChanged = false;
1261 std::optional<ConstantRange> RetRange;
1262 if (F.hasExactDefinition() && F.getReturnType()->isIntOrIntVectorTy())
1263 RetRange =
1264 ConstantRange::getEmpty(BitWidth: F.getReturnType()->getScalarSizeInBits());
1265
1266 // Visiting in a pre-order depth-first traversal causes us to simplify early
1267 // blocks before querying later blocks (which require us to analyze early
1268 // blocks). Eagerly simplifying shallow blocks means there is strictly less
1269 // work to do for deep blocks. This also means we don't visit unreachable
1270 // blocks.
1271 for (BasicBlock *BB : depth_first(G: &F.getEntryBlock())) {
1272 bool BBChanged = false;
1273 for (Instruction &II : llvm::make_early_inc_range(Range&: *BB)) {
1274 switch (II.getOpcode()) {
1275 case Instruction::Select:
1276 BBChanged |= processSelect(S: cast<SelectInst>(Val: &II), LVI);
1277 break;
1278 case Instruction::PHI:
1279 BBChanged |= processPHI(P: cast<PHINode>(Val: &II), LVI, DT, SQ);
1280 break;
1281 case Instruction::ICmp:
1282 case Instruction::FCmp:
1283 BBChanged |= processCmp(Cmp: cast<CmpInst>(Val: &II), LVI);
1284 break;
1285 case Instruction::Call:
1286 case Instruction::Invoke:
1287 BBChanged |= processCallSite(CB&: cast<CallBase>(Val&: II), LVI);
1288 break;
1289 case Instruction::SRem:
1290 case Instruction::SDiv:
1291 BBChanged |= processSDivOrSRem(Instr: cast<BinaryOperator>(Val: &II), LVI);
1292 break;
1293 case Instruction::UDiv:
1294 case Instruction::URem:
1295 BBChanged |= processUDivOrURem(Instr: cast<BinaryOperator>(Val: &II), LVI);
1296 break;
1297 case Instruction::AShr:
1298 BBChanged |= processAShr(SDI: cast<BinaryOperator>(Val: &II), LVI);
1299 break;
1300 case Instruction::SExt:
1301 BBChanged |= processSExt(SDI: cast<SExtInst>(Val: &II), LVI);
1302 break;
1303 case Instruction::ZExt:
1304 BBChanged |= processZExt(ZExt: cast<ZExtInst>(Val: &II), LVI);
1305 break;
1306 case Instruction::UIToFP:
1307 BBChanged |= processUIToFP(UIToFP: cast<UIToFPInst>(Val: &II), LVI);
1308 break;
1309 case Instruction::SIToFP:
1310 BBChanged |= processSIToFP(SIToFP: cast<SIToFPInst>(Val: &II), LVI);
1311 break;
1312 case Instruction::Add:
1313 case Instruction::Sub:
1314 case Instruction::Mul:
1315 case Instruction::Shl:
1316 BBChanged |= processBinOp(BinOp: cast<BinaryOperator>(Val: &II), LVI);
1317 break;
1318 case Instruction::And:
1319 BBChanged |= processAnd(BinOp: cast<BinaryOperator>(Val: &II), LVI);
1320 break;
1321 case Instruction::Trunc:
1322 BBChanged |= processTrunc(TI: cast<TruncInst>(Val: &II), LVI);
1323 break;
1324 }
1325 }
1326
1327 Instruction *Term = BB->getTerminator();
1328 switch (Term->getOpcode()) {
1329 case Instruction::Switch:
1330 BBChanged |= processSwitch(I: cast<SwitchInst>(Val: Term), LVI, DT);
1331 break;
1332 case Instruction::Ret: {
1333 auto *RI = cast<ReturnInst>(Val: Term);
1334 // Try to determine the return value if we can. This is mainly here to
1335 // simplify the writing of unit tests, but also helps to enable IPO by
1336 // constant folding the return values of callees.
1337 auto *RetVal = RI->getReturnValue();
1338 if (!RetVal) break; // handle "ret void"
1339 if (RetRange && !RetRange->isFullSet())
1340 RetRange =
1341 RetRange->unionWith(CR: LVI->getConstantRange(V: RetVal, CxtI: RI,
1342 /*UndefAllowed=*/false));
1343
1344 if (isa<Constant>(Val: RetVal)) break; // nothing to do
1345 if (auto *C = getConstantAt(V: RetVal, At: RI, LVI)) {
1346 ++NumReturns;
1347 RI->replaceUsesOfWith(From: RetVal, To: C);
1348 BBChanged = true;
1349 }
1350 }
1351 }
1352
1353 FnChanged |= BBChanged;
1354 }
1355
1356 // Infer range attribute on return value.
1357 if (RetRange && !RetRange->isFullSet()) {
1358 Attribute RangeAttr = F.getRetAttribute(Kind: Attribute::Range);
1359 if (RangeAttr.isValid())
1360 RetRange = RetRange->intersectWith(CR: RangeAttr.getRange());
1361 // Don't add attribute for constant integer returns to reduce noise. These
1362 // are propagated across functions by IPSCCP.
1363 if (!RetRange->isEmptySet() && !RetRange->isSingleElement()) {
1364 F.addRangeRetAttr(CR: *RetRange);
1365 FnChanged = true;
1366 }
1367 }
1368 return FnChanged;
1369}
1370
1371PreservedAnalyses
1372CorrelatedValuePropagationPass::run(Function &F, FunctionAnalysisManager &AM) {
1373 LazyValueInfo *LVI = &AM.getResult<LazyValueAnalysis>(IR&: F);
1374 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
1375
1376 bool Changed = runImpl(F, LVI, DT, SQ: getBestSimplifyQuery(AM, F));
1377
1378 PreservedAnalyses PA;
1379 if (!Changed) {
1380 PA = PreservedAnalyses::all();
1381 } else {
1382#if defined(EXPENSIVE_CHECKS)
1383 assert(DT->verify(DominatorTree::VerificationLevel::Full));
1384#else
1385 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
1386#endif // EXPENSIVE_CHECKS
1387
1388 PA.preserve<DominatorTreeAnalysis>();
1389 PA.preserve<LazyValueAnalysis>();
1390 }
1391
1392 // Keeping LVI alive is expensive, both because it uses a lot of memory, and
1393 // because invalidating values in LVI is expensive. While CVP does preserve
1394 // LVI, we know that passes after JumpThreading+CVP will not need the result
1395 // of this analysis, so we forcefully discard it early.
1396 PA.abandon<LazyValueAnalysis>();
1397 return PA;
1398}
1399