xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Analysis/OptimizationRemarkEmitter.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- OptimizationRemarkEmitter.h - Optimization Diagnostic ----*- 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 // Optimization diagnostic interfaces.  It's packaged as an analysis pass so
10 // that by using this service passes become dependent on BFI as well.  BFI is
11 // used to compute the "hotness" of the diagnostic message.
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ANALYSIS_OPTIMIZATIONREMARKEMITTER_H
15 #define LLVM_ANALYSIS_OPTIMIZATIONREMARKEMITTER_H
16 
17 #include "llvm/Analysis/BlockFrequencyInfo.h"
18 #include "llvm/IR/DiagnosticInfo.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/PassManager.h"
21 #include "llvm/Pass.h"
22 #include <optional>
23 
24 namespace llvm {
25 class Function;
26 class Value;
27 
28 /// The optimization diagnostic interface.
29 ///
30 /// It allows reporting when optimizations are performed and when they are not
31 /// along with the reasons for it.  Hotness information of the corresponding
32 /// code region can be included in the remark if DiagnosticsHotnessRequested is
33 /// enabled in the LLVM context.
34 class OptimizationRemarkEmitter {
35 public:
OptimizationRemarkEmitter(const Function * F,BlockFrequencyInfo * BFI)36   OptimizationRemarkEmitter(const Function *F, BlockFrequencyInfo *BFI)
37       : F(F), BFI(BFI) {}
38 
39   /// This variant can be used to generate ORE on demand (without the
40   /// analysis pass).
41   ///
42   /// Note that this ctor has a very different cost depending on whether
43   /// F->getContext().getDiagnosticsHotnessRequested() is on or not.  If it's off
44   /// the operation is free.
45   ///
46   /// Whereas if DiagnosticsHotnessRequested is on, it is fairly expensive
47   /// operation since BFI and all its required analyses are computed.  This is
48   /// for example useful for CGSCC passes that can't use function analyses
49   /// passes in the old PM.
50   OptimizationRemarkEmitter(const Function *F);
51 
OptimizationRemarkEmitter(OptimizationRemarkEmitter && Arg)52   OptimizationRemarkEmitter(OptimizationRemarkEmitter &&Arg)
53       : F(Arg.F), BFI(Arg.BFI) {}
54 
55   OptimizationRemarkEmitter &operator=(OptimizationRemarkEmitter &&RHS) {
56     F = RHS.F;
57     BFI = RHS.BFI;
58     return *this;
59   }
60 
61   /// Handle invalidation events in the new pass manager.
62   bool invalidate(Function &F, const PreservedAnalyses &PA,
63                   FunctionAnalysisManager::Invalidator &Inv);
64 
65   /// Return true iff at least *some* remarks are enabled.
enabled()66   bool enabled() const {
67     return F->getContext().getLLVMRemarkStreamer() ||
68            F->getContext().getDiagHandlerPtr()->isAnyRemarkEnabled();
69   }
70 
71   /// Output the remark via the diagnostic handler and to the
72   /// optimization record file.
73   void emit(DiagnosticInfoOptimizationBase &OptDiag);
74 
75   /// Take a lambda that returns a remark which will be emitted.  Second
76   /// argument is only used to restrict this to functions.
77   template <typename T>
78   void emit(T RemarkBuilder, decltype(RemarkBuilder()) * = nullptr) {
79     // Avoid building the remark unless we know there are at least *some*
80     // remarks enabled. We can't currently check whether remarks are requested
81     // for the calling pass since that requires actually building the remark.
82 
83     if (enabled()) {
84       auto R = RemarkBuilder();
85       static_assert(
86           std::is_base_of<DiagnosticInfoOptimizationBase, decltype(R)>::value,
87           "the lambda passed to emit() must return a remark");
88       emit((DiagnosticInfoOptimizationBase &)R);
89     }
90   }
91 
92   /// Whether we allow for extra compile-time budget to perform more
93   /// analysis to produce fewer false positives.
94   ///
95   /// This is useful when reporting missed optimizations.  In this case we can
96   /// use the extra analysis (1) to filter trivial false positives or (2) to
97   /// provide more context so that non-trivial false positives can be quickly
98   /// detected by the user.
allowExtraAnalysis(StringRef PassName)99   bool allowExtraAnalysis(StringRef PassName) const {
100     return OptimizationRemarkEmitter::allowExtraAnalysis(*F, PassName);
101   }
allowExtraAnalysis(const Function & F,StringRef PassName)102   static bool allowExtraAnalysis(const Function &F, StringRef PassName) {
103     return allowExtraAnalysis(F.getContext(), PassName);
104   }
allowExtraAnalysis(LLVMContext & Ctx,StringRef PassName)105   static bool allowExtraAnalysis(LLVMContext &Ctx, StringRef PassName) {
106     return Ctx.getLLVMRemarkStreamer() ||
107            Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(PassName);
108   }
109 
110 private:
111   const Function *F;
112 
113   BlockFrequencyInfo *BFI;
114 
115   /// If we generate BFI on demand, we need to free it when ORE is freed.
116   std::unique_ptr<BlockFrequencyInfo> OwnedBFI;
117 
118   /// Compute hotness from IR value (currently assumed to be a block) if PGO is
119   /// available.
120   std::optional<uint64_t> computeHotness(const Value *V);
121 
122   /// Similar but use value from \p OptDiag and update hotness there.
123   void computeHotness(DiagnosticInfoIROptimization &OptDiag);
124 
125   /// Only allow verbose messages if we know we're filtering by hotness
126   /// (BFI is only set in this case).
shouldEmitVerbose()127   bool shouldEmitVerbose() { return BFI != nullptr; }
128 
129   OptimizationRemarkEmitter(const OptimizationRemarkEmitter &) = delete;
130   void operator=(const OptimizationRemarkEmitter &) = delete;
131 };
132 
133 /// Add a small namespace to avoid name clashes with the classes used in
134 /// the streaming interface.  We want these to be short for better
135 /// write/readability.
136 namespace ore {
137 using NV = DiagnosticInfoOptimizationBase::Argument;
138 using setIsVerbose = DiagnosticInfoOptimizationBase::setIsVerbose;
139 using setExtraArgs = DiagnosticInfoOptimizationBase::setExtraArgs;
140 }
141 
142 /// OptimizationRemarkEmitter legacy analysis pass
143 ///
144 /// Note that this pass shouldn't generally be marked as preserved by other
145 /// passes.  It's holding onto BFI, so if the pass does not preserve BFI, BFI
146 /// could be freed.
147 class OptimizationRemarkEmitterWrapperPass : public FunctionPass {
148   std::unique_ptr<OptimizationRemarkEmitter> ORE;
149 
150 public:
151   OptimizationRemarkEmitterWrapperPass();
152 
153   bool runOnFunction(Function &F) override;
154 
155   void getAnalysisUsage(AnalysisUsage &AU) const override;
156 
getORE()157   OptimizationRemarkEmitter &getORE() {
158     assert(ORE && "pass not run yet");
159     return *ORE;
160   }
161 
162   static char ID;
163 };
164 
165 class OptimizationRemarkEmitterAnalysis
166     : public AnalysisInfoMixin<OptimizationRemarkEmitterAnalysis> {
167   friend AnalysisInfoMixin<OptimizationRemarkEmitterAnalysis>;
168   static AnalysisKey Key;
169 
170 public:
171   /// Provide the result typedef for this analysis pass.
172   typedef OptimizationRemarkEmitter Result;
173 
174   /// Run the analysis pass over a function and produce BFI.
175   Result run(Function &F, FunctionAnalysisManager &AM);
176 };
177 }
178 #endif // LLVM_ANALYSIS_OPTIMIZATIONREMARKEMITTER_H
179