1 //===-- llvm/CodeGen/MachineModuleInfo.h ------------------------*- 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 // Collect meta information for a module.  This information should be in a
10 // neutral form that can be used by different debugging and exception handling
11 // schemes.
12 //
13 // The organization of information is primarily clustered around the source
14 // compile units.  The main exception is source line correspondence where
15 // inlining may interleave code from various compile units.
16 //
17 // The following information can be retrieved from the MachineModuleInfo.
18 //
19 //  -- Source directories - Directories are uniqued based on their canonical
20 //     string and assigned a sequential numeric ID (base 1.)
21 //  -- Source files - Files are also uniqued based on their name and directory
22 //     ID.  A file ID is sequential number (base 1.)
23 //  -- Source line correspondence - A vector of file ID, line#, column# triples.
24 //     A DEBUG_LOCATION instruction is generated  by the DAG Legalizer
25 //     corresponding to each entry in the source line list.  This allows a debug
26 //     emitter to generate labels referenced by debug information tables.
27 //
28 //===----------------------------------------------------------------------===//
29 
30 #ifndef LLVM_CODEGEN_MACHINEMODULEINFO_H
31 #define LLVM_CODEGEN_MACHINEMODULEINFO_H
32 
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/PointerIntPair.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Pass.h"
40 #include <memory>
41 #include <utility>
42 #include <vector>
43 
44 namespace llvm {
45 
46 class BasicBlock;
47 class CallInst;
48 class Function;
49 class LLVMTargetMachine;
50 class MMIAddrLabelMap;
51 class MachineFunction;
52 class Module;
53 
54 //===----------------------------------------------------------------------===//
55 /// This class can be derived from and used by targets to hold private
56 /// target-specific information for each Module.  Objects of type are
57 /// accessed/created with MMI::getInfo and destroyed when the MachineModuleInfo
58 /// is destroyed.
59 ///
60 class MachineModuleInfoImpl {
61 public:
62   using StubValueTy = PointerIntPair<MCSymbol *, 1, bool>;
63   using SymbolListTy = std::vector<std::pair<MCSymbol *, StubValueTy>>;
64 
65   virtual ~MachineModuleInfoImpl();
66 
67 protected:
68   /// Return the entries from a DenseMap in a deterministic sorted orer.
69   /// Clears the map.
70   static SymbolListTy getSortedStubs(DenseMap<MCSymbol*, StubValueTy>&);
71 };
72 
73 //===----------------------------------------------------------------------===//
74 /// This class contains meta information specific to a module.  Queries can be
75 /// made by different debugging and exception handling schemes and reformated
76 /// for specific use.
77 ///
78 class MachineModuleInfo {
79   friend class MachineModuleInfoWrapperPass;
80   friend class MachineModuleAnalysis;
81 
82   const LLVMTargetMachine &TM;
83 
84   /// This is the MCContext used for the entire code generator.
85   MCContext Context;
86 
87   /// This is the LLVM Module being worked on.
88   const Module *TheModule;
89 
90   /// This is the object-file-format-specific implementation of
91   /// MachineModuleInfoImpl, which lets targets accumulate whatever info they
92   /// want.
93   MachineModuleInfoImpl *ObjFileMMI;
94 
95   /// \name Exception Handling
96   /// \{
97 
98   /// Vector of all personality functions ever seen. Used to emit common EH
99   /// frames.
100   std::vector<const Function *> Personalities;
101 
102   /// The current call site index being processed, if any. 0 if none.
103   unsigned CurCallSite;
104 
105   /// \}
106 
107   /// This map keeps track of which symbol is being used for the specified
108   /// basic block's address of label.
109   MMIAddrLabelMap *AddrLabelSymbols;
110 
111   // TODO: Ideally, what we'd like is to have a switch that allows emitting
112   // synchronous (precise at call-sites only) CFA into .eh_frame. However,
113   // even under this switch, we'd like .debug_frame to be precise when using
114   // -g. At this moment, there's no way to specify that some CFI directives
115   // go into .eh_frame only, while others go into .debug_frame only.
116 
117   /// True if debugging information is available in this module.
118   bool DbgInfoAvailable;
119 
120   /// True if this module is being built for windows/msvc, and uses floating
121   /// point.  This is used to emit an undefined reference to _fltused.
122   bool UsesMSVCFloatingPoint;
123 
124   /// True if the module calls the __morestack function indirectly, as is
125   /// required under the large code model on x86. This is used to emit
126   /// a definition of a symbol, __morestack_addr, containing the address. See
127   /// comments in lib/Target/X86/X86FrameLowering.cpp for more details.
128   bool UsesMorestackAddr;
129 
130   /// True if the module contains split-stack functions. This is used to
131   /// emit .note.GNU-split-stack section as required by the linker for
132   /// special handling split-stack function calling no-split-stack function.
133   bool HasSplitStack;
134 
135   /// True if the module contains no-split-stack functions. This is used to
136   /// emit .note.GNU-no-split-stack section when it also contains split-stack
137   /// functions.
138   bool HasNosplitStack;
139 
140   /// Maps IR Functions to their corresponding MachineFunctions.
141   DenseMap<const Function*, std::unique_ptr<MachineFunction>> MachineFunctions;
142   /// Next unique number available for a MachineFunction.
143   unsigned NextFnNum = 0;
144   const Function *LastRequest = nullptr; ///< Used for shortcut/cache.
145   MachineFunction *LastResult = nullptr; ///< Used for shortcut/cache.
146 
147   MachineModuleInfo &operator=(MachineModuleInfo &&MMII) = delete;
148 
149 public:
150   explicit MachineModuleInfo(const LLVMTargetMachine *TM = nullptr);
151 
152   MachineModuleInfo(MachineModuleInfo &&MMII);
153 
154   ~MachineModuleInfo();
155 
156   void initialize();
157   void finalize();
158 
159   const LLVMTargetMachine &getTarget() const { return TM; }
160 
161   const MCContext &getContext() const { return Context; }
162   MCContext &getContext() { return Context; }
163 
164   const Module *getModule() const { return TheModule; }
165 
166   /// Returns the MachineFunction constructed for the IR function \p F.
167   /// Creates a new MachineFunction if none exists yet.
168   MachineFunction &getOrCreateMachineFunction(const Function &F);
169 
170   /// \bried Returns the MachineFunction associated to IR function \p F if there
171   /// is one, otherwise nullptr.
172   MachineFunction *getMachineFunction(const Function &F) const;
173 
174   /// Delete the MachineFunction \p MF and reset the link in the IR Function to
175   /// Machine Function map.
176   void deleteMachineFunctionFor(Function &F);
177 
178   /// Keep track of various per-function pieces of information for backends
179   /// that would like to do so.
180   template<typename Ty>
181   Ty &getObjFileInfo() {
182     if (ObjFileMMI == nullptr)
183       ObjFileMMI = new Ty(*this);
184     return *static_cast<Ty*>(ObjFileMMI);
185   }
186 
187   template<typename Ty>
188   const Ty &getObjFileInfo() const {
189     return const_cast<MachineModuleInfo*>(this)->getObjFileInfo<Ty>();
190   }
191 
192   /// Returns true if valid debug info is present.
193   bool hasDebugInfo() const { return DbgInfoAvailable; }
194   void setDebugInfoAvailability(bool avail) { DbgInfoAvailable = avail; }
195 
196   bool usesMSVCFloatingPoint() const { return UsesMSVCFloatingPoint; }
197 
198   void setUsesMSVCFloatingPoint(bool b) { UsesMSVCFloatingPoint = b; }
199 
200   bool usesMorestackAddr() const {
201     return UsesMorestackAddr;
202   }
203 
204   void setUsesMorestackAddr(bool b) {
205     UsesMorestackAddr = b;
206   }
207 
208   bool hasSplitStack() const {
209     return HasSplitStack;
210   }
211 
212   void setHasSplitStack(bool b) {
213     HasSplitStack = b;
214   }
215 
216   bool hasNosplitStack() const {
217     return HasNosplitStack;
218   }
219 
220   void setHasNosplitStack(bool b) {
221     HasNosplitStack = b;
222   }
223 
224   /// Return the symbol to be used for the specified basic block when its
225   /// address is taken.  This cannot be its normal LBB label because the block
226   /// may be accessed outside its containing function.
227   MCSymbol *getAddrLabelSymbol(const BasicBlock *BB) {
228     return getAddrLabelSymbolToEmit(BB).front();
229   }
230 
231   /// Return the symbol to be used for the specified basic block when its
232   /// address is taken.  If other blocks were RAUW'd to this one, we may have
233   /// to emit them as well, return the whole set.
234   ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(const BasicBlock *BB);
235 
236   /// If the specified function has had any references to address-taken blocks
237   /// generated, but the block got deleted, return the symbol now so we can
238   /// emit it.  This prevents emitting a reference to a symbol that has no
239   /// definition.
240   void takeDeletedSymbolsForFunction(const Function *F,
241                                      std::vector<MCSymbol*> &Result);
242 
243   /// \name Exception Handling
244   /// \{
245 
246   /// Set the call site currently being processed.
247   void setCurrentCallSite(unsigned Site) { CurCallSite = Site; }
248 
249   /// Get the call site currently being processed, if any.  return zero if
250   /// none.
251   unsigned getCurrentCallSite() { return CurCallSite; }
252 
253   /// Provide the personality function for the exception information.
254   void addPersonality(const Function *Personality);
255 
256   /// Return array of personality functions ever seen.
257   const std::vector<const Function *>& getPersonalities() const {
258     return Personalities;
259   }
260   /// \}
261 }; // End class MachineModuleInfo
262 
263 class MachineModuleInfoWrapperPass : public ImmutablePass {
264   MachineModuleInfo MMI;
265 
266 public:
267   static char ID; // Pass identification, replacement for typeid
268   explicit MachineModuleInfoWrapperPass(const LLVMTargetMachine *TM = nullptr);
269 
270   // Initialization and Finalization
271   bool doInitialization(Module &) override;
272   bool doFinalization(Module &) override;
273 
274   MachineModuleInfo &getMMI() { return MMI; }
275   const MachineModuleInfo &getMMI() const { return MMI; }
276 };
277 
278 /// An analysis that produces \c MachineInfo for a module.
279 class MachineModuleAnalysis : public AnalysisInfoMixin<MachineModuleAnalysis> {
280   friend AnalysisInfoMixin<MachineModuleAnalysis>;
281   static AnalysisKey Key;
282 
283   const LLVMTargetMachine *TM;
284 
285 public:
286   /// Provide the result type for this analysis pass.
287   using Result = MachineModuleInfo;
288 
289   MachineModuleAnalysis(const LLVMTargetMachine *TM) : TM(TM) {}
290 
291   /// Run the analysis pass and produce machine module information.
292   MachineModuleInfo run(Module &M, ModuleAnalysisManager &);
293 };
294 
295 } // end namespace llvm
296 
297 #endif // LLVM_CODEGEN_MACHINEMODULEINFO_H
298