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