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