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