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