1 //===-- llvm/CodeGen/GCStrategy.h - Garbage collection ----------*- 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 // GCStrategy coordinates code generation algorithms and implements some itself
11 // in order to generate code compatible with a target code generator as
12 // specified in a function's 'gc' attribute. Algorithms are enabled by setting
13 // flags in a subclass's constructor, and some virtual methods can be
14 // overridden.
15 //
16 // GCStrategy is relevant for implementations using either gc.root or
17 // gc.statepoint based lowering strategies, but is currently focused mostly on
18 // options for gc.root.  This will change over time.
19 //
20 // When requested by a subclass of GCStrategy, the gc.root implementation will
21 // populate GCModuleInfo and GCFunctionInfo with that about each Function in
22 // the Module that opts in to garbage collection.  Specifically:
23 //
24 // - Safe points
25 //   Garbage collection is generally only possible at certain points in code.
26 //   GCStrategy can request that the collector insert such points:
27 //
28 //     - At and after any call to a subroutine
29 //     - Before returning from the current function
30 //     - Before backwards branches (loops)
31 //
32 // - Roots
33 //   When a reference to a GC-allocated object exists on the stack, it must be
34 //   stored in an alloca registered with llvm.gcoot.
35 //
36 // This information can used to emit the metadata tables which are required by
37 // the target garbage collector runtime.
38 //
39 // When used with gc.statepoint, information about safepoint and roots can be
40 // found in the binary StackMap section after code generation.  Safepoint
41 // placement is currently the responsibility of the frontend, though late
42 // insertion support is planned.  gc.statepoint does not currently support
43 // custom stack map formats; such can be generated by parsing the standard
44 // stack map section if desired.
45 //
46 // The read and write barrier support can be used with either implementation.
47 //
48 //===----------------------------------------------------------------------===//
49 
50 #ifndef LLVM_CODEGEN_GCSTRATEGY_H
51 #define LLVM_CODEGEN_GCSTRATEGY_H
52 
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/CodeGen/GCMetadata.h"
55 #include "llvm/CodeGen/MachineFunction.h"
56 #include "llvm/Support/Registry.h"
57 #include <string>
58 
59 namespace llvm {
60   /// GCStrategy describes a garbage collector algorithm's code generation
61   /// requirements, and provides overridable hooks for those needs which cannot
62   /// be abstractly described.  GCStrategy objects currently must be looked up
63   /// through the GCModuleInfo analysis pass.  They are owned by the analysis
64   /// pass and recreated every time that pass is invalidated.
65   class GCStrategy {
66   private:
67     std::string Name;
68     friend class GCModuleInfo;
69 
70   protected:
71     bool UseStatepoints;       /// Uses gc.statepoints as opposed to gc.roots,
72                                /// if set, none of the other options can be
73                                /// anything but their default values.
74 
75     unsigned NeededSafePoints; ///< Bitmask of required safe points.
76     bool CustomReadBarriers;   ///< Default is to insert loads.
77     bool CustomWriteBarriers;  ///< Default is to insert stores.
78     bool CustomRoots;          ///< Default is to pass through to backend.
79     bool CustomSafePoints;     ///< Default is to use NeededSafePoints
80                                ///< to find safe points.
81     bool InitRoots;            ///< If set, roots are nulled during lowering.
82     bool UsesMetadata;         ///< If set, backend must emit metadata tables.
83 
84   public:
85     GCStrategy();
~GCStrategy()86     virtual ~GCStrategy() {}
87 
88     /// Return the name of the GC strategy.  This is the value of the collector
89     /// name string specified on functions which use this strategy.
getName()90     const std::string &getName() const { return Name; }
91 
92     /// By default, write barriers are replaced with simple store
93     /// instructions. If true, then performCustomLowering must instead lower
94     /// them.
customWriteBarrier()95     bool customWriteBarrier() const { return CustomWriteBarriers; }
96 
97     /// By default, read barriers are replaced with simple load
98     /// instructions. If true, then performCustomLowering must instead lower
99     /// them.
customReadBarrier()100     bool customReadBarrier() const { return CustomReadBarriers; }
101 
102     /// Returns true if this strategy is expecting the use of gc.statepoints,
103     /// and false otherwise.
useStatepoints()104     bool useStatepoints() const { return UseStatepoints; }
105 
106     /** @name Statepoint Specific Properties */
107     ///@{
108 
109     /// If the value specified can be reliably distinguished, returns true for
110     /// pointers to GC managed locations and false for pointers to non-GC
111     /// managed locations.  Note a GCStrategy can always return 'None' (i.e. an
112     /// empty optional indicating it can't reliably distinguish.
isGCManagedPointer(const Value * V)113     virtual Optional<bool> isGCManagedPointer(const Value *V) const {
114       return None;
115     }
116     ///@}
117 
118     /** @name GCRoot Specific Properties
119      * These properties and overrides only apply to collector strategies using
120      * GCRoot.
121      */
122     ///@{
123 
124     /// True if safe points of any kind are required. By default, none are
125     /// recorded.
needsSafePoints()126     bool needsSafePoints() const {
127       return CustomSafePoints || NeededSafePoints != 0;
128     }
129 
130     /// True if the given kind of safe point is required. By default, none are
131     /// recorded.
needsSafePoint(GC::PointKind Kind)132     bool needsSafePoint(GC::PointKind Kind) const {
133       return (NeededSafePoints & 1 << Kind) != 0;
134     }
135 
136     /// By default, roots are left for the code generator so it can generate a
137     /// stack map. If true, then performCustomLowering must delete them.
customRoots()138     bool customRoots() const { return CustomRoots; }
139 
140     /// By default, the GC analysis will find safe points according to
141     /// NeededSafePoints. If true, then findCustomSafePoints must create them.
customSafePoints()142     bool customSafePoints() const { return CustomSafePoints; }
143 
144     /// If set, gcroot intrinsics should initialize their allocas to null
145     /// before the first use. This is necessary for most GCs and is enabled by
146     /// default.
initializeRoots()147     bool initializeRoots() const { return InitRoots; }
148 
149     /// If set, appropriate metadata tables must be emitted by the back-end
150     /// (assembler, JIT, or otherwise). For statepoint, this method is
151     /// currently unsupported.  The stackmap information can be found in the
152     /// StackMap section as described in the documentation.
usesMetadata()153     bool usesMetadata() const { return UsesMetadata; }
154 
155     ///@}
156 
157     /// initializeCustomLowering/performCustomLowering - If any of the actions
158     /// are set to custom, performCustomLowering must be overriden to transform
159     /// the corresponding actions to LLVM IR. initializeCustomLowering is
160     /// optional to override. These are the only GCStrategy methods through
161     /// which the LLVM IR can be modified.  These methods apply mostly to
162     /// gc.root based implementations, but can be overriden to provide custom
163     /// barrier lowerings with gc.statepoint as well.
164     ///@{
initializeCustomLowering(Module & F)165     virtual bool initializeCustomLowering(Module &F) {
166       // No changes made
167       return false;
168     }
performCustomLowering(Function & F)169     virtual bool performCustomLowering(Function &F) {
170       llvm_unreachable("GCStrategy subclass specified a configuration which"
171                        "requires a custom lowering without providing one");
172     }
173     ///@}
174     /// Called if customSafepoints returns true, used only by gc.root
175     /// implementations.
findCustomSafePoints(GCFunctionInfo & FI,MachineFunction & MF)176     virtual bool findCustomSafePoints(GCFunctionInfo& FI, MachineFunction& MF) {
177       llvm_unreachable("GCStrategy subclass specified a configuration which"
178                        "requests custom safepoint identification without"
179                        "providing an implementation for such");
180     }
181   };
182 
183   /// Subclasses of GCStrategy are made available for use during compilation by
184   /// adding them to the global GCRegistry.  This can done either within the
185   /// LLVM source tree or via a loadable plugin.  An example registeration
186   /// would be:
187   /// static GCRegistry::Add<CustomGC> X("custom-name",
188   ///        "my custom supper fancy gc strategy");
189   ///
190   /// Note that to use a custom GCMetadataPrinter w/gc.roots, you must also
191   /// register your GCMetadataPrinter subclass with the
192   /// GCMetadataPrinterRegistery as well.
193   typedef Registry<GCStrategy> GCRegistry;
194 }
195 
196 #endif
197