LLVM 24.0.0git
SCCPSolver.cpp
Go to the documentation of this file.
1//===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
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// \file
10// This file implements the Sparse Conditional Constant Propagation (SCCP)
11// utility.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/SetVector.h"
19#include "llvm/Analysis/Loads.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/InstVisitor.h"
28#include "llvm/IR/NoFolder.h"
31#include "llvm/Support/Debug.h"
35#include <cassert>
36#include <utility>
37#include <vector>
38
39using namespace llvm;
40using namespace PatternMatch;
41
42#define DEBUG_TYPE "sccp"
43
44// The maximum number of range extensions allowed for operations requiring
45// widening.
46static const unsigned MaxNumRangeExtensions = 10;
47
48/// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
53
54namespace llvm {
55
57 return LV.isConstant() ||
59}
60
64
68
70 Constant *Const = getConstantOrNull(V);
71 if (!Const)
72 return false;
73 // Replacing `musttail` instructions with constant breaks `musttail` invariant
74 // unless the call itself can be removed.
75 // Calls with "clang.arc.attachedcall" implicitly use the return value and
76 // those uses cannot be updated with a constant.
78 if (CB && ((CB->isMustTailCall() && !wouldInstructionBeTriviallyDead(CB)) ||
81
82 // Don't zap returns of the callee
83 if (F)
85
86 LLVM_DEBUG(dbgs() << " Can\'t treat the result of call " << *CB
87 << " as a constant\n");
88 return false;
89 }
90
91 // For pointer constants derived from PredicateInfo, the constant may have
92 // different provenance. Take this into account during constant pointer
93 // propagation.
94 if (V->getType()->isPointerTy()) {
95 const auto &LV = getLatticeValueFor(V);
96 if (LV.mayHaveDifferentProvenance()) {
97 const DataLayout &DL = getDataLayout();
98 bool Changed = V->replaceUsesWithIf(Const, [&](Use &U) {
99 bool CanReplace = canReplacePointersInUseIfEqual(U, Const, DL);
100 if (CanReplace)
101 LLVM_DEBUG(dbgs() << " Constant pointer: " << *Const << " = " << *V
102 << '\n');
103 return CanReplace;
104 });
105 return Changed;
106 }
107 }
108
109 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n');
110
111 // Replaces all of the uses of a variable with uses of the constant.
112 V->replaceAllUsesWith(Const);
113 return true;
114}
115
116/// Helper for propagting !implicit.ref metadata from callee to caller before
117/// erasing a call instruction. This ensures that references to global objects
118/// (e.g., copyright strings) are preserved even when calls are optimized away.
120 Function *Callee = CB->getCalledFunction();
121 if (!Callee)
122 return;
123
124 if (!Callee->hasMetadata(LLVMContext::MD_implicit_ref))
125 return;
126
127 Function *Caller = CB->getParent()->getParent();
128 if (!Caller)
129 return;
130
132 Callee->getMetadata(LLVMContext::MD_implicit_ref, MDs);
133 for (MDNode *MD : MDs)
134 Caller->addMetadata(LLVMContext::MD_implicit_ref, *MD);
135}
136
137/// Helper for getting ranges from \p Solver. Instructions inserted during
138/// simplification are unavailable in the solver, so we return a full range for
139/// them.
141 const SmallPtrSetImpl<Value *> &InsertedValues) {
142 if (auto *Const = dyn_cast<Constant>(Op))
143 return Const->toConstantRange();
144 if (InsertedValues.contains(Op)) {
145 unsigned Bitwidth = Op->getType()->getScalarSizeInBits();
146 return ConstantRange::getFull(Bitwidth);
147 }
148 return Solver.getLatticeValueFor(Op).asConstantRange(Op->getType(),
149 /*UndefAllowed=*/false);
150}
151
152/// Try to use \p Inst's value range from \p Solver to infer the NUW flag.
153static bool refineInstruction(SCCPSolver &Solver,
154 const SmallPtrSetImpl<Value *> &InsertedValues,
155 Instruction &Inst) {
156 bool Changed = false;
157 auto GetRange = [&Solver, &InsertedValues](Value *Op) {
158 return getRange(Op, Solver, InsertedValues);
159 };
160
162 if (Inst.hasNoSignedWrap() && Inst.hasNoUnsignedWrap())
163 return false;
164
165 auto RangeA = GetRange(Inst.getOperand(0));
166 auto RangeB = GetRange(Inst.getOperand(1));
167 if (!Inst.hasNoUnsignedWrap()) {
169 Instruction::BinaryOps(Inst.getOpcode()), RangeB,
171 if (NUWRange.contains(RangeA)) {
173 Changed = true;
174 }
175 }
176 if (!Inst.hasNoSignedWrap()) {
178 Instruction::BinaryOps(Inst.getOpcode()), RangeB,
180 if (NSWRange.contains(RangeA)) {
181 Inst.setHasNoSignedWrap();
182 Changed = true;
183 }
184 }
185 } else if (isa<PossiblyNonNegInst>(Inst) && !Inst.hasNonNeg()) {
186 auto Range = GetRange(Inst.getOperand(0));
187 if (Range.isAllNonNegative()) {
188 Inst.setNonNeg();
189 Changed = true;
190 }
191 } else if (TruncInst *TI = dyn_cast<TruncInst>(&Inst)) {
192 if (TI->hasNoSignedWrap() && TI->hasNoUnsignedWrap())
193 return false;
194
195 auto Range = GetRange(Inst.getOperand(0));
196 uint64_t DestWidth = TI->getDestTy()->getScalarSizeInBits();
197 if (!TI->hasNoUnsignedWrap()) {
198 if (Range.getActiveBits() <= DestWidth) {
199 TI->setHasNoUnsignedWrap(true);
200 Changed = true;
201 }
202 }
203 if (!TI->hasNoSignedWrap()) {
204 if (Range.getMinSignedBits() <= DestWidth) {
205 TI->setHasNoSignedWrap(true);
206 Changed = true;
207 }
208 }
209 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst)) {
210 if (GEP->hasNoUnsignedWrap() || !GEP->hasNoUnsignedSignedWrap())
211 return false;
212
213 if (all_of(GEP->indices(),
214 [&](Value *V) { return GetRange(V).isAllNonNegative(); })) {
215 GEP->setNoWrapFlags(GEP->getNoWrapFlags() |
217 Changed = true;
218 }
219 }
220
221 return Changed;
222}
223
224/// Try to replace signed instructions with their unsigned equivalent.
225static bool replaceSignedInst(SCCPSolver &Solver,
226 SmallPtrSetImpl<Value *> &InsertedValues,
227 Instruction &Inst) {
228 // Determine if a signed value is known to be >= 0.
229 auto isNonNegative = [&Solver, &InsertedValues](Value *V) {
230 return getRange(V, Solver, InsertedValues).isAllNonNegative();
231 };
232
233 Instruction *NewInst = nullptr;
234 switch (Inst.getOpcode()) {
235 case Instruction::SIToFP:
236 case Instruction::SExt: {
237 // If the source value is not negative, this is a zext/uitofp.
238 Value *Op0 = Inst.getOperand(0);
239 if (!isNonNegative(Op0))
240 return false;
241 NewInst = CastInst::Create(Inst.getOpcode() == Instruction::SExt
242 ? Instruction::ZExt
243 : Instruction::UIToFP,
244 Op0, Inst.getType(), "", Inst.getIterator());
245 NewInst->setNonNeg();
246 break;
247 }
248 case Instruction::AShr: {
249 // If the shifted value is not negative, this is a logical shift right.
250 Value *Op0 = Inst.getOperand(0);
251 if (!isNonNegative(Op0))
252 return false;
253 NewInst = BinaryOperator::CreateLShr(Op0, Inst.getOperand(1), "", Inst.getIterator());
254 NewInst->setIsExact(Inst.isExact());
255 break;
256 }
257 case Instruction::SDiv:
258 case Instruction::SRem: {
259 // If both operands are not negative, this is the same as udiv/urem.
260 Value *Op0 = Inst.getOperand(0), *Op1 = Inst.getOperand(1);
261 if (!isNonNegative(Op0) || !isNonNegative(Op1))
262 return false;
263 auto NewOpcode = Inst.getOpcode() == Instruction::SDiv ? Instruction::UDiv
264 : Instruction::URem;
265 NewInst = BinaryOperator::Create(NewOpcode, Op0, Op1, "", Inst.getIterator());
266 if (Inst.getOpcode() == Instruction::SDiv)
267 NewInst->setIsExact(Inst.isExact());
268 break;
269 }
270 default:
271 return false;
272 }
273
274 // Wire up the new instruction and update state.
275 assert(NewInst && "Expected replacement instruction");
276 NewInst->takeName(&Inst);
277 InsertedValues.insert(NewInst);
278 Inst.replaceAllUsesWith(NewInst);
279 NewInst->setDebugLoc(Inst.getDebugLoc());
280 Solver.removeLatticeValueFor(&Inst);
281 Inst.eraseFromParent();
282 return true;
283}
284
285/// Try to use \p Inst's value range from \p Solver to simplify it.
287 SmallPtrSetImpl<Value *> &InsertedValues,
288 Instruction &Inst) {
289 auto GetRange = [&Solver, &InsertedValues](Value *Op) {
290 return getRange(Op, Solver, InsertedValues);
291 };
292
293 Value *X;
294 const APInt *RHSC;
295 // Remove masking operations.
296 if (match(&Inst, m_And(m_Value(X), m_LowBitMask(RHSC)))) {
297 ConstantRange LRange = GetRange(X);
298 if (LRange.getUnsignedMax().ule(*RHSC))
299 return X;
300 }
301
302 // Check if we can simplify [us]cmp(X, Y) to X - Y.
303 if (auto *Cmp = dyn_cast<CmpIntrinsic>(&Inst)) {
304 Value *LHS = Cmp->getOperand(0);
305 Value *RHS = Cmp->getOperand(1);
306 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
307 // Bail out on 1-bit comparisons.
308 if (BitWidth == 1)
309 return nullptr;
310 ConstantRange LRange = GetRange(LHS);
311 if (LRange.isSizeLargerThan(3))
312 return nullptr;
313 ConstantRange RRange = GetRange(RHS);
314 if (RRange.isSizeLargerThan(3))
315 return nullptr;
316 ConstantRange RHSLower = RRange.sub(APInt(BitWidth, 1));
317 ConstantRange RHSUpper = RRange.add(APInt(BitWidth, 1));
319 Cmp->isSigned() ? CmpInst::ICMP_SLE : CmpInst::ICMP_ULE;
320 if (!RHSLower.icmp(Pred, LRange) || !LRange.icmp(Pred, RHSUpper))
321 return nullptr;
322
323 IRBuilder<NoFolder> Builder(&Inst);
324 Value *Sub = Builder.CreateSub(LHS, RHS, Inst.getName(), /*HasNUW=*/false,
325 /*HasNSW=*/Cmp->isSigned());
326 InsertedValues.insert(Sub);
327 if (Sub->getType() != Inst.getType()) {
328 Sub = Builder.CreateSExtOrTrunc(Sub, Inst.getType());
329 InsertedValues.insert(Sub);
330 }
331 return Sub;
332 }
333
334 // Relax range checks.
335 if (auto *ICmp = dyn_cast<ICmpInst>(&Inst)) {
336 Value *X;
337 auto MatchTwoInstructionExactRangeCheck =
338 [&]() -> std::optional<ConstantRange> {
339 const APInt *RHSC;
340 if (!match(ICmp->getOperand(1), m_APInt(RHSC)))
341 return std::nullopt;
342
343 Value *LHS = ICmp->getOperand(0);
344 ICmpInst::Predicate Pred = ICmp->getPredicate();
345 const APInt *Offset;
347 return ConstantRange::makeExactICmpRegion(Pred, *RHSC).sub(*Offset);
348 // Match icmp eq/ne X & NegPow2, C
349 if (ICmp->isEquality()) {
350 const APInt *Mask;
351 if (match(LHS, m_OneUse(m_And(m_Value(X), m_NegatedPower2(Mask)))) &&
352 RHSC->countr_zero() >= Mask->countr_zero()) {
353 ConstantRange CR(*RHSC, *RHSC - *Mask);
354 return Pred == ICmpInst::ICMP_EQ ? CR : CR.inverse();
355 }
356 }
357 return std::nullopt;
358 };
359
360 if (auto CR = MatchTwoInstructionExactRangeCheck()) {
361 ConstantRange LRange = GetRange(X);
362 // Early exit if we know nothing about X.
363 if (LRange.isFullSet())
364 return nullptr;
365 auto ConvertCRToICmp =
366 [&](const std::optional<ConstantRange> &NewCR) -> Value * {
368 APInt RHS;
369 // Check if we can represent NewCR as an icmp predicate.
370 if (NewCR && NewCR->getEquivalentICmp(Pred, RHS)) {
371 IRBuilder<NoFolder> Builder(&Inst);
372 Value *NewICmp =
373 Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), RHS));
374 InsertedValues.insert(NewICmp);
375 return NewICmp;
376 }
377 return nullptr;
378 };
379 // We are allowed to refine the comparison to either true or false for out
380 // of range inputs.
381 // Here we refine the comparison to false, and check if we can narrow the
382 // range check to a simpler test.
383 if (auto *V = ConvertCRToICmp(CR->exactIntersectWith(LRange)))
384 return V;
385 // Here we refine the comparison to true, i.e. we relax the range check.
386 if (auto *V = ConvertCRToICmp(CR->exactUnionWith(LRange.inverse())))
387 return V;
388 }
389 }
390
391 return nullptr;
392}
393
395 SmallPtrSetImpl<Value *> &InsertedValues,
396 Statistic &InstRemovedStat,
397 Statistic &InstReplacedStat) {
398 bool MadeChanges = false;
399 for (Instruction &Inst : make_early_inc_range(BB)) {
400 if (Inst.getType()->isVoidTy())
401 continue;
402 if (tryToReplaceWithConstant(&Inst)) {
403 if (isInstructionTriviallyDead(&Inst)) {
404 // Propagate !implicit.ref before erasing the call.
405 if (auto *CB = dyn_cast<CallBase>(&Inst))
407
408 Inst.eraseFromParent();
409 ++InstRemovedStat;
410 }
411 MadeChanges = true;
412 } else if (replaceSignedInst(*this, InsertedValues, Inst)) {
413 MadeChanges = true;
414 ++InstReplacedStat;
415 } else if (refineInstruction(*this, InsertedValues, Inst)) {
416 MadeChanges = true;
417 } else if (auto *V = simplifyInstruction(*this, InsertedValues, Inst)) {
418 Inst.replaceAllUsesWith(V);
419 Inst.eraseFromParent();
420 ++InstRemovedStat;
421 MadeChanges = true;
422 }
423 }
424 return MadeChanges;
425}
426
428 BasicBlock *&NewUnreachableBB) const {
429 SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
430 bool HasNonFeasibleEdges = false;
431 for (BasicBlock *Succ : successors(BB)) {
432 if (isEdgeFeasible(BB, Succ))
433 FeasibleSuccessors.insert(Succ);
434 else
435 HasNonFeasibleEdges = true;
436 }
437
438 // All edges feasible, nothing to do.
439 if (!HasNonFeasibleEdges)
440 return false;
441
442 // SCCP can only determine non-feasible edges for br, switch and indirectbr.
443 Instruction *TI = BB->getTerminator();
445 "Terminator must be a br, switch or indirectbr");
446
447 if (FeasibleSuccessors.size() == 0) {
448 // Branch on undef/poison, replace with unreachable.
451 for (BasicBlock *Succ : successors(BB)) {
452 Succ->removePredecessor(BB);
453 if (SeenSuccs.insert(Succ).second)
454 Updates.push_back({DominatorTree::Delete, BB, Succ});
455 }
456 TI->eraseFromParent();
457 new UnreachableInst(BB->getContext(), BB);
458 DTU.applyUpdatesPermissive(Updates);
459 } else if (FeasibleSuccessors.size() == 1) {
460 // Replace with an unconditional branch to the only feasible successor.
461 BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
463 bool HaveSeenOnlyFeasibleSuccessor = false;
464 for (BasicBlock *Succ : successors(BB)) {
465 if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
466 // Don't remove the edge to the only feasible successor the first time
467 // we see it. We still do need to remove any multi-edges to it though.
468 HaveSeenOnlyFeasibleSuccessor = true;
469 continue;
470 }
471
472 Succ->removePredecessor(BB);
473 Updates.push_back({DominatorTree::Delete, BB, Succ});
474 }
475
476 Instruction *BI = UncondBrInst::Create(OnlyFeasibleSuccessor, BB);
477 BI->setDebugLoc(TI->getDebugLoc());
478 TI->eraseFromParent();
479 DTU.applyUpdatesPermissive(Updates);
480 } else if (FeasibleSuccessors.size() > 1) {
483
484 // If the default destination is unfeasible it will never be taken. Replace
485 // it with a new block with a single Unreachable instruction.
486 BasicBlock *DefaultDest = SI->getDefaultDest();
487 if (!FeasibleSuccessors.contains(DefaultDest)) {
488 if (!NewUnreachableBB) {
489 NewUnreachableBB =
490 BasicBlock::Create(DefaultDest->getContext(), "default.unreachable",
491 DefaultDest->getParent(), DefaultDest);
492 auto *UI =
493 new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB);
494 UI->setDebugLoc(DebugLoc::getTemporary());
495 }
496
497 DefaultDest->removePredecessor(BB);
498 SI->setDefaultDest(NewUnreachableBB);
499 Updates.push_back({DominatorTree::Delete, BB, DefaultDest});
500 Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB});
501 }
502
503 for (auto CI = SI->case_begin(); CI != SI->case_end();) {
504 if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
505 ++CI;
506 continue;
507 }
508
509 BasicBlock *Succ = CI->getCaseSuccessor();
510 Succ->removePredecessor(BB);
511 Updates.push_back({DominatorTree::Delete, BB, Succ});
512 SI.removeCase(CI);
513 // Don't increment CI, as we removed a case.
514 }
515
516 DTU.applyUpdatesPermissive(Updates);
517 } else {
518 llvm_unreachable("Must have at least one feasible successor");
519 }
520 return true;
521}
522
523static void inferAttribute(Function *F, unsigned AttrIndex,
524 const ValueLatticeElement &Val) {
525 // If there is a known constant range for the value, add range attribute.
526 if (Val.isConstantRange() && !Val.getConstantRange().isSingleElement()) {
527 // Do not add range attribute if the value may include undef.
529 return;
530
531 // Take the intersection of the existing attribute and the inferred range.
532 Attribute OldAttr = F->getAttributeAtIndex(AttrIndex, Attribute::Range);
534 if (OldAttr.isValid())
535 CR = CR.intersectWith(OldAttr.getRange());
536 F->addAttributeAtIndex(
537 AttrIndex, Attribute::get(F->getContext(), Attribute::Range, CR));
538 return;
539 }
540 // Infer nonnull attribute.
541 if (Val.isNotConstant() && Val.getNotConstant()->getType()->isPointerTy() &&
542 Val.getNotConstant()->isNullValue() &&
543 !F->hasAttributeAtIndex(AttrIndex, Attribute::NonNull)) {
544 F->addAttributeAtIndex(AttrIndex,
545 Attribute::get(F->getContext(), Attribute::NonNull));
546 }
547}
548
550 for (const auto &[F, ReturnValue] : getTrackedRetVals())
551 inferAttribute(F, AttributeList::ReturnIndex, ReturnValue);
552}
553
556 if (!isBlockExecutable(&F->front()))
557 continue;
558 for (Argument &A : F->args())
559 if (!A.getType()->isStructTy())
560 inferAttribute(F, AttributeList::FirstArgIndex + A.getArgNo(),
562 }
563}
564
565/// Helper class for SCCPSolver. This implements the instruction visitor and
566/// holds all the state.
567class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
568 const DataLayout &DL;
569 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
570 /// Basic blocks that are executable (but may not have been visited yet).
571 SmallPtrSet<BasicBlock *, 8> BBExecutable;
572 /// Basic blocks that are executable and have been visited at least once.
575 ValueState; // The state each value is in.
576
577 /// StructValueState - This maintains ValueState for values that have
578 /// StructType, for example for formal arguments, calls, insertelement, etc.
580
581 /// GlobalValue - If we are tracking any values for the contents of a global
582 /// variable, we keep a mapping from the constant accessor to the element of
583 /// the global, to the currently known value. If the value becomes
584 /// overdefined, it's entry is simply removed from this map.
586
587 /// TrackedRetVals - If we are tracking arguments into and the return
588 /// value out of a function, it will have an entry in this map, indicating
589 /// what the known return value for the function is.
591
592 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
593 /// that return multiple values.
595 TrackedMultipleRetVals;
596
597 /// The set of values whose lattice has been invalidated.
598 /// Populated by resetLatticeValueFor(), cleared after resolving undefs.
599 DenseSet<Value *> Invalidated;
600
601 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
602 /// represented here for efficient lookup.
603 SmallPtrSet<Function *, 16> MRVFunctionsTracked;
604
605 /// A list of functions whose return cannot be modified.
606 SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
607
608 /// TrackingIncomingArguments - This is the set of functions for whose
609 /// arguments we make optimistic assumptions about and try to prove as
610 /// constants.
611 SmallPtrSet<Function *, 16> TrackingIncomingArguments;
612
613 /// Worklist of instructions to re-visit. This only includes instructions
614 /// in blocks that have already been visited at least once.
616
617 /// Current instruction while visiting a block for the first time, used to
618 /// avoid unnecessary instruction worklist insertions. Null if an instruction
619 /// is visited outside a whole-block visitation.
620 Instruction *CurI = nullptr;
621
622 // The BasicBlock work list
624
625 /// KnownFeasibleEdges - Entries in this set are edges which have already had
626 /// PHI nodes retriggered.
627 using Edge = std::pair<BasicBlock *, BasicBlock *>;
628 DenseSet<Edge> KnownFeasibleEdges;
629
631
633
634 LLVMContext &Ctx;
635
636 BumpPtrAllocator PredicateInfoAllocator;
637
638private:
639 ConstantInt *getConstantInt(const ValueLatticeElement &IV, Type *Ty) const {
641 }
642
643 /// Push instruction \p I to the worklist.
644 void pushToWorkList(Instruction *I);
645
646 /// Push users of value \p V to the worklist.
647 void pushUsersToWorkList(Value *V);
648
649 /// Like pushUsersToWorkList(), but also prints a debug message with the
650 /// updated value.
651 void pushUsersToWorkListMsg(ValueLatticeElement &IV, Value *V);
652
653 // markConstant - Make a value be marked as "constant". If the value
654 // is not already a constant, add it to the instruction work list so that
655 // the users of the instruction are updated later.
656 bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
657 bool MayIncludeUndef = false);
658
659 bool markConstant(Value *V, Constant *C) {
660 assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
661 return markConstant(ValueState[V], V, C);
662 }
663
664 bool markNotConstant(ValueLatticeElement &IV, Value *V, Constant *C);
665
666 bool markNotNull(ValueLatticeElement &IV, Value *V) {
667 return markNotConstant(IV, V, Constant::getNullValue(V->getType()));
668 }
669
670 /// markConstantRange - Mark the object as constant range with \p CR. If the
671 /// object is not a constant range with the range \p CR, add it to the
672 /// instruction work list so that the users of the instruction are updated
673 /// later.
674 bool markConstantRange(ValueLatticeElement &IV, Value *V,
675 const ConstantRange &CR);
676
677 // markOverdefined - Make a value be marked as "overdefined". If the
678 // value is not already overdefined, add it to the overdefined instruction
679 // work list so that the users of the instruction are updated later.
680 bool markOverdefined(ValueLatticeElement &IV, Value *V);
681
682 /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
683 /// changes.
684 bool mergeInValue(ValueLatticeElement &IV, Value *V,
685 const ValueLatticeElement &MergeWithV,
687 /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
688
689 /// getValueState - Return the ValueLatticeElement object that corresponds to
690 /// the value. This function handles the case when the value hasn't been seen
691 /// yet by properly seeding constants etc.
692 ValueLatticeElement &getValueState(Value *V) {
693 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
694
695 auto I = ValueState.try_emplace(V);
696 ValueLatticeElement &LV = I.first->second;
697
698 if (!I.second)
699 return LV; // Common case, already in the map.
700
701 if (auto *C = dyn_cast<Constant>(V))
702 LV.markConstant(C); // Constants are constant
703
704 // All others are unknown by default.
705 return LV;
706 }
707
708 /// getStructValueState - Return the ValueLatticeElement object that
709 /// corresponds to the value/field pair. This function handles the case when
710 /// the value hasn't been seen yet by properly seeding constants etc.
711 ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
712 assert(V->getType()->isStructTy() && "Should use getValueState");
713 assert(i < cast<StructType>(V->getType())->getNumElements() &&
714 "Invalid element #");
715
716 auto I = StructValueState.insert(
717 std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
718 ValueLatticeElement &LV = I.first->second;
719
720 if (!I.second)
721 return LV; // Common case, already in the map.
722
723 if (auto *C = dyn_cast<Constant>(V)) {
724 Constant *Elt = C->getAggregateElement(i);
725
726 if (!Elt)
727 LV.markOverdefined(); // Unknown sort of constant.
728 else
729 LV.markConstant(Elt); // Constants are constant.
730 }
731
732 // All others are underdefined by default.
733 return LV;
734 }
735
736 /// Traverse the use-def chain of \p Call, marking itself and its users as
737 /// "unknown" on the way.
738 void invalidate(CallBase *Call) {
740 ToInvalidate.push_back(Call);
741
742 while (!ToInvalidate.empty()) {
743 Instruction *Inst = ToInvalidate.pop_back_val();
744
745 if (!Invalidated.insert(Inst).second)
746 continue;
747
748 if (!BBExecutable.count(Inst->getParent()))
749 continue;
750
751 Value *V = nullptr;
752 // For return instructions we need to invalidate the tracked returns map.
753 // Anything else has its lattice in the value map.
754 if (auto *RetInst = dyn_cast<ReturnInst>(Inst)) {
755 Function *F = RetInst->getParent()->getParent();
756 if (auto It = TrackedRetVals.find(F); It != TrackedRetVals.end()) {
757 It->second = ValueLatticeElement();
758 V = F;
759 } else if (MRVFunctionsTracked.count(F)) {
760 auto *STy = cast<StructType>(F->getReturnType());
761 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
762 TrackedMultipleRetVals[{F, I}] = ValueLatticeElement();
763 V = F;
764 }
765 } else if (auto *STy = dyn_cast<StructType>(Inst->getType())) {
766 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
767 if (auto It = StructValueState.find({Inst, I});
768 It != StructValueState.end()) {
769 It->second = ValueLatticeElement();
770 V = Inst;
771 }
772 }
773 } else if (auto It = ValueState.find(Inst); It != ValueState.end()) {
774 It->second = ValueLatticeElement();
775 V = Inst;
776 }
777
778 if (V) {
779 LLVM_DEBUG(dbgs() << "Invalidated lattice for " << *V << "\n");
780
781 for (User *U : V->users())
782 if (auto *UI = dyn_cast<Instruction>(U))
783 ToInvalidate.push_back(UI);
784
785 auto It = AdditionalUsers.find(V);
786 if (It != AdditionalUsers.end())
787 for (User *U : It->second)
788 if (auto *UI = dyn_cast<Instruction>(U))
789 ToInvalidate.push_back(UI);
790 }
791 }
792 }
793
794 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
795 /// work list if it is not already executable.
796 bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
797
798 // getFeasibleSuccessors - Return a vector of booleans to indicate which
799 // successors are reachable from a given terminator instruction.
800 void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
801
802 // Add U as additional user of V.
803 void addAdditionalUser(Value *V, User *U) { AdditionalUsers[V].insert(U); }
804
805 void handlePredicate(Instruction *I, Value *CopyOf, const PredicateBase *PI);
806 void handleCallOverdefined(CallBase &CB);
807 void handleCallResult(CallBase &CB);
808 void handleCallArguments(CallBase &CB);
809 void handleExtractOfWithOverflow(ExtractValueInst &EVI,
810 const WithOverflowInst *WO, unsigned Idx);
811 bool isInstFullyOverDefined(Instruction &Inst);
812
813private:
814 friend class InstVisitor<SCCPInstVisitor>;
815
816 // visit implementations - Something changed in this instruction. Either an
817 // operand made a transition, or the instruction is newly executable. Change
818 // the value type of I to reflect these changes if appropriate.
819 void visitPHINode(PHINode &I);
820
821 // Terminators
822
823 void visitReturnInst(ReturnInst &I);
824 void visitTerminator(Instruction &TI);
825
826 void visitCastInst(CastInst &I);
827 void visitSelectInst(SelectInst &I);
828 void visitUnaryOperator(Instruction &I);
829 void visitFreezeInst(FreezeInst &I);
830 void visitBinaryOperator(Instruction &I);
831 void visitCmpInst(CmpInst &I);
832 void visitExtractValueInst(ExtractValueInst &EVI);
833 void visitInsertValueInst(InsertValueInst &IVI);
834
835 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
836 markOverdefined(&CPI);
837 visitTerminator(CPI);
838 }
839
840 // Instructions that cannot be folded away.
841
842 void visitStoreInst(StoreInst &I);
843 void visitLoadInst(LoadInst &I);
844 void visitGetElementPtrInst(GetElementPtrInst &I);
845 void visitAllocaInst(AllocaInst &AI);
846
847 void visitInvokeInst(InvokeInst &II) {
848 visitCallBase(II);
849 visitTerminator(II);
850 }
851
852 void visitCallBrInst(CallBrInst &CBI) {
853 visitCallBase(CBI);
854 visitTerminator(CBI);
855 }
856
857 void visitCallBase(CallBase &CB);
858 void visitResumeInst(ResumeInst &I) { /*returns void*/
859 }
860 void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
861 }
862 void visitFenceInst(FenceInst &I) { /*returns void*/
863 }
864
865 void visitInstruction(Instruction &I);
866
867public:
868 const DataLayout &getDataLayout() const { return DL; }
869
871 FnPredicateInfo.insert({&F, std::make_unique<PredicateInfo>(
872 F, DT, AC, PredicateInfoAllocator)});
873 }
874
876 auto It = FnPredicateInfo.find(&F);
877 if (It == FnPredicateInfo.end())
878 return;
879
880 for (BasicBlock &BB : F) {
881 for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
882 if (auto *BC = dyn_cast<BitCastInst>(&Inst)) {
883 if (BC->getType() == BC->getOperand(0)->getType()) {
884 if (It->second->getPredicateInfoFor(&Inst)) {
885 Value *Op = BC->getOperand(0);
886 Inst.replaceAllUsesWith(Op);
887 Inst.eraseFromParent();
888 }
889 }
890 }
891 }
892 }
893 }
894
895 void visitCallInst(CallInst &I) { visitCallBase(I); }
896
898
900 auto It = FnPredicateInfo.find(I->getParent()->getParent());
901 if (It == FnPredicateInfo.end())
902 return nullptr;
903 return It->second->getPredicateInfoFor(I);
904 }
905
907 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
908 LLVMContext &Ctx)
909 : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
910
912 // We only track the contents of scalar globals.
913 if (GV->getValueType()->isSingleValueType()) {
914 ValueLatticeElement &IV = TrackedGlobals[GV];
915 IV.markConstant(GV->getInitializer());
916 }
917 }
918
920 // Add an entry, F -> undef.
921 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
922 MRVFunctionsTracked.insert(F);
923 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
924 TrackedMultipleRetVals.try_emplace(std::make_pair(F, i));
925 } else if (!F->getReturnType()->isVoidTy())
926 TrackedRetVals.try_emplace(F);
927 }
928
930 MustPreserveReturnsInFunctions.insert(F);
931 }
932
934 return MustPreserveReturnsInFunctions.count(F);
935 }
936
938 TrackingIncomingArguments.insert(F);
939 }
940
942 return TrackingIncomingArguments.count(F);
943 }
944
946 return TrackingIncomingArguments;
947 }
948
949 void solve();
950
952
954
956 return BBExecutable.count(BB);
957 }
958
959 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
960
961 std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
962 std::vector<ValueLatticeElement> StructValues;
963 auto *STy = dyn_cast<StructType>(V->getType());
964 assert(STy && "getStructLatticeValueFor() can be called only on structs");
965 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
966 auto I = StructValueState.find(std::make_pair(V, i));
967 assert(I != StructValueState.end() && "Value not in valuemap!");
968 StructValues.push_back(I->second);
969 }
970 return StructValues;
971 }
972
973 void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
974
975 /// Invalidate the Lattice Value of \p Call and its users after specializing
976 /// the call. Then recompute it.
978 // Calls to void returning functions do not need invalidation.
979 Function *F = Call->getCalledFunction();
980 (void)F;
981 assert(!F->getReturnType()->isVoidTy() &&
982 (TrackedRetVals.count(F) || MRVFunctionsTracked.count(F)) &&
983 "All non void specializations should be tracked");
984 invalidate(Call);
985 handleCallResult(*Call);
986 }
987
989 assert(!V->getType()->isStructTy() &&
990 "Should use getStructLatticeValueFor");
991 auto I = ValueState.find(V);
992 assert(I != ValueState.end() &&
993 "V not found in ValueState nor Paramstate map!");
994 return I->second;
995 }
996
998 return TrackedRetVals;
999 }
1000
1003 return TrackedGlobals;
1004 }
1005
1007 return MRVFunctionsTracked;
1008 }
1009
1011 if (auto *STy = dyn_cast<StructType>(V->getType()))
1012 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1013 markOverdefined(getStructValueState(V, i), V);
1014 else
1015 markOverdefined(ValueState[V], V);
1016 }
1017
1019 if (A->getType()->isIntOrIntVectorTy()) {
1020 if (std::optional<ConstantRange> Range = A->getRange())
1022 }
1023 if (A->hasNonNullAttr())
1025 // Assume nothing about the incoming arguments without attributes.
1027 }
1028
1030 if (A->getType()->isStructTy())
1031 return (void)markOverdefined(A);
1032 mergeInValue(ValueState[A], A, getArgAttributeVL(A));
1033 }
1034
1036
1037 Constant *getConstant(const ValueLatticeElement &LV, Type *Ty) const;
1038
1039 Constant *getConstantOrNull(Value *V) const;
1040
1042 const SmallVectorImpl<ArgInfo> &Args);
1043
1045 for (auto &BB : *F)
1046 BBExecutable.erase(&BB);
1047 }
1048
1050 bool ResolvedUndefs = true;
1051 while (ResolvedUndefs) {
1052 solve();
1053 ResolvedUndefs = false;
1054 for (Function &F : M)
1055 ResolvedUndefs |= resolvedUndefsIn(F);
1056 }
1057 }
1058
1060 bool ResolvedUndefs = true;
1061 while (ResolvedUndefs) {
1062 solve();
1063 ResolvedUndefs = false;
1064 for (Function *F : WorkList)
1065 ResolvedUndefs |= resolvedUndefsIn(*F);
1066 }
1067 }
1068
1070 bool ResolvedUndefs = true;
1071 while (ResolvedUndefs) {
1072 solve();
1073 ResolvedUndefs = false;
1074 for (Value *V : Invalidated)
1075 if (auto *I = dyn_cast<Instruction>(V))
1076 ResolvedUndefs |= resolvedUndef(*I);
1077 }
1078 Invalidated.clear();
1079 }
1080};
1081
1082} // namespace llvm
1083
1085 if (!BBExecutable.insert(BB).second)
1086 return false;
1087 LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
1088 BBWorkList.push_back(BB); // Add the block to the work list!
1089 return true;
1090}
1091
1092void SCCPInstVisitor::pushToWorkList(Instruction *I) {
1093 // If we're currently visiting a block, do not push any instructions in the
1094 // same blocks that are after the current one, as they will be visited
1095 // anyway. We do have to push updates to earlier instructions (e.g. phi
1096 // nodes or loads of tracked globals).
1097 if (CurI && I->getParent() == CurI->getParent() && !I->comesBefore(CurI))
1098 return;
1099 // Only push instructions in already visited blocks. Otherwise we'll handle
1100 // it when we visit the block for the first time.
1101 if (BBVisited.contains(I->getParent()))
1102 InstWorkList.insert(I);
1103}
1104
1105void SCCPInstVisitor::pushUsersToWorkList(Value *V) {
1106 for (User *U : V->users())
1107 if (auto *UI = dyn_cast<Instruction>(U))
1108 pushToWorkList(UI);
1109
1110 auto Iter = AdditionalUsers.find(V);
1111 if (Iter != AdditionalUsers.end()) {
1112 // Copy additional users before notifying them of changes, because new
1113 // users may be added, potentially invalidating the iterator.
1115 for (User *U : Iter->second)
1116 if (auto *UI = dyn_cast<Instruction>(U))
1117 ToNotify.push_back(UI);
1118 for (Instruction *UI : ToNotify)
1119 pushToWorkList(UI);
1120 }
1121}
1122
1123void SCCPInstVisitor::pushUsersToWorkListMsg(ValueLatticeElement &IV,
1124 Value *V) {
1125 LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
1126 pushUsersToWorkList(V);
1127}
1128
1129bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
1130 Constant *C, bool MayIncludeUndef) {
1131 if (!IV.markConstant(C, MayIncludeUndef))
1132 return false;
1133 LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
1134 pushUsersToWorkList(V);
1135 return true;
1136}
1137
1138bool SCCPInstVisitor::markNotConstant(ValueLatticeElement &IV, Value *V,
1139 Constant *C) {
1140 if (!IV.markNotConstant(C))
1141 return false;
1142 LLVM_DEBUG(dbgs() << "markNotConstant: " << *C << ": " << *V << '\n');
1143 pushUsersToWorkList(V);
1144 return true;
1145}
1146
1147bool SCCPInstVisitor::markConstantRange(ValueLatticeElement &IV, Value *V,
1148 const ConstantRange &CR) {
1149 if (!IV.markConstantRange(CR))
1150 return false;
1151 LLVM_DEBUG(dbgs() << "markConstantRange: " << CR << ": " << *V << '\n');
1152 pushUsersToWorkList(V);
1153 return true;
1154}
1155
1156bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
1157 if (!IV.markOverdefined())
1158 return false;
1159
1160 LLVM_DEBUG(dbgs() << "markOverdefined: ";
1161 if (auto *F = dyn_cast<Function>(V)) dbgs()
1162 << "Function '" << F->getName() << "'\n";
1163 else dbgs() << *V << '\n');
1164 // Only instructions go on the work list
1165 pushUsersToWorkList(V);
1166 return true;
1167}
1168
1170 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1171 const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
1172 assert(It != TrackedMultipleRetVals.end());
1173 if (!SCCPSolver::isReplaceableConstant(It->second))
1174 return false;
1175 }
1176 return true;
1177}
1178
1180 Type *Ty) const {
1181 if (LV.isConstant()) {
1182 Constant *C = LV.getConstant();
1183 assert(C->getType() == Ty && "Type mismatch");
1184 return C;
1185 }
1186
1187 if (LV.isConstantRange()) {
1188 const auto &CR = LV.getConstantRange();
1189 if (CR.getSingleElement())
1190 return ConstantInt::get(Ty, *CR.getSingleElement());
1191 }
1192 return nullptr;
1193}
1194
1196 Constant *Const = nullptr;
1197 if (V->getType()->isStructTy()) {
1198 std::vector<ValueLatticeElement> LVs = getStructLatticeValueFor(V);
1200 return nullptr;
1201 std::vector<Constant *> ConstVals;
1202 auto *ST = cast<StructType>(V->getType());
1203 for (unsigned I = 0, E = ST->getNumElements(); I != E; ++I) {
1204 const ValueLatticeElement &LV = LVs[I];
1205 ConstVals.push_back(SCCPSolver::isConstant(LV)
1206 ? getConstant(LV, ST->getElementType(I))
1207 : UndefValue::get(ST->getElementType(I)));
1208 }
1209 Const = ConstantStruct::get(ST, ConstVals);
1210 } else {
1213 return nullptr;
1214 Const = SCCPSolver::isConstant(LV) ? getConstant(LV, V->getType())
1215 : UndefValue::get(V->getType());
1216 }
1217 assert(Const && "Constant is nullptr here!");
1218 return Const;
1219}
1220
1222 const SmallVectorImpl<ArgInfo> &Args) {
1223 assert(!Args.empty() && "Specialization without arguments");
1224 assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() &&
1225 "Functions should have the same number of arguments");
1226
1227 auto Iter = Args.begin();
1228 Function::arg_iterator NewArg = F->arg_begin();
1229 Function::arg_iterator OldArg = Args[0].Formal->getParent()->arg_begin();
1230 for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) {
1231
1232 LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
1233 << NewArg->getNameOrAsOperand() << "\n");
1234
1235 // Mark the argument constants in the new function
1236 // or copy the lattice state over from the old function.
1237 if (Iter != Args.end() && Iter->Formal == &*OldArg) {
1238 if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
1239 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
1240 ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
1241 NewValue.markConstant(Iter->Actual->getAggregateElement(I));
1242 }
1243 } else {
1244 ValueState[&*NewArg].markConstant(Iter->Actual);
1245 }
1246 ++Iter;
1247 } else {
1248 if (auto *STy = dyn_cast<StructType>(NewArg->getType())) {
1249 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I) {
1250 ValueLatticeElement &NewValue = StructValueState[{&*NewArg, I}];
1251 NewValue = StructValueState[{&*OldArg, I}];
1252 }
1253 } else {
1254 ValueLatticeElement &NewValue = ValueState[&*NewArg];
1255 NewValue = ValueState[&*OldArg];
1256 }
1257 }
1258 }
1259}
1260
1261void SCCPInstVisitor::visitInstruction(Instruction &I) {
1262 // All the instructions we don't do any special handling for just
1263 // go to overdefined.
1264 LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
1265 markOverdefined(&I);
1266}
1267
1268bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
1269 const ValueLatticeElement &MergeWithV,
1271 if (IV.mergeIn(MergeWithV, Opts)) {
1272 pushUsersToWorkList(V);
1273 LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
1274 << IV << "\n");
1275 return true;
1276 }
1277 return false;
1278}
1279
1280bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
1281 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
1282 return false; // This edge is already known to be executable!
1283
1284 if (!markBlockExecutable(Dest)) {
1285 // If the destination is already executable, we just made an *edge*
1286 // feasible that wasn't before. Revisit the PHI nodes in the block
1287 // because they have potentially new operands.
1288 LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
1289 << " -> " << Dest->getName() << '\n');
1290
1291 for (PHINode &PN : Dest->phis())
1292 pushToWorkList(&PN);
1293 }
1294 return true;
1295}
1296
1297// getFeasibleSuccessors - Return a vector of booleans to indicate which
1298// successors are reachable from a given terminator instruction.
1299void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
1300 SmallVectorImpl<bool> &Succs) {
1301 Succs.resize(TI.getNumSuccessors());
1302 if (isa<UncondBrInst>(TI)) {
1303 Succs[0] = true;
1304 return;
1305 }
1306
1307 if (auto *BI = dyn_cast<CondBrInst>(&TI)) {
1308 const ValueLatticeElement &BCValue = getValueState(BI->getCondition());
1309 ConstantInt *CI = getConstantInt(BCValue, BI->getCondition()->getType());
1310 if (!CI) {
1311 // Overdefined condition variables, and branches on unfoldable constant
1312 // conditions, mean the branch could go either way.
1313 if (!BCValue.isUnknownOrUndef())
1314 Succs[0] = Succs[1] = true;
1315 return;
1316 }
1317
1318 // Constant condition variables mean the branch can only go a single way.
1319 Succs[CI->isZero()] = true;
1320 return;
1321 }
1322
1323 // We cannot analyze special terminators, so consider all successors
1324 // executable.
1325 if (TI.isSpecialTerminator()) {
1326 Succs.assign(TI.getNumSuccessors(), true);
1327 return;
1328 }
1329
1330 if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
1331 if (!SI->getNumCases()) {
1332 Succs[0] = true;
1333 return;
1334 }
1335 const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
1336 if (ConstantInt *CI =
1337 getConstantInt(SCValue, SI->getCondition()->getType())) {
1338 Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
1339 return;
1340 }
1341
1342 // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
1343 // is ready.
1344 if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
1345 const ConstantRange &Range = SCValue.getConstantRange();
1346 unsigned ReachableCaseCount = 0;
1347 for (const auto &Case : SI->cases()) {
1348 const APInt &CaseValue = Case.getCaseValue()->getValue();
1349 if (Range.contains(CaseValue)) {
1350 Succs[Case.getSuccessorIndex()] = true;
1351 ++ReachableCaseCount;
1352 }
1353 }
1354
1355 Succs[SI->case_default()->getSuccessorIndex()] =
1356 Range.isSizeLargerThan(ReachableCaseCount);
1357 return;
1358 }
1359
1360 // Overdefined or unknown condition? All destinations are executable!
1361 if (!SCValue.isUnknownOrUndef())
1362 Succs.assign(TI.getNumSuccessors(), true);
1363 return;
1364 }
1365
1366 // In case of indirect branch and its address is a blockaddress, we mark
1367 // the target as executable.
1368 if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
1369 // Casts are folded by visitCastInst.
1370 const ValueLatticeElement &IBRValue = getValueState(IBR->getAddress());
1372 getConstant(IBRValue, IBR->getAddress()->getType()));
1373 if (!Addr) { // Overdefined or unknown condition?
1374 // All destinations are executable!
1375 if (!IBRValue.isUnknownOrUndef())
1376 Succs.assign(TI.getNumSuccessors(), true);
1377 return;
1378 }
1379
1380 BasicBlock *T = Addr->getBasicBlock();
1381 assert(Addr->getFunction() == T->getParent() &&
1382 "Block address of a different function ?");
1383 for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
1384 // This is the target.
1385 if (IBR->getDestination(i) == T) {
1386 Succs[i] = true;
1387 return;
1388 }
1389 }
1390
1391 // If we didn't find our destination in the IBR successor list, then we
1392 // have undefined behavior. Its ok to assume no successor is executable.
1393 return;
1394 }
1395
1396 LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
1397 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
1398}
1399
1400// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
1401// block to the 'To' basic block is currently feasible.
1403 // Check if we've called markEdgeExecutable on the edge yet. (We could
1404 // be more aggressive and try to consider edges which haven't been marked
1405 // yet, but there isn't any need.)
1406 return KnownFeasibleEdges.count(Edge(From, To));
1407}
1408
1409// visit Implementations - Something changed in this instruction, either an
1410// operand made a transition, or the instruction is newly executable. Change
1411// the value type of I to reflect these changes if appropriate. This method
1412// makes sure to do the following actions:
1413//
1414// 1. If a phi node merges two constants in, and has conflicting value coming
1415// from different branches, or if the PHI node merges in an overdefined
1416// value, then the PHI node becomes overdefined.
1417// 2. If a phi node merges only constants in, and they all agree on value, the
1418// PHI node becomes a constant value equal to that.
1419// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
1420// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
1421// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
1422// 6. If a conditional branch has a value that is constant, make the selected
1423// destination executable
1424// 7. If a conditional branch has a value that is overdefined, make all
1425// successors executable.
1426void SCCPInstVisitor::visitPHINode(PHINode &PN) {
1427 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
1428 // and slow us down a lot. Just mark them overdefined.
1429 if (PN.getNumIncomingValues() > 64)
1430 return (void)markOverdefined(&PN);
1431
1432 if (isInstFullyOverDefined(PN))
1433 return;
1434 SmallVector<unsigned> FeasibleIncomingIndices;
1435 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1436 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
1437 continue;
1438 FeasibleIncomingIndices.push_back(i);
1439 }
1440
1441 // Look at all of the executable operands of the PHI node. If any of them
1442 // are overdefined, the PHI becomes overdefined as well. If they are all
1443 // constant, and they agree with each other, the PHI becomes the identical
1444 // constant. If they are constant and don't agree, the PHI is a constant
1445 // range. If there are no executable operands, the PHI remains unknown.
1446 if (StructType *STy = dyn_cast<StructType>(PN.getType())) {
1447 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1448 ValueLatticeElement PhiState = getStructValueState(&PN, i);
1449 if (PhiState.isOverdefined())
1450 continue;
1451 for (unsigned j : FeasibleIncomingIndices) {
1452 const ValueLatticeElement &IV =
1453 getStructValueState(PN.getIncomingValue(j), i);
1454 PhiState.mergeIn(IV);
1455 if (PhiState.isOverdefined())
1456 break;
1457 }
1458 ValueLatticeElement &PhiStateRef = getStructValueState(&PN, i);
1459 mergeInValue(PhiStateRef, &PN, PhiState,
1460 ValueLatticeElement::MergeOptions().setMaxWidenSteps(
1461 FeasibleIncomingIndices.size() + 1));
1462 PhiStateRef.setNumRangeExtensions(
1463 std::max((unsigned)FeasibleIncomingIndices.size(),
1464 PhiStateRef.getNumRangeExtensions()));
1465 }
1466 } else {
1467 ValueLatticeElement PhiState = getValueState(&PN);
1468 for (unsigned i : FeasibleIncomingIndices) {
1469 const ValueLatticeElement &IV = getValueState(PN.getIncomingValue(i));
1470 PhiState.mergeIn(IV);
1471 if (PhiState.isOverdefined())
1472 break;
1473 }
1474 // We allow up to 1 range extension per active incoming value and one
1475 // additional extension. Note that we manually adjust the number of range
1476 // extensions to match the number of active incoming values. This helps to
1477 // limit multiple extensions caused by the same incoming value, if other
1478 // incoming values are equal.
1479 ValueLatticeElement &PhiStateRef = ValueState[&PN];
1480 mergeInValue(PhiStateRef, &PN, PhiState,
1481 ValueLatticeElement::MergeOptions().setMaxWidenSteps(
1482 FeasibleIncomingIndices.size() + 1));
1483 PhiStateRef.setNumRangeExtensions(
1484 std::max((unsigned)FeasibleIncomingIndices.size(),
1485 PhiStateRef.getNumRangeExtensions()));
1486 }
1487}
1488
1489void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
1490 if (I.getNumOperands() == 0)
1491 return; // ret void
1492
1493 Function *F = I.getParent()->getParent();
1494 Value *ResultOp = I.getOperand(0);
1495
1496 // If we are tracking the return value of this function, merge it in.
1497 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
1498 auto TFRVI = TrackedRetVals.find(F);
1499 if (TFRVI != TrackedRetVals.end()) {
1500 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
1501 return;
1502 }
1503 }
1504
1505 // Handle functions that return multiple values.
1506 if (!TrackedMultipleRetVals.empty()) {
1507 if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
1508 if (MRVFunctionsTracked.count(F))
1509 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1510 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
1511 getStructValueState(ResultOp, i));
1512 }
1513}
1514
1515void SCCPInstVisitor::visitTerminator(Instruction &TI) {
1516 SmallVector<bool, 16> SuccFeasible;
1517 getFeasibleSuccessors(TI, SuccFeasible);
1518
1519 BasicBlock *BB = TI.getParent();
1520
1521 // Mark all feasible successors executable.
1522 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
1523 if (SuccFeasible[i])
1524 markEdgeExecutable(BB, TI.getSuccessor(i));
1525}
1526
1527void SCCPInstVisitor::visitCastInst(CastInst &I) {
1528 // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1529 // discover a concrete value later.
1530 if (ValueState[&I].isOverdefined())
1531 return;
1532
1533 if (auto *BC = dyn_cast<BitCastInst>(&I)) {
1534 if (BC->getType() == BC->getOperand(0)->getType()) {
1535 if (const PredicateBase *PI = getPredicateInfoFor(&I)) {
1536 handlePredicate(&I, I.getOperand(0), PI);
1537 return;
1538 }
1539 }
1540 }
1541
1542 const ValueLatticeElement &OpSt = getValueState(I.getOperand(0));
1543 if (OpSt.isUnknownOrUndef())
1544 return;
1545
1546 if (Constant *OpC = getConstant(OpSt, I.getOperand(0)->getType())) {
1547 // Fold the constant as we build.
1548 if (Constant *C =
1549 ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL)) {
1550 auto &LV = ValueState[&I];
1551 mergeInValue(LV, &I, ValueLatticeElement::get(C));
1552 return;
1553 }
1554 }
1555
1556 // Ignore bitcasts, as they may change the number of vector elements.
1557 if (I.getDestTy()->isIntOrIntVectorTy() &&
1558 I.getSrcTy()->isIntOrIntVectorTy() &&
1559 I.getOpcode() != Instruction::BitCast) {
1560 ConstantRange OpRange =
1561 OpSt.asConstantRange(I.getSrcTy(), /*UndefAllowed=*/false);
1562 auto &LV = getValueState(&I);
1563
1564 Type *DestTy = I.getDestTy();
1565 ConstantRange Res = ConstantRange::getEmpty(DestTy->getScalarSizeInBits());
1566 if (auto *Trunc = dyn_cast<TruncInst>(&I))
1567 Res = OpRange.truncate(DestTy->getScalarSizeInBits(),
1568 Trunc->getNoWrapKind());
1569 else
1570 Res = OpRange.castOp(I.getOpcode(), DestTy->getScalarSizeInBits());
1571 mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
1572 } else
1573 markOverdefined(&I);
1574}
1575
1576void SCCPInstVisitor::handleExtractOfWithOverflow(ExtractValueInst &EVI,
1577 const WithOverflowInst *WO,
1578 unsigned Idx) {
1579 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
1580 Type *Ty = LHS->getType();
1581
1582 addAdditionalUser(LHS, &EVI);
1583 addAdditionalUser(RHS, &EVI);
1584
1585 const ValueLatticeElement &L = getValueState(LHS);
1586 if (L.isUnknownOrUndef())
1587 return; // Wait to resolve.
1588 ConstantRange LR = L.asConstantRange(Ty, /*UndefAllowed=*/false);
1589
1590 const ValueLatticeElement &R = getValueState(RHS);
1591 if (R.isUnknownOrUndef())
1592 return; // Wait to resolve.
1593
1594 ConstantRange RR = R.asConstantRange(Ty, /*UndefAllowed=*/false);
1595 if (Idx == 0) {
1596 ConstantRange Res = LR.binaryOp(WO->getBinaryOp(), RR);
1597 mergeInValue(ValueState[&EVI], &EVI, ValueLatticeElement::getRange(Res));
1598 } else {
1599 assert(Idx == 1 && "Index can only be 0 or 1");
1600 ConstantRange NWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1601 WO->getBinaryOp(), RR, WO->getNoWrapKind());
1602 if (NWRegion.contains(LR))
1603 return (void)markConstant(&EVI, ConstantInt::getFalse(EVI.getType()));
1604 markOverdefined(&EVI);
1605 }
1606}
1607
1608void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
1609 // If this returns a struct, mark all elements over defined, we don't track
1610 // structs in structs.
1611 if (EVI.getType()->isStructTy())
1612 return (void)markOverdefined(&EVI);
1613
1614 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1615 // discover a concrete value later.
1616 if (ValueState[&EVI].isOverdefined())
1617 return (void)markOverdefined(&EVI);
1618
1619 // If this is extracting from more than one level of struct, we don't know.
1620 if (EVI.getNumIndices() != 1)
1621 return (void)markOverdefined(&EVI);
1622
1623 Value *AggVal = EVI.getAggregateOperand();
1624 if (AggVal->getType()->isStructTy()) {
1625 unsigned i = *EVI.idx_begin();
1626 if (auto *WO = dyn_cast<WithOverflowInst>(AggVal))
1627 return handleExtractOfWithOverflow(EVI, WO, i);
1628 ValueLatticeElement EltVal = getStructValueState(AggVal, i);
1629 mergeInValue(ValueState[&EVI], &EVI, EltVal);
1630 } else {
1631 // Otherwise, must be extracting from an array.
1632 return (void)markOverdefined(&EVI);
1633 }
1634}
1635
1636void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
1637 auto *STy = dyn_cast<StructType>(IVI.getType());
1638 if (!STy)
1639 return (void)markOverdefined(&IVI);
1640
1641 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1642 // discover a concrete value later.
1643 if (ValueState[&IVI].isOverdefined())
1644 return (void)markOverdefined(&IVI);
1645
1646 // If this has more than one index, we can't handle it, drive all results to
1647 // undef.
1648 if (IVI.getNumIndices() != 1)
1649 return (void)markOverdefined(&IVI);
1650
1651 Value *Aggr = IVI.getAggregateOperand();
1652 unsigned Idx = *IVI.idx_begin();
1653
1654 // Compute the result based on what we're inserting.
1655 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1656 // This passes through all values that aren't the inserted element.
1657 if (i != Idx) {
1658 ValueLatticeElement EltVal = getStructValueState(Aggr, i);
1659 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
1660 continue;
1661 }
1662
1663 Value *Val = IVI.getInsertedValueOperand();
1664 if (Val->getType()->isStructTy())
1665 // We don't track structs in structs.
1666 markOverdefined(getStructValueState(&IVI, i), &IVI);
1667 else {
1668 ValueLatticeElement InVal = getValueState(Val);
1669 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
1670 }
1671 }
1672}
1673
1674void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
1675 // If this select returns a struct, just mark the result overdefined.
1676 // TODO: We could do a lot better than this if code actually uses this.
1677 if (I.getType()->isStructTy())
1678 return (void)markOverdefined(&I);
1679
1680 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1681 // discover a concrete value later.
1682 if (ValueState[&I].isOverdefined())
1683 return (void)markOverdefined(&I);
1684
1685 const ValueLatticeElement &CondValue = getValueState(I.getCondition());
1686 if (CondValue.isUnknownOrUndef())
1687 return;
1688
1689 if (ConstantInt *CondCB =
1690 getConstantInt(CondValue, I.getCondition()->getType())) {
1691 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
1692 const ValueLatticeElement &OpValState = getValueState(OpVal);
1693 // Safety: ValueState[&I] doesn't invalidate OpValState since it is already
1694 // in the map.
1695 assert(ValueState.contains(&I) && "&I is not in ValueState map.");
1696 mergeInValue(ValueState[&I], &I, OpValState);
1697 return;
1698 }
1699
1700 // Otherwise, the condition is overdefined or a constant we can't evaluate.
1701 // See if we can produce something better than overdefined based on the T/F
1702 // value.
1703 ValueLatticeElement TVal = getValueState(I.getTrueValue());
1704 ValueLatticeElement FVal = getValueState(I.getFalseValue());
1705
1706 ValueLatticeElement &State = ValueState[&I];
1707 bool Changed = State.mergeIn(TVal);
1708 Changed |= State.mergeIn(FVal);
1709 if (Changed)
1710 pushUsersToWorkListMsg(State, &I);
1711}
1712
1713// Handle Unary Operators.
1714void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
1715 ValueLatticeElement V0State = getValueState(I.getOperand(0));
1716
1717 ValueLatticeElement &IV = ValueState[&I];
1718 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1719 // discover a concrete value later.
1720 if (IV.isOverdefined())
1721 return (void)markOverdefined(&I);
1722
1723 // If something is unknown/undef, wait for it to resolve.
1724 if (V0State.isUnknownOrUndef())
1725 return;
1726
1727 if (SCCPSolver::isConstant(V0State))
1728 if (Constant *C = ConstantFoldUnaryOpOperand(
1729 I.getOpcode(), getConstant(V0State, I.getType()), DL))
1730 return (void)markConstant(IV, &I, C);
1731
1732 markOverdefined(&I);
1733}
1734
1735void SCCPInstVisitor::visitFreezeInst(FreezeInst &I) {
1736 // If this freeze returns a struct, just mark the result overdefined.
1737 // TODO: We could do a lot better than this.
1738 if (I.getType()->isStructTy())
1739 return (void)markOverdefined(&I);
1740
1741 ValueLatticeElement V0State = getValueState(I.getOperand(0));
1742 ValueLatticeElement &IV = ValueState[&I];
1743 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1744 // discover a concrete value later.
1745 if (IV.isOverdefined())
1746 return (void)markOverdefined(&I);
1747
1748 // If something is unknown/undef, wait for it to resolve.
1749 if (V0State.isUnknownOrUndef())
1750 return;
1751
1752 if (SCCPSolver::isConstant(V0State) &&
1753 isGuaranteedNotToBeUndefOrPoison(getConstant(V0State, I.getType())))
1754 return (void)markConstant(IV, &I, getConstant(V0State, I.getType()));
1755
1756 markOverdefined(&I);
1757}
1758
1759// Handle Binary Operators.
1760void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
1761 ValueLatticeElement V1State = getValueState(I.getOperand(0));
1762 ValueLatticeElement V2State = getValueState(I.getOperand(1));
1763
1764 ValueLatticeElement &IV = ValueState[&I];
1765 if (IV.isOverdefined())
1766 return;
1767
1768 // If something is undef, wait for it to resolve.
1769 if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
1770 return;
1771
1772 if (V1State.isOverdefined() && V2State.isOverdefined())
1773 return (void)markOverdefined(&I);
1774
1775 // If either of the operands is a constant, try to fold it to a constant.
1776 // TODO: Use information from notconstant better.
1777 if ((V1State.isConstant() || V2State.isConstant())) {
1778 Value *V1 = SCCPSolver::isConstant(V1State)
1779 ? getConstant(V1State, I.getOperand(0)->getType())
1780 : I.getOperand(0);
1781 Value *V2 = SCCPSolver::isConstant(V2State)
1782 ? getConstant(V2State, I.getOperand(1)->getType())
1783 : I.getOperand(1);
1784 Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL, &I));
1785 auto *C = dyn_cast_or_null<Constant>(R);
1786 if (C) {
1787 // Conservatively assume that the result may be based on operands that may
1788 // be undef. Note that we use mergeInValue to combine the constant with
1789 // the existing lattice value for I, as different constants might be found
1790 // after one of the operands go to overdefined, e.g. due to one operand
1791 // being a special floating value.
1792 ValueLatticeElement NewV;
1793 NewV.markConstant(C, /*MayIncludeUndef=*/true);
1794 return (void)mergeInValue(ValueState[&I], &I, NewV);
1795 }
1796 }
1797
1798 // Only use ranges for binary operators on integers.
1799 if (!I.getType()->isIntOrIntVectorTy())
1800 return markOverdefined(&I);
1801
1802 // Try to simplify to a constant range.
1803 ConstantRange A =
1804 V1State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
1805 ConstantRange B =
1806 V2State.asConstantRange(I.getType(), /*UndefAllowed=*/false);
1807
1808 auto *BO = cast<BinaryOperator>(&I);
1809 ConstantRange R = ConstantRange::getEmpty(I.getType()->getScalarSizeInBits());
1810 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO))
1811 R = A.overflowingBinaryOp(BO->getOpcode(), B, OBO->getNoWrapKind());
1812 else
1813 R = A.binaryOp(BO->getOpcode(), B);
1814 mergeInValue(ValueState[&I], &I, ValueLatticeElement::getRange(R));
1815
1816 // TODO: Currently we do not exploit special values that produce something
1817 // better than overdefined with an overdefined operand for vector or floating
1818 // point types, like and <4 x i32> overdefined, zeroinitializer.
1819}
1820
1821// Handle ICmpInst instruction.
1822void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
1823 // Do not cache this lookup, getValueState calls later in the function might
1824 // invalidate the reference.
1825 if (ValueState[&I].isOverdefined())
1826 return (void)markOverdefined(&I);
1827
1828 Value *Op1 = I.getOperand(0);
1829 Value *Op2 = I.getOperand(1);
1830
1831 // For parameters, use ParamState which includes constant range info if
1832 // available.
1833 auto V1State = getValueState(Op1);
1834 auto V2State = getValueState(Op2);
1835
1836 Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
1837 if (C) {
1838 ValueLatticeElement CV;
1839 CV.markConstant(C);
1840 mergeInValue(ValueState[&I], &I, CV);
1841 return;
1842 }
1843
1844 // If operands are still unknown, wait for it to resolve.
1845 if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1846 !SCCPSolver::isConstant(ValueState[&I]))
1847 return;
1848
1849 markOverdefined(&I);
1850}
1851
1852// Handle getelementptr instructions. If all operands are constants then we
1853// can turn this into a getelementptr ConstantExpr.
1854void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
1855 if (ValueState[&I].isOverdefined())
1856 return (void)markOverdefined(&I);
1857
1858 const ValueLatticeElement &PtrState = getValueState(I.getPointerOperand());
1859 if (PtrState.isUnknownOrUndef())
1860 return;
1861
1862 // gep inbounds/nuw of non-null is non-null.
1863 if (PtrState.isNotConstant() && PtrState.getNotConstant()->isNullValue()) {
1864 if (I.hasNoUnsignedWrap() ||
1865 (I.isInBounds() &&
1866 !NullPointerIsDefined(I.getFunction(), I.getAddressSpace())))
1867 return (void)markNotNull(ValueState[&I], &I);
1868 return (void)markOverdefined(&I);
1869 }
1870
1872 Operands.reserve(I.getNumOperands());
1873 bool PtrMayHaveDifferentProvenance = PtrState.mayHaveDifferentProvenance();
1874
1875 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1876 const ValueLatticeElement &State = getValueState(I.getOperand(i));
1877 if (State.isUnknownOrUndef())
1878 return; // Operands are not resolved yet.
1879
1880 if (Constant *C = getConstant(State, I.getOperand(i)->getType())) {
1881 Operands.push_back(C);
1882 continue;
1883 }
1884
1885 return (void)markOverdefined(&I);
1886 }
1887
1888 if (Constant *C = ConstantFoldInstOperands(&I, Operands, DL)) {
1889 mergeInValue(ValueState[&I], &I, ValueLatticeElement::get(C));
1890 // The pointer operand's lattice has found to be a constant, however, the
1891 // returned pointer of the GEP may not be freely substituted, as it may have
1892 // been derived from a pointer with potentially different provenance.
1893 if (PtrMayHaveDifferentProvenance)
1894 ValueState[&I].setMayHaveDifferentProvenance(true);
1895 } else
1896 markOverdefined(&I);
1897}
1898
1899void SCCPInstVisitor::visitAllocaInst(AllocaInst &I) {
1900 if (!NullPointerIsDefined(I.getFunction(), I.getAddressSpace()))
1901 return (void)markNotNull(ValueState[&I], &I);
1902
1903 markOverdefined(&I);
1904}
1905
1906void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
1907 // If this store is of a struct, ignore it.
1908 if (SI.getOperand(0)->getType()->isStructTy())
1909 return;
1910
1911 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1912 return;
1913
1914 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1915 auto I = TrackedGlobals.find(GV);
1916 if (I == TrackedGlobals.end())
1917 return;
1918
1919 // Get the value we are storing into the global, then merge it.
1920 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1921 ValueLatticeElement::MergeOptions().setCheckWiden(false));
1922 if (I->second.isOverdefined())
1923 TrackedGlobals.erase(I); // No need to keep tracking this!
1924}
1925
1927 if (const auto *CB = dyn_cast<CallBase>(I)) {
1928 if (CB->getType()->isIntOrIntVectorTy())
1929 if (std::optional<ConstantRange> Range = CB->getRange())
1931 if (CB->getType()->isPointerTy() && CB->isReturnNonNull())
1934 }
1935
1936 if (I->getType()->isIntOrIntVectorTy())
1937 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1940 if (I->hasMetadata(LLVMContext::MD_nonnull))
1943
1945}
1946
1947// Handle load instructions. If the operand is a constant pointer to a constant
1948// global, we can replace the load with the loaded constant value!
1949void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
1950 // If this load is of a struct or the load is volatile, just mark the result
1951 // as overdefined.
1952 if (I.getType()->isStructTy() || I.isVolatile())
1953 return (void)markOverdefined(&I);
1954
1955 // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1956 // discover a concrete value later.
1957 if (ValueState[&I].isOverdefined())
1958 return (void)markOverdefined(&I);
1959
1960 const ValueLatticeElement &PtrVal = getValueState(I.getOperand(0));
1961 if (PtrVal.isUnknownOrUndef())
1962 return; // The pointer is not resolved yet!
1963
1964 if (SCCPSolver::isConstant(PtrVal)) {
1965 Constant *Ptr = getConstant(PtrVal, I.getOperand(0)->getType());
1966 ValueLatticeElement &IV = ValueState[&I];
1967
1968 // load null is undefined.
1969 if (isa<ConstantPointerNull>(Ptr)) {
1970 if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1971 return (void)markOverdefined(IV, &I);
1972 else
1973 return;
1974 }
1975
1976 // Transform load (constant global) into the value loaded.
1977 if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1978 if (!TrackedGlobals.empty()) {
1979 // If we are tracking this global, merge in the known value for it.
1980 auto It = TrackedGlobals.find(GV);
1981 if (It != TrackedGlobals.end()) {
1982 mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1983 return;
1984 }
1985 }
1986 }
1987
1988 // Transform load from a constant into a constant if possible.
1989 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL))
1990 return (void)markConstant(IV, &I, C);
1991 }
1992
1993 // Fall back to metadata.
1994 mergeInValue(ValueState[&I], &I, getValueFromMetadata(&I));
1995}
1996
1997void SCCPInstVisitor::visitCallBase(CallBase &CB) {
1998 handleCallResult(CB);
1999 handleCallArguments(CB);
2000}
2001
2002void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
2004
2005 // Void return and not tracking callee, just bail.
2006 if (CB.getType()->isVoidTy())
2007 return;
2008
2009 // Always mark struct return as overdefined.
2010 if (CB.getType()->isStructTy())
2011 return (void)markOverdefined(&CB);
2012
2013 // Otherwise, if we have a single return value case, and if the function is
2014 // a declaration, maybe we can constant fold it.
2015 if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
2017 for (const Use &A : CB.args()) {
2018 if (A.get()->getType()->isStructTy())
2019 return markOverdefined(&CB); // Can't handle struct args.
2020 if (A.get()->getType()->isMetadataTy())
2021 continue; // Carried in CB, not allowed in Operands.
2022 const ValueLatticeElement &State = getValueState(A);
2023
2024 if (State.isUnknownOrUndef())
2025 return; // Operands are not resolved yet.
2026 if (SCCPSolver::isOverdefined(State))
2027 return (void)markOverdefined(&CB);
2028 assert(SCCPSolver::isConstant(State) && "Unknown state!");
2029 Operands.push_back(getConstant(State, A->getType()));
2030 }
2031
2032 if (SCCPSolver::isOverdefined(getValueState(&CB)))
2033 return (void)markOverdefined(&CB);
2034
2035 // If we can constant fold this, mark the result of the call as a
2036 // constant.
2037 if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F))) {
2038 mergeInValue(ValueState[&CB], &CB, ValueLatticeElement::get(C));
2039 return;
2040 }
2041 }
2042
2043 // Fall back to metadata.
2044 mergeInValue(ValueState[&CB], &CB, getValueFromMetadata(&CB));
2045}
2046
2047void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
2049 // If this is a local function that doesn't have its address taken, mark its
2050 // entry block executable and merge in the actual arguments to the call into
2051 // the formal arguments of the function.
2052 if (TrackingIncomingArguments.count(F)) {
2053 markBlockExecutable(&F->front());
2054
2055 // Propagate information from this call site into the callee.
2056 auto CAI = CB.arg_begin();
2057 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2058 ++AI, ++CAI) {
2059 // If this argument is byval, and if the function is not readonly, there
2060 // will be an implicit copy formed of the input aggregate.
2061 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
2062 markOverdefined(&*AI);
2063 continue;
2064 }
2065
2066 if (auto *STy = dyn_cast<StructType>(AI->getType())) {
2067 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2068 ValueLatticeElement CallArg = getStructValueState(*CAI, i);
2069 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
2071 }
2072 } else {
2073 ValueLatticeElement CallArg =
2074 getValueState(*CAI).intersect(getArgAttributeVL(&*AI));
2075 mergeInValue(ValueState[&*AI], &*AI, CallArg, getMaxWidenStepsOpts());
2076 }
2077 }
2078 }
2079}
2080
2081void SCCPInstVisitor::handlePredicate(Instruction *I, Value *CopyOf,
2082 const PredicateBase *PI) {
2083 ValueLatticeElement CopyOfVal = getValueState(CopyOf);
2084 const std::optional<PredicateConstraint> &Constraint = PI->getConstraint();
2085 if (!Constraint) {
2086 mergeInValue(ValueState[I], I, CopyOfVal);
2087 return;
2088 }
2089
2090 CmpInst::Predicate Pred = Constraint->Predicate;
2091 Value *OtherOp = Constraint->OtherOp;
2092
2093 // Wait until OtherOp is resolved.
2094 if (getValueState(OtherOp).isUnknown()) {
2095 addAdditionalUser(OtherOp, I);
2096 return;
2097 }
2098
2099 ValueLatticeElement CondVal = getValueState(OtherOp);
2100 ValueLatticeElement &IV = ValueState[I];
2101 if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
2102 auto ImposedCR =
2103 ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
2104
2105 // Get the range imposed by the condition.
2106 if (CondVal.isConstantRange())
2108 Pred, CondVal.getConstantRange());
2109
2110 // Combine range info for the original value with the new range from the
2111 // condition.
2112 auto CopyOfCR = CopyOfVal.asConstantRange(CopyOf->getType(),
2113 /*UndefAllowed=*/true);
2114 // Treat an unresolved input like a full range.
2115 if (CopyOfCR.isEmptySet())
2116 CopyOfCR = ConstantRange::getFull(CopyOfCR.getBitWidth());
2117 auto NewCR = ImposedCR.intersectWith(CopyOfCR);
2118 // If the existing information is != x, do not use the information from
2119 // a chained predicate, as the != x information is more likely to be
2120 // helpful in practice.
2121 if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
2122 NewCR = std::move(CopyOfCR);
2123
2124 // The new range is based on a branch condition. That guarantees that
2125 // neither of the compare operands can be undef in the branch targets,
2126 // unless we have conditions that are always true/false (e.g. icmp ule
2127 // i32, %a, i32_max). For the latter overdefined/empty range will be
2128 // inferred, but the branch will get folded accordingly anyways.
2129 addAdditionalUser(OtherOp, I);
2130 mergeInValue(
2131 IV, I, ValueLatticeElement::getRange(NewCR, /*MayIncludeUndef*/ false));
2132 return;
2133 } else if (Pred == CmpInst::ICMP_EQ &&
2134 (CondVal.isConstant() || CondVal.isNotConstant())) {
2135 // For non-integer values or integer constant expressions, only
2136 // propagate equal constants or not-constants.
2137 addAdditionalUser(OtherOp, I);
2138 if (CopyOf->getType()->isPointerTy())
2139 CondVal.setMayHaveDifferentProvenance(true);
2140 mergeInValue(IV, I, CondVal);
2141 return;
2142 } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) {
2143 // Propagate inequalities.
2144 addAdditionalUser(OtherOp, I);
2145 mergeInValue(IV, I, ValueLatticeElement::getNot(CondVal.getConstant()));
2146 return;
2147 }
2148
2149 return (void)mergeInValue(IV, I, CopyOfVal);
2150}
2151
2152void SCCPInstVisitor::handleCallResult(CallBase &CB) {
2154
2155 if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
2156 if (II->getIntrinsicID() == Intrinsic::vscale) {
2157 unsigned BitWidth = CB.getType()->getScalarSizeInBits();
2158 const ConstantRange Result = getVScaleRange(II->getFunction(), BitWidth);
2159 return (void)mergeInValue(ValueState[II], II,
2161 }
2162 if (II->getIntrinsicID() == Intrinsic::experimental_get_vector_length) {
2163 Value *CountArg = II->getArgOperand(0);
2164 Value *VF = II->getArgOperand(1);
2165 bool Scalable = cast<ConstantInt>(II->getArgOperand(2))->isOne();
2166
2167 // Computation happens in the larger type.
2168 unsigned BitWidth = std::max(CountArg->getType()->getScalarSizeInBits(),
2169 VF->getType()->getScalarSizeInBits());
2170
2171 ConstantRange Count = getValueState(CountArg)
2172 .asConstantRange(CountArg->getType(), false)
2173 .zeroExtend(BitWidth);
2174 ConstantRange MaxLanes = getValueState(VF)
2175 .asConstantRange(VF->getType(), false)
2176 .zeroExtend(BitWidth);
2177 if (Scalable)
2178 MaxLanes =
2179 MaxLanes.multiply(getVScaleRange(II->getFunction(), BitWidth));
2180
2181 // The result is always less than both Count and MaxLanes.
2182 ConstantRange Result = ConstantRange::getNonEmpty(
2184 APIntOps::umin(Count.getUnsignedMax(), MaxLanes.getUnsignedMax()) +
2185 1);
2186
2187 // If Count <= MaxLanes, getvectorlength(Count, MaxLanes) = Count
2188 if (Count.icmp(CmpInst::ICMP_ULE, MaxLanes))
2189 Result = std::move(Count);
2190
2191 Result = Result.truncate(II->getType()->getScalarSizeInBits());
2192 return (void)mergeInValue(ValueState[II], II,
2194 }
2195
2196 if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
2197 // Compute result range for intrinsics supported by ConstantRange.
2198 // Do this even if we don't know a range for all operands, as we may
2199 // still know something about the result range, e.g. of abs(x).
2201 for (Value *Op : II->args()) {
2202 const ValueLatticeElement &State = getValueState(Op);
2203 if (State.isUnknownOrUndef())
2204 return;
2205 OpRanges.push_back(
2206 State.asConstantRange(Op->getType(), /*UndefAllowed=*/false));
2207 }
2208
2209 ConstantRange Result =
2210 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
2211 return (void)mergeInValue(ValueState[II], II,
2213 }
2214 }
2215
2216 // The common case is that we aren't tracking the callee, either because we
2217 // are not doing interprocedural analysis or the callee is indirect, or is
2218 // external. Handle these cases first.
2219 if (!F || F->isDeclaration())
2220 return handleCallOverdefined(CB);
2221
2222 // If this is a single/zero retval case, see if we're tracking the function.
2223 if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
2224 if (!MRVFunctionsTracked.count(F))
2225 return handleCallOverdefined(CB); // Not tracking this callee.
2226
2227 // If we are tracking this callee, propagate the result of the function
2228 // into this call site.
2229 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2230 mergeInValue(getStructValueState(&CB, i), &CB,
2231 TrackedMultipleRetVals[std::make_pair(F, i)],
2233 } else {
2234 auto TFRVI = TrackedRetVals.find(F);
2235 if (TFRVI == TrackedRetVals.end())
2236 return handleCallOverdefined(CB); // Not tracking this callee.
2237
2238 // If so, propagate the return value of the callee into this call result.
2239 mergeInValue(ValueState[&CB], &CB, TFRVI->second, getMaxWidenStepsOpts());
2240 }
2241}
2242
2243bool SCCPInstVisitor::isInstFullyOverDefined(Instruction &Inst) {
2244 // For structure Type, we handle each member separately.
2245 // A structure object won't be considered as overdefined when
2246 // there is at least one member that is not overdefined.
2247 if (StructType *STy = dyn_cast<StructType>(Inst.getType())) {
2248 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i) {
2249 if (!getStructValueState(&Inst, i).isOverdefined())
2250 return false;
2251 }
2252 return true;
2253 }
2254
2255 return getValueState(&Inst).isOverdefined();
2256}
2257
2259 // Process the work lists until they are empty!
2260 while (!BBWorkList.empty() || !InstWorkList.empty()) {
2261 // Process the instruction work list.
2262 while (!InstWorkList.empty()) {
2263 Instruction *I = InstWorkList.pop_back_val();
2264 Invalidated.erase(I);
2265
2266 LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
2267
2268 visit(I);
2269 }
2270
2271 // Process the basic block work list.
2272 while (!BBWorkList.empty()) {
2273 BasicBlock *BB = BBWorkList.pop_back_val();
2274 BBVisited.insert(BB);
2275
2276 LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
2277 for (Instruction &I : *BB) {
2278 CurI = &I;
2279 visit(I);
2280 }
2281 CurI = nullptr;
2282 }
2283 }
2284}
2285
2287 // Look for instructions which produce undef values.
2288 if (I.getType()->isVoidTy())
2289 return false;
2290
2291 if (auto *STy = dyn_cast<StructType>(I.getType())) {
2292 // Only a few things that can be structs matter for undef.
2293
2294 // Tracked calls must never be marked overdefined in resolvedUndefsIn.
2295 if (auto *CB = dyn_cast<CallBase>(&I))
2296 if (Function *F = CB->getCalledFunction())
2297 if (MRVFunctionsTracked.count(F))
2298 return false;
2299
2300 // extractvalue and insertvalue don't need to be marked; they are
2301 // tracked as precisely as their operands.
2303 return false;
2304 // Send the results of everything else to overdefined. We could be
2305 // more precise than this but it isn't worth bothering.
2306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2307 ValueLatticeElement &LV = getStructValueState(&I, i);
2308 if (LV.isUnknown()) {
2309 markOverdefined(LV, &I);
2310 return true;
2311 }
2312 }
2313 return false;
2314 }
2315
2316 ValueLatticeElement &LV = getValueState(&I);
2317 if (!LV.isUnknown())
2318 return false;
2319
2320 // There are two reasons a call can have an undef result
2321 // 1. It could be tracked.
2322 // 2. It could be constant-foldable.
2323 // Because of the way we solve return values, tracked calls must
2324 // never be marked overdefined in resolvedUndefsIn.
2325 if (auto *CB = dyn_cast<CallBase>(&I))
2326 if (Function *F = CB->getCalledFunction())
2327 if (TrackedRetVals.count(F))
2328 return false;
2329
2330 if (isa<LoadInst>(I)) {
2331 // A load here means one of two things: a load of undef from a global,
2332 // a load from an unknown pointer. Either way, having it return undef
2333 // is okay.
2334 return false;
2335 }
2336
2337 markOverdefined(&I);
2338 return true;
2339}
2340
2341/// While solving the dataflow for a function, we don't compute a result for
2342/// operations with an undef operand, to allow undef to be lowered to a
2343/// constant later. For example, constant folding of "zext i8 undef to i16"
2344/// would result in "i16 0", and if undef is later lowered to "i8 1", then the
2345/// zext result would become "i16 1" and would result into an overdefined
2346/// lattice value once merged with the previous result. Not computing the
2347/// result of the zext (treating undef the same as unknown) allows us to handle
2348/// a later undef->constant lowering more optimally.
2349///
2350/// However, if the operand remains undef when the solver returns, we do need
2351/// to assign some result to the instruction (otherwise we would treat it as
2352/// unreachable). For simplicity, we mark any instructions that are still
2353/// unknown as overdefined.
2355 bool MadeChange = false;
2356 for (BasicBlock &BB : F) {
2357 if (!BBExecutable.count(&BB))
2358 continue;
2359
2360 for (Instruction &I : BB)
2361 MadeChange |= resolvedUndef(I);
2362 }
2363
2364 LLVM_DEBUG(if (MadeChange) dbgs()
2365 << "\nResolved undefs in " << F.getName() << '\n');
2366
2367 return MadeChange;
2368}
2369
2370//===----------------------------------------------------------------------===//
2371//
2372// SCCPSolver implementations
2373//
2375 const DataLayout &DL,
2376 std::function<const TargetLibraryInfo &(Function &)> GetTLI,
2377 LLVMContext &Ctx)
2378 : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
2379
2380SCCPSolver::~SCCPSolver() = default;
2381
2383 return Visitor->getDataLayout();
2384}
2385
2387 AssumptionCache &AC) {
2388 Visitor->addPredicateInfo(F, DT, AC);
2389}
2390
2392 Visitor->removeSSACopies(F);
2393}
2394
2396 return Visitor->markBlockExecutable(BB);
2397}
2398
2400 return Visitor->getPredicateInfoFor(I);
2401}
2402
2404 Visitor->trackValueOfGlobalVariable(GV);
2405}
2406
2408 Visitor->addTrackedFunction(F);
2409}
2410
2412 Visitor->addToMustPreserveReturnsInFunctions(F);
2413}
2414
2416 return Visitor->mustPreserveReturn(F);
2417}
2418
2420 Visitor->addArgumentTrackedFunction(F);
2421}
2422
2424 return Visitor->isArgumentTrackedFunction(F);
2425}
2426
2429 return Visitor->getArgumentTrackedFunctions();
2430}
2431
2432void SCCPSolver::solve() { Visitor->solve(); }
2433
2435 return Visitor->resolvedUndefsIn(F);
2436}
2437
2439 Visitor->solveWhileResolvedUndefsIn(M);
2440}
2441
2442void
2444 Visitor->solveWhileResolvedUndefsIn(WorkList);
2445}
2446
2448 Visitor->solveWhileResolvedUndefs();
2449}
2450
2452 return Visitor->isBlockExecutable(BB);
2453}
2454
2456 return Visitor->isEdgeFeasible(From, To);
2457}
2458
2459std::vector<ValueLatticeElement>
2461 return Visitor->getStructLatticeValueFor(V);
2462}
2463
2465 return Visitor->removeLatticeValueFor(V);
2466}
2467
2469 Visitor->resetLatticeValueFor(Call);
2470}
2471
2473 return Visitor->getLatticeValueFor(V);
2474}
2475
2478 return Visitor->getTrackedRetVals();
2479}
2480
2483 return Visitor->getTrackedGlobals();
2484}
2485
2487 return Visitor->getMRVFunctionsTracked();
2488}
2489
2490void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
2491
2493 Visitor->trackValueOfArgument(V);
2494}
2495
2497 return Visitor->isStructLatticeConstant(F, STy);
2498}
2499
2501 Type *Ty) const {
2502 return Visitor->getConstant(LV, Ty);
2503}
2504
2506 return Visitor->getConstantOrNull(V);
2507}
2508
2510 const SmallVectorImpl<ArgInfo> &Args) {
2511 Visitor->setLatticeValueForSpecializationArguments(F, Args);
2512}
2513
2515 Visitor->markFunctionUnreachable(F);
2516}
2517
2518void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
2519
2520void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Hexagon Common GEP
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts()
Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
static const unsigned MaxNumRangeExtensions
static ValueLatticeElement getValueFromMetadata(const Instruction *I)
SI Fold Operands
std::pair< BasicBlock *, BasicBlock * > Edge
This file implements a set that has insertion order iteration characteristics.
static ConstantInt * getConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
A cache of @llvm.assume calls within a function.
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
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
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.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
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 Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
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.
Function * getFunction() const
Definition Constants.h:1126
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
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.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
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 ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
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_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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 ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
static LLVM_ABI ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
LLVM_ABI bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
static LLVM_ABI bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
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 ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
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 ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getTemporary()
Definition DebugLoc.h:152
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
This instruction extracts a struct member or array element value from an aggregate value.
unsigned getNumIndices() const
idx_iterator idx_begin() const
This class represents a freeze function that returns random concrete value if an operand is either a ...
Argument * arg_iterator
Definition Function.h:73
static GEPNoWrapFlags noUnsignedWrap()
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Module * getParent()
Get the module that this global value is contained inside of...
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
This instruction inserts a struct field of array element value into an aggregate value.
Value * getInsertedValueOperand()
unsigned getNumIndices() const
idx_iterator idx_begin() const
Base class for instruction visitors.
Definition InstVisitor.h:78
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
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 BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool hasNonNeg() const LLVM_READONLY
Determine whether the the nneg flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
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.
bool isSpecialTerminator() const
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1069
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
LLVM_ABI std::optional< PredicateConstraint > getConstraint() const
Fetch condition in the form of PredicateConstraint, if possible.
Return a value (possibly void), from a function.
Helper class for SCCPSolver.
const MapVector< Function *, ValueLatticeElement > & getTrackedRetVals() const
const PredicateBase * getPredicateInfoFor(Instruction *I)
std::vector< ValueLatticeElement > getStructLatticeValueFor(Value *V) const
bool resolvedUndef(Instruction &I)
void markFunctionUnreachable(Function *F)
bool markBlockExecutable(BasicBlock *BB)
bool resolvedUndefsIn(Function &F)
While solving the dataflow for a function, we don't compute a result for operations with an undef ope...
Constant * getConstant(const ValueLatticeElement &LV, Type *Ty) const
SCCPInstVisitor(const DataLayout &DL, std::function< const TargetLibraryInfo &(Function &)> GetTLI, LLVMContext &Ctx)
const DenseMap< GlobalVariable *, ValueLatticeElement > & getTrackedGlobals() const
const ValueLatticeElement & getLatticeValueFor(Value *V) const
void removeLatticeValueFor(Value *V)
void trackValueOfArgument(Argument *A)
void visitCallInst(CallInst &I)
void markOverdefined(Value *V)
bool isArgumentTrackedFunction(Function *F)
void addTrackedFunction(Function *F)
void solveWhileResolvedUndefsIn(Module &M)
void trackValueOfGlobalVariable(GlobalVariable *GV)
Constant * getConstantOrNull(Value *V) const
void removeSSACopies(Function &F)
const SmallPtrSet< Function *, 16 > & getMRVFunctionsTracked() const
const SmallPtrSetImpl< Function * > & getArgumentTrackedFunctions() const
void resetLatticeValueFor(CallBase *Call)
Invalidate the Lattice Value of Call and its users after specializing the call.
ValueLatticeElement getArgAttributeVL(Argument *A)
void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC)
void addToMustPreserveReturnsInFunctions(Function *F)
void addArgumentTrackedFunction(Function *F)
bool isStructLatticeConstant(Function *F, StructType *STy)
void solveWhileResolvedUndefsIn(SmallVectorImpl< Function * > &WorkList)
bool isBlockExecutable(BasicBlock *BB) const
bool mustPreserveReturn(Function *F)
void setLatticeValueForSpecializationArguments(Function *F, const SmallVectorImpl< ArgInfo > &Args)
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const
const DataLayout & getDataLayout() const
SCCPSolver - This interface class is a general purpose solver for Sparse Conditional Constant Propaga...
Definition SCCPSolver.h:66
LLVM_ABI void visitCall(CallInst &I)
LLVM_ABI ~SCCPSolver()
LLVM_ABI void resetLatticeValueFor(CallBase *Call)
Invalidate the Lattice Value of Call and its users after specializing the call.
LLVM_ABI void trackValueOfGlobalVariable(GlobalVariable *GV)
trackValueOfGlobalVariable - Clients can use this method to inform the SCCPSolver that it should trac...
LLVM_ABI bool tryToReplaceWithConstant(Value *V)
LLVM_ABI void inferArgAttributes() const
LLVM_ABI bool isStructLatticeConstant(Function *F, StructType *STy)
LLVM_ABI void addPredicateInfo(Function &F, DominatorTree &DT, AssumptionCache &AC)
LLVM_ABI void solve()
Solve - Solve for constants and executable blocks.
LLVM_ABI void visit(Instruction *I)
LLVM_ABI void trackValueOfArgument(Argument *V)
trackValueOfArgument - Mark the specified argument overdefined unless it have range attribute.
LLVM_ABI const DenseMap< GlobalVariable *, ValueLatticeElement > & getTrackedGlobals() const
getTrackedGlobals - Get and return the set of inferred initializers for global variables.
LLVM_ABI void addTrackedFunction(Function *F)
addTrackedFunction - If the SCCP solver is supposed to track calls into and out of the specified func...
LLVM_ABI void solveWhileResolvedUndefsIn(Module &M)
LLVM_ABI const PredicateBase * getPredicateInfoFor(Instruction *I)
LLVM_ABI const SmallPtrSetImpl< Function * > & getArgumentTrackedFunctions() const
LLVM_ABI const SmallPtrSet< Function *, 16 > & getMRVFunctionsTracked() const
getMRVFunctionsTracked - Get the set of functions which return multiple values tracked by the pass.
LLVM_ABI bool resolvedUndefsIn(Function &F)
resolvedUndefsIn - While solving the dataflow for a function, we assume that branches on undef values...
LLVM_ABI const DataLayout & getDataLayout() const
LLVM_ABI void addArgumentTrackedFunction(Function *F)
static LLVM_ABI bool isReplaceableConstant(const ValueLatticeElement &LV)
LLVM_ABI void solveWhileResolvedUndefs()
LLVM_ABI void removeLatticeValueFor(Value *V)
LLVM_ABI std::vector< ValueLatticeElement > getStructLatticeValueFor(Value *V) const
LLVM_ABI Constant * getConstantOrNull(Value *V) const
Return either a Constant or nullptr for a given Value.
LLVM_ABI bool simplifyInstsInBlock(BasicBlock &BB, SmallPtrSetImpl< Value * > &InsertedValues, Statistic &InstRemovedStat, Statistic &InstReplacedStat)
LLVM_ABI Constant * getConstant(const ValueLatticeElement &LV, Type *Ty) const
Helper to return a Constant if LV is either a constant or a constant range with a single element.
LLVM_ABI const ValueLatticeElement & getLatticeValueFor(Value *V) const
LLVM_ABI void addToMustPreserveReturnsInFunctions(Function *F)
Add function to the list of functions whose return cannot be modified.
LLVM_ABI bool removeNonFeasibleEdges(BasicBlock *BB, DomTreeUpdater &DTU, BasicBlock *&NewUnreachableBB) const
LLVM_ABI bool isBlockExecutable(BasicBlock *BB) const
LLVM_ABI void inferReturnAttributes() const
LLVM_ABI bool markBlockExecutable(BasicBlock *BB)
markBlockExecutable - This method can be used by clients to mark all of the blocks that are known to ...
LLVM_ABI void setLatticeValueForSpecializationArguments(Function *F, const SmallVectorImpl< ArgInfo > &Args)
Set the Lattice Value for the arguments of a specialization F.
static LLVM_ABI bool isConstant(const ValueLatticeElement &LV)
LLVM_ABI const MapVector< Function *, ValueLatticeElement > & getTrackedRetVals() const
getTrackedRetVals - Get the inferred return value map.
LLVM_ABI bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const
LLVM_ABI bool mustPreserveReturn(Function *F)
Returns true if the return of the given function cannot be modified.
static LLVM_ABI bool isOverdefined(const ValueLatticeElement &LV)
LLVM_ABI void markFunctionUnreachable(Function *F)
Mark all of the blocks in function F non-executable.
LLVM_ABI bool isArgumentTrackedFunction(Function *F)
Returns true if the given function is in the solver's set of argument-tracked functions.
LLVM_ABI SCCPSolver(const DataLayout &DL, std::function< const TargetLibraryInfo &(Function &)> GetTLI, LLVMContext &Ctx)
LLVM_ABI void markOverdefined(Value *V)
markOverdefined - Mark the specified value overdefined.
LLVM_ABI void removeSSACopies(Function &F)
This class represents the LLVM 'select' instruction.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
Provides information about what library functions are available for the current target.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:311
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:276
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
This class represents lattice values for constants.
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
void setMayHaveDifferentProvenance(bool V)
LLVM_ABI Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other, const DataLayout &DL) const
true, false or undef constants, or nullptr if the comparison cannot be evaluated.
bool isConstantRangeIncludingUndef() const
static ValueLatticeElement getNot(Constant *C)
ConstantRange asConstantRange(unsigned BW, bool UndefAllowed=false) const
void setNumRangeExtensions(unsigned N)
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
static ValueLatticeElement get(Constant *C)
unsigned getNumRangeExtensions() const
Constant * getNotConstant() const
LLVM_ABI ValueLatticeElement intersect(const ValueLatticeElement &Other) const
Combine two sets of facts about the same value into a single set of facts.
Constant * getConstant() const
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
bool mayHaveDifferentProvenance() const
bool markConstant(Constant *V, bool MayIncludeUndef=false)
static ValueLatticeElement getOverdefined()
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:461
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Represents an op.with.overflow intrinsic.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2289
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
static bool replaceSignedInst(SCCPSolver &Solver, SmallPtrSetImpl< Value * > &InsertedValues, Instruction &Inst)
Try to replace signed instructions with their unsigned equivalent.
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
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)
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
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:633
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
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
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
NoopStatistic Statistic
Definition Statistic.h:162
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:862
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:422
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
static void propagateImplicitRefFromCall(CallBase *CB)
Helper for propagting !implicit.ref metadata from callee to caller before erasing a call instruction.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
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
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
static bool refineInstruction(SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues, Instruction &Inst)
Try to use Inst's value range from Solver to infer the NUW flag.
static void inferAttribute(Function *F, unsigned AttrIndex, const ValueLatticeElement &Val)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
Struct to control some aspects related to merging constant ranges.
MergeOptions & setMaxWidenSteps(unsigned Steps=1)