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