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