|
| 1 | +//===------------------------------------------------------------*- 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 | +#include "llvm/Transforms/Scalar/DropUnnecessaryAssumes.h" |
| 10 | +#include "llvm/Analysis/AssumptionCache.h" |
| 11 | +#include "llvm/Analysis/ValueTracking.h" |
| 12 | +#include "llvm/IR/IntrinsicInst.h" |
| 13 | +#include "llvm/IR/PatternMatch.h" |
| 14 | +#include "llvm/Transforms/Utils/Local.h" |
| 15 | + |
| 16 | +using namespace llvm; |
| 17 | +using namespace llvm::PatternMatch; |
| 18 | + |
| 19 | +PreservedAnalyses |
| 20 | +DropUnnecessaryAssumesPass::run(Function &F, FunctionAnalysisManager &FAM) { |
| 21 | + AssumptionCache &AC = FAM.getResult<AssumptionAnalysis>(F); |
| 22 | + bool Changed = false; |
| 23 | + |
| 24 | + for (AssumptionCache::ResultElem &Elem : AC.assumptions()) { |
| 25 | + auto *Assume = cast_or_null<AssumeInst>(Elem.Assume); |
| 26 | + if (!Assume) |
| 27 | + continue; |
| 28 | + |
| 29 | + // TODO: Handle assumes with operand bundles. |
| 30 | + if (Assume->hasOperandBundles()) |
| 31 | + continue; |
| 32 | + |
| 33 | + Value *Cond = Assume->getArgOperand(0); |
| 34 | + // Don't drop type tests, which have special semantics. |
| 35 | + if (match(Cond, m_Intrinsic<Intrinsic::type_test>())) |
| 36 | + continue; |
| 37 | + |
| 38 | + SmallPtrSet<Value *, 8> Affected; |
| 39 | + findValuesAffectedByCondition(Cond, /*IsAssume=*/true, |
| 40 | + [&](Value *A) { Affected.insert(A); }); |
| 41 | + |
| 42 | + // If all the affected uses have only one use (part of the assume), then |
| 43 | + // the assume does not provide useful information. Note that additional |
| 44 | + // users may appear as a result of inlining and CSE, so we should only |
| 45 | + // make this assumption late in the optimization pipeline. |
| 46 | + // TODO: Handle dead cyclic usages. |
| 47 | + // TODO: Handle multiple dead assumes on the same value. |
| 48 | + if (!all_of(Affected, match_fn(m_OneUse(m_Value())))) |
| 49 | + continue; |
| 50 | + |
| 51 | + Assume->eraseFromParent(); |
| 52 | + RecursivelyDeleteTriviallyDeadInstructions(Cond); |
| 53 | + Changed = true; |
| 54 | + } |
| 55 | + |
| 56 | + if (Changed) { |
| 57 | + PreservedAnalyses PA; |
| 58 | + PA.preserveSet<CFGAnalyses>(); |
| 59 | + return PA; |
| 60 | + } |
| 61 | + return PreservedAnalyses::all(); |
| 62 | +} |
0 commit comments