Re-land r235154-r235156 under the existing -sehprepare flag
[oota-llvm.git] / include / llvm / CodeGen / MachineModuleInfo.h
1 //===-- llvm/CodeGen/MachineModuleInfo.h ------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect meta information for a module.  This information should be in a
11 // neutral form that can be used by different debugging and exception handling
12 // schemes.
13 //
14 // The organization of information is primarily clustered around the source
15 // compile units.  The main exception is source line correspondence where
16 // inlining may interleave code from various compile units.
17 //
18 // The following information can be retrieved from the MachineModuleInfo.
19 //
20 //  -- Source directories - Directories are uniqued based on their canonical
21 //     string and assigned a sequential numeric ID (base 1.)
22 //  -- Source files - Files are also uniqued based on their name and directory
23 //     ID.  A file ID is sequential number (base 1.)
24 //  -- Source line correspondence - A vector of file ID, line#, column# triples.
25 //     A DEBUG_LOCATION instruction is generated  by the DAG Legalizer
26 //     corresponding to each entry in the source line list.  This allows a debug
27 //     emitter to generate labels referenced by debug information tables.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #ifndef LLVM_CODEGEN_MACHINEMODULEINFO_H
32 #define LLVM_CODEGEN_MACHINEMODULEINFO_H
33
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/PointerIntPair.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Analysis/LibCallSemantics.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/ValueHandle.h"
42 #include "llvm/MC/MCContext.h"
43 #include "llvm/MC/MachineLocation.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Support/DataTypes.h"
46 #include "llvm/Support/Dwarf.h"
47
48 namespace llvm {
49
50 //===----------------------------------------------------------------------===//
51 // Forward declarations.
52 class Constant;
53 class GlobalVariable;
54 class BlockAddress;
55 class MDNode;
56 class MMIAddrLabelMap;
57 class MachineBasicBlock;
58 class MachineFunction;
59 class Module;
60 class PointerType;
61 class StructType;
62 struct WinEHFuncInfo;
63
64 struct SEHHandler {
65   // Filter or finally function. Null indicates a catch-all.
66   const Function *FilterOrFinally;
67
68   // Address of block to recover at. Null for a finally handler.
69   const BlockAddress *RecoverBA;
70 };
71
72 //===----------------------------------------------------------------------===//
73 /// LandingPadInfo - This structure is used to retain landing pad info for
74 /// the current function.
75 ///
76 struct LandingPadInfo {
77   MachineBasicBlock *LandingPadBlock;      // Landing pad block.
78   SmallVector<MCSymbol *, 1> BeginLabels;  // Labels prior to invoke.
79   SmallVector<MCSymbol *, 1> EndLabels;    // Labels after invoke.
80   SmallVector<MCSymbol *, 1> ClauseLabels; // Labels for each clause.
81   SmallVector<SEHHandler, 1> SEHHandlers;  // SEH handlers active at this lpad.
82   MCSymbol *LandingPadLabel;               // Label at beginning of landing pad.
83   const Function *Personality;             // Personality function.
84   std::vector<int> TypeIds;               // List of type ids (filters negative).
85   int WinEHState;                         // WinEH specific state number.
86
87   explicit LandingPadInfo(MachineBasicBlock *MBB)
88       : LandingPadBlock(MBB), LandingPadLabel(nullptr), Personality(nullptr),
89         WinEHState(-1) {}
90 };
91
92 //===----------------------------------------------------------------------===//
93 /// MachineModuleInfoImpl - This class can be derived from and used by targets
94 /// to hold private target-specific information for each Module.  Objects of
95 /// type are accessed/created with MMI::getInfo and destroyed when the
96 /// MachineModuleInfo is destroyed.
97 /// 
98 class MachineModuleInfoImpl {
99 public:
100   typedef PointerIntPair<MCSymbol*, 1, bool> StubValueTy;
101   virtual ~MachineModuleInfoImpl();
102   typedef std::vector<std::pair<MCSymbol*, StubValueTy> > SymbolListTy;
103 protected:
104
105   /// Return the entries from a DenseMap in a deterministic sorted orer.
106   /// Clears the map.
107   static SymbolListTy getSortedStubs(DenseMap<MCSymbol*, StubValueTy>&);
108 };
109
110 //===----------------------------------------------------------------------===//
111 /// MachineModuleInfo - This class contains meta information specific to a
112 /// module.  Queries can be made by different debugging and exception handling
113 /// schemes and reformated for specific use.
114 ///
115 class MachineModuleInfo : public ImmutablePass {
116   /// Context - This is the MCContext used for the entire code generator.
117   MCContext Context;
118
119   /// TheModule - This is the LLVM Module being worked on.
120   const Module *TheModule;
121
122   /// ObjFileMMI - This is the object-file-format-specific implementation of
123   /// MachineModuleInfoImpl, which lets targets accumulate whatever info they
124   /// want.
125   MachineModuleInfoImpl *ObjFileMMI;
126
127   /// List of moves done by a function's prolog.  Used to construct frame maps
128   /// by debug and exception handling consumers.
129   std::vector<MCCFIInstruction> FrameInstructions;
130
131   /// LandingPads - List of LandingPadInfo describing the landing pad
132   /// information in the current function.
133   std::vector<LandingPadInfo> LandingPads;
134
135   /// LPadToCallSiteMap - Map a landing pad's EH symbol to the call site
136   /// indexes.
137   DenseMap<MCSymbol*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
138
139   /// CallSiteMap - Map of invoke call site index values to associated begin
140   /// EH_LABEL for the current function.
141   DenseMap<MCSymbol*, unsigned> CallSiteMap;
142
143   /// CurCallSite - The current call site index being processed, if any. 0 if
144   /// none.
145   unsigned CurCallSite;
146
147   /// TypeInfos - List of C++ TypeInfo used in the current function.
148   std::vector<const GlobalValue *> TypeInfos;
149
150   /// FilterIds - List of typeids encoding filters used in the current function.
151   std::vector<unsigned> FilterIds;
152
153   /// FilterEnds - List of the indices in FilterIds corresponding to filter
154   /// terminators.
155   std::vector<unsigned> FilterEnds;
156
157   /// Personalities - Vector of all personality functions ever seen. Used to
158   /// emit common EH frames.
159   std::vector<const Function *> Personalities;
160
161   /// UsedFunctions - The functions in the @llvm.used list in a more easily
162   /// searchable format.  This does not include the functions in
163   /// llvm.compiler.used.
164   SmallPtrSet<const Function *, 32> UsedFunctions;
165
166   /// AddrLabelSymbols - This map keeps track of which symbol is being used for
167   /// the specified basic block's address of label.
168   MMIAddrLabelMap *AddrLabelSymbols;
169
170   bool CallsEHReturn;
171   bool CallsUnwindInit;
172
173   /// DbgInfoAvailable - True if debugging information is available
174   /// in this module.
175   bool DbgInfoAvailable;
176
177   /// UsesVAFloatArgument - True if this module calls VarArg function with
178   /// floating-point arguments.  This is used to emit an undefined reference
179   /// to _fltused on Windows targets.
180   bool UsesVAFloatArgument;
181
182   /// UsesMorestackAddr - True if the module calls the __morestack function
183   /// indirectly, as is required under the large code model on x86. This is used
184   /// to emit a definition of a symbol, __morestack_addr, containing the
185   /// address. See comments in lib/Target/X86/X86FrameLowering.cpp for more
186   /// details.
187   bool UsesMorestackAddr;
188
189   EHPersonality PersonalityTypeCache;
190
191   DenseMap<const Function *, std::unique_ptr<WinEHFuncInfo>> FuncInfoMap;
192
193 public:
194   static char ID; // Pass identification, replacement for typeid
195
196   struct VariableDbgInfo {
197     const MDLocalVariable *Var;
198     const MDExpression *Expr;
199     unsigned Slot;
200     const MDLocation *Loc;
201
202     VariableDbgInfo(const MDLocalVariable *Var, const MDExpression *Expr,
203                     unsigned Slot, const MDLocation *Loc)
204         : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
205   };
206   typedef SmallVector<VariableDbgInfo, 4> VariableDbgInfoMapTy;
207   VariableDbgInfoMapTy VariableDbgInfos;
208
209   MachineModuleInfo();  // DUMMY CONSTRUCTOR, DO NOT CALL.
210   // Real constructor.
211   MachineModuleInfo(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
212                     const MCObjectFileInfo *MOFI);
213   ~MachineModuleInfo() override;
214
215   // Initialization and Finalization
216   bool doInitialization(Module &) override;
217   bool doFinalization(Module &) override;
218
219   /// EndFunction - Discard function meta information.
220   ///
221   void EndFunction();
222
223   const MCContext &getContext() const { return Context; }
224   MCContext &getContext() { return Context; }
225
226   void setModule(const Module *M) { TheModule = M; }
227   const Module *getModule() const { return TheModule; }
228
229   const Function *getWinEHParent(const Function *F) const;
230   WinEHFuncInfo &getWinEHFuncInfo(const Function *F);
231   bool hasWinEHFuncInfo(const Function *F) const {
232     return FuncInfoMap.count(getWinEHParent(F)) > 0;
233   }
234
235   /// getInfo - Keep track of various per-function pieces of information for
236   /// backends that would like to do so.
237   ///
238   template<typename Ty>
239   Ty &getObjFileInfo() {
240     if (ObjFileMMI == nullptr)
241       ObjFileMMI = new Ty(*this);
242     return *static_cast<Ty*>(ObjFileMMI);
243   }
244
245   template<typename Ty>
246   const Ty &getObjFileInfo() const {
247     return const_cast<MachineModuleInfo*>(this)->getObjFileInfo<Ty>();
248   }
249
250   /// AnalyzeModule - Scan the module for global debug information.
251   ///
252   void AnalyzeModule(const Module &M);
253
254   /// hasDebugInfo - Returns true if valid debug info is present.
255   ///
256   bool hasDebugInfo() const { return DbgInfoAvailable; }
257   void setDebugInfoAvailability(bool avail) { DbgInfoAvailable = avail; }
258
259   bool callsEHReturn() const { return CallsEHReturn; }
260   void setCallsEHReturn(bool b) { CallsEHReturn = b; }
261
262   bool callsUnwindInit() const { return CallsUnwindInit; }
263   void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
264
265   bool usesVAFloatArgument() const {
266     return UsesVAFloatArgument;
267   }
268
269   void setUsesVAFloatArgument(bool b) {
270     UsesVAFloatArgument = b;
271   }
272
273   bool usesMorestackAddr() const {
274     return UsesMorestackAddr;
275   }
276
277   void setUsesMorestackAddr(bool b) {
278     UsesMorestackAddr = b;
279   }
280
281   /// \brief Returns a reference to a list of cfi instructions in the current
282   /// function's prologue.  Used to construct frame maps for debug and exception
283   /// handling comsumers.
284   const std::vector<MCCFIInstruction> &getFrameInstructions() const {
285     return FrameInstructions;
286   }
287
288   unsigned LLVM_ATTRIBUTE_UNUSED_RESULT
289   addFrameInst(const MCCFIInstruction &Inst) {
290     FrameInstructions.push_back(Inst);
291     return FrameInstructions.size() - 1;
292   }
293
294   /// getAddrLabelSymbol - Return the symbol to be used for the specified basic
295   /// block when its address is taken.  This cannot be its normal LBB label
296   /// because the block may be accessed outside its containing function.
297   MCSymbol *getAddrLabelSymbol(const BasicBlock *BB);
298
299   /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
300   /// basic block when its address is taken.  If other blocks were RAUW'd to
301   /// this one, we may have to emit them as well, return the whole set.
302   std::vector<MCSymbol*> getAddrLabelSymbolToEmit(const BasicBlock *BB);
303
304   /// takeDeletedSymbolsForFunction - If the specified function has had any
305   /// references to address-taken blocks generated, but the block got deleted,
306   /// return the symbol now so we can emit it.  This prevents emitting a
307   /// reference to a symbol that has no definition.
308   void takeDeletedSymbolsForFunction(const Function *F,
309                                      std::vector<MCSymbol*> &Result);
310
311
312   //===- EH ---------------------------------------------------------------===//
313
314   /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
315   /// specified MachineBasicBlock.
316   LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
317
318   /// addInvoke - Provide the begin and end labels of an invoke style call and
319   /// associate it with a try landing pad block.
320   void addInvoke(MachineBasicBlock *LandingPad,
321                  MCSymbol *BeginLabel, MCSymbol *EndLabel);
322
323   /// addLandingPad - Add a new panding pad.  Returns the label ID for the
324   /// landing pad entry.
325   MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
326
327   /// addPersonality - Provide the personality function for the exception
328   /// information.
329   void addPersonality(MachineBasicBlock *LandingPad,
330                       const Function *Personality);
331
332   void addWinEHState(MachineBasicBlock *LandingPad, int State);
333
334   /// getPersonalityIndex - Get index of the current personality function inside
335   /// Personalitites array
336   unsigned getPersonalityIndex() const;
337
338   /// getPersonalities - Return array of personality functions ever seen.
339   const std::vector<const Function *>& getPersonalities() const {
340     return Personalities;
341   }
342
343   /// isUsedFunction - Return true if the functions in the llvm.used list.  This
344   /// does not return true for things in llvm.compiler.used unless they are also
345   /// in llvm.used.
346   bool isUsedFunction(const Function *F) const {
347     return UsedFunctions.count(F);
348   }
349
350   /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
351   ///
352   void addCatchTypeInfo(MachineBasicBlock *LandingPad,
353                         ArrayRef<const GlobalValue *> TyInfo);
354
355   /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
356   ///
357   void addFilterTypeInfo(MachineBasicBlock *LandingPad,
358                          ArrayRef<const GlobalValue *> TyInfo);
359
360   /// addCleanup - Add a cleanup action for a landing pad.
361   ///
362   void addCleanup(MachineBasicBlock *LandingPad);
363
364   /// Add a clause for a landing pad. Returns a new label for the clause. This
365   /// is used by EH schemes that have more than one landing pad. In this case,
366   /// each clause gets its own basic block.
367   MCSymbol *addClauseForLandingPad(MachineBasicBlock *LandingPad);
368
369   void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
370                           const BlockAddress *RecoverLabel);
371
372   void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
373                             const Function *Cleanup);
374
375   /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
376   /// function wide.
377   unsigned getTypeIDFor(const GlobalValue *TI);
378
379   /// getFilterIDFor - Return the id of the filter encoded by TyIds.  This is
380   /// function wide.
381   int getFilterIDFor(std::vector<unsigned> &TyIds);
382
383   /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
384   /// pads.
385   void TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap = nullptr);
386
387   /// getLandingPads - Return a reference to the landing pad info for the
388   /// current function.
389   const std::vector<LandingPadInfo> &getLandingPads() const {
390     return LandingPads;
391   }
392
393   /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call
394   /// site indexes.
395   void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
396
397   /// getCallSiteLandingPad - Get the call site indexes for a landing pad EH
398   /// symbol.
399   SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
400     assert(hasCallSiteLandingPad(Sym) &&
401            "missing call site number for landing pad!");
402     return LPadToCallSiteMap[Sym];
403   }
404
405   /// hasCallSiteLandingPad - Return true if the landing pad Eh symbol has an
406   /// associated call site.
407   bool hasCallSiteLandingPad(MCSymbol *Sym) {
408     return !LPadToCallSiteMap[Sym].empty();
409   }
410
411   /// setCallSiteBeginLabel - Map the begin label for a call site.
412   void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
413     CallSiteMap[BeginLabel] = Site;
414   }
415
416   /// getCallSiteBeginLabel - Get the call site number for a begin label.
417   unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) {
418     assert(hasCallSiteBeginLabel(BeginLabel) &&
419            "Missing call site number for EH_LABEL!");
420     return CallSiteMap[BeginLabel];
421   }
422
423   /// hasCallSiteBeginLabel - Return true if the begin label has a call site
424   /// number associated with it.
425   bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) {
426     return CallSiteMap[BeginLabel] != 0;
427   }
428
429   /// setCurrentCallSite - Set the call site currently being processed.
430   void setCurrentCallSite(unsigned Site) { CurCallSite = Site; }
431
432   /// getCurrentCallSite - Get the call site currently being processed, if any.
433   /// return zero if none.
434   unsigned getCurrentCallSite() { return CurCallSite; }
435
436   /// getTypeInfos - Return a reference to the C++ typeinfo for the current
437   /// function.
438   const std::vector<const GlobalValue *> &getTypeInfos() const {
439     return TypeInfos;
440   }
441
442   /// getFilterIds - Return a reference to the typeids encoding filters used in
443   /// the current function.
444   const std::vector<unsigned> &getFilterIds() const {
445     return FilterIds;
446   }
447
448   /// getPersonality - Return a personality function if available.  The presence
449   /// of one is required to emit exception handling info.
450   const Function *getPersonality() const;
451
452   /// Classify the personality function amongst known EH styles.
453   EHPersonality getPersonalityType();
454
455   /// setVariableDbgInfo - Collect information used to emit debugging
456   /// information of a variable.
457   void setVariableDbgInfo(const MDLocalVariable *Var, const MDExpression *Expr,
458                           unsigned Slot, const MDLocation *Loc) {
459     VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
460   }
461
462   VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
463
464 }; // End class MachineModuleInfo
465
466 } // End llvm namespace
467
468 #endif