[ThinLTO] Add code comment. NFC
[llvm-core.git] / docs / ORCv2.rst
blob0a8788a6b3a52b9b3621bddd8bd45b78ceb9038f
1 ===============================
2 ORC Design and Implementation
3 ===============================
5 .. contents::
6    :local:
8 Introduction
9 ============
11 This document aims to provide a high-level overview of the design and
12 implementation of the ORC JIT APIs. Except where otherwise stated, all
13 discussion applies to the design of the APIs as of LLVM version 9 (ORCv2).
15 Use-cases
16 =========
18 ORC provides a modular API for building JIT compilers. There are a range
19 of use cases for such an API. For example:
21 1. The LLVM tutorials use a simple ORC-based JIT class to execute expressions
22 compiled from a toy language: Kaleidoscope.
24 2. The LLVM debugger, LLDB, uses a cross-compiling JIT for expression
25 evaluation. In this use case, cross compilation allows expressions compiled
26 in the debugger process to be executed on the debug target process, which may
27 be on a different device/architecture.
29 3. In high-performance JITs (e.g. JVMs, Julia) that want to make use of LLVM's
30 optimizations within an existing JIT infrastructure.
32 4. In interpreters and REPLs, e.g. Cling (C++) and the Swift interpreter.
34 By adopting a modular, library-based design we aim to make ORC useful in as many
35 of these contexts as possible.
37 Features
38 ========
40 ORC provides the following features:
42 - *JIT-linking* links relocatable object files (COFF, ELF, MachO) [1]_ into a
43   target process an runtime. The target process may be the same process that
44   contains the JIT session object and jit-linker, or may be another process
45   (even one running on a different machine or architecture) that communicates
46   with the JIT via RPC.
48 - *LLVM IR compilation*, which is provided by off the shelf components
49   (IRCompileLayer, SimpleCompiler, ConcurrentIRCompiler) that make it easy to
50   add LLVM IR to a JIT'd process.
52 - *Eager and lazy compilation*. By default, ORC will compile symbols as soon as
53   they are looked up in the JIT session object (``ExecutionSession``). Compiling
54   eagerly by default makes it easy to use ORC as a simple in-memory compiler for
55   an existing JIT. ORC also provides a simple mechanism, lazy-reexports, for
56   deferring compilation until first call.
58 - *Support for custom compilers and program representations*. Clients can supply
59   custom compilers for each symbol that they define in their JIT session. ORC
60   will run the user-supplied compiler when the a definition of a symbol is
61   needed. ORC is actually fully language agnostic: LLVM IR is not treated
62   specially, and is supported via the same wrapper mechanism (the
63   ``MaterializationUnit`` class) that is used for custom compilers.
65 - *Concurrent JIT'd code* and *concurrent compilation*. JIT'd code may spawn
66   multiple threads, and may re-enter the JIT (e.g. for lazy compilation)
67   concurrently from multiple threads. The ORC APIs also support running multiple
68   compilers concurrently, and provides off-the-shelf infrastructure to track
69   dependencies on running compiles (e.g. to ensure that we never call into code
70   until it is safe to do so, even if that involves waiting on multiple
71   compiles).
73 - *Orthogonality* and *composability*: Each of the features above can be used (or
74   not) independently. It is possible to put ORC components together to make a
75   non-lazy, in-process, single threaded JIT or a lazy, out-of-process,
76   concurrent JIT, or anything in between.
78 LLJIT and LLLazyJIT
79 ===================
81 ORC provides two basic JIT classes off-the-shelf. These are useful both as
82 examples of how to assemble ORC components to make a JIT, and as replacements
83 for earlier LLVM JIT APIs (e.g. MCJIT).
85 The LLJIT class uses an IRCompileLayer and RTDyldObjectLinkingLayer to support
86 compilation of LLVM IR and linking of relocatable object files. All operations
87 are performed eagerly on symbol lookup (i.e. a symbol's definition is compiled
88 as soon as you attempt to look up its address). LLJIT is a suitable replacement
89 for MCJIT in most cases (note: some more advanced features, e.g.
90 JITEventListeners are not supported yet).
92 The LLLazyJIT extends LLJIT and adds a CompileOnDemandLayer to enable lazy
93 compilation of LLVM IR. When an LLVM IR module is added via the addLazyIRModule
94 method, function bodies in that module will not be compiled until they are first
95 called. LLLazyJIT aims to provide a replacement of LLVM's original (pre-MCJIT)
96 JIT API.
98 LLJIT and LLLazyJIT instances can be created using their respective builder
99 classes: LLJITBuilder and LLazyJITBuilder. For example, assuming you have a
100 module ``M`` loaded on an ThreadSafeContext ``Ctx``:
102 .. code-block:: c++
104   // Try to detect the host arch and construct an LLJIT instance.
105   auto JIT = LLJITBuilder().create();
107   // If we could not construct an instance, return an error.
108   if (!JIT)
109     return JIT.takeError();
111   // Add the module.
112   if (auto Err = JIT->addIRModule(TheadSafeModule(std::move(M), Ctx)))
113     return Err;
115   // Look up the JIT'd code entry point.
116   auto EntrySym = JIT->lookup("entry");
117   if (!EntrySym)
118     return EntrySym.takeError();
120   // Cast the entry point address to a function pointer.
121   auto *Entry = (void(*)())EntrySym.getAddress();
123   // Call into JIT'd code.
124   Entry();
126 The builder clasess provide a number of configuration options that can be
127 specified before the JIT instance is constructed. For example:
129 .. code-block:: c++
131   // Build an LLLazyJIT instance that uses four worker threads for compilation,
132   // and jumps to a specific error handler (rather than null) on lazy compile
133   // failures.
135   void handleLazyCompileFailure() {
136     // JIT'd code will jump here if lazy compilation fails, giving us an
137     // opportunity to exit or throw an exception into JIT'd code.
138     throw JITFailed();
139   }
141   auto JIT = LLLazyJITBuilder()
142                .setNumCompileThreads(4)
143                .setLazyCompileFailureAddr(
144                    toJITTargetAddress(&handleLazyCompileFailure))
145                .create();
147   // ...
149 For users wanting to get started with LLJIT a minimal example program can be
150 found at ``llvm/examples/HowToUseLLJIT``.
152 Design Overview
153 ===============
155 ORC's JIT'd program model aims to emulate the linking and symbol resolution
156 rules used by the static and dynamic linkers. This allows ORC to JIT
157 arbitrary LLVM IR, including IR produced by an ordinary static compiler (e.g.
158 clang) that uses constructs like symbol linkage and visibility, and weak [3]_
159 and common symbol definitions.
161 To see how this works, imagine a program ``foo`` which links against a pair
162 of dynamic libraries: ``libA`` and ``libB``. On the command line, building this
163 program might look like:
165 .. code-block:: bash
167   $ clang++ -shared -o libA.dylib a1.cpp a2.cpp
168   $ clang++ -shared -o libB.dylib b1.cpp b2.cpp
169   $ clang++ -o myapp myapp.cpp -L. -lA -lB
170   $ ./myapp
172 In ORC, this would translate into API calls on a "CXXCompilingLayer" (with error
173 checking omitted for brevity) as:
175 .. code-block:: c++
177   ExecutionSession ES;
178   RTDyldObjectLinkingLayer ObjLinkingLayer(
179       ES, []() { return std::make_unique<SectionMemoryManager>(); });
180   CXXCompileLayer CXXLayer(ES, ObjLinkingLayer);
182   // Create JITDylib "A" and add code to it using the CXX layer.
183   auto &LibA = ES.createJITDylib("A");
184   CXXLayer.add(LibA, MemoryBuffer::getFile("a1.cpp"));
185   CXXLayer.add(LibA, MemoryBuffer::getFile("a2.cpp"));
187   // Create JITDylib "B" and add code to it using the CXX layer.
188   auto &LibB = ES.createJITDylib("B");
189   CXXLayer.add(LibB, MemoryBuffer::getFile("b1.cpp"));
190   CXXLayer.add(LibB, MemoryBuffer::getFile("b2.cpp"));
192   // Specify the search order for the main JITDylib. This is equivalent to a
193   // "links against" relationship in a command-line link.
194   ES.getMainJITDylib().setSearchOrder({{&LibA, false}, {&LibB, false}});
195   CXXLayer.add(ES.getMainJITDylib(), MemoryBuffer::getFile("main.cpp"));
197   // Look up the JIT'd main, cast it to a function pointer, then call it.
198   auto MainSym = ExitOnErr(ES.lookup({&ES.getMainJITDylib()}, "main"));
199   auto *Main = (int(*)(int, char*[]))MainSym.getAddress();
201 v  int Result = Main(...);
203 This example tells us nothing about *how* or *when* compilation will happen.
204 That will depend on the implementation of the hypothetical CXXCompilingLayer.
205 The same linker-based symbol resolution rules will apply regardless of that
206 implementation, however. For example, if a1.cpp and a2.cpp both define a
207 function "foo" then ORCv2 will generate a duplicate definition error. On the
208 other hand, if a1.cpp and b1.cpp both define "foo" there is no error (different
209 dynamic libraries may define the same symbol). If main.cpp refers to "foo", it
210 should bind to the definition in LibA rather than the one in LibB, since
211 main.cpp is part of the "main" dylib, and the main dylib links against LibA
212 before LibB.
214 Many JIT clients will have no need for this strict adherence to the usual
215 ahead-of-time linking rules, and should be able to get by just fine by putting
216 all of their code in a single JITDylib. However, clients who want to JIT code
217 for languages/projects that traditionally rely on ahead-of-time linking (e.g.
218 C++) will find that this feature makes life much easier.
220 Symbol lookup in ORC serves two other important functions, beyond providing
221 addresses for symbols: (1) It triggers compilation of the symbol(s) searched for
222 (if they have not been compiled already), and (2) it provides the
223 synchronization mechanism for concurrent compilation. The pseudo-code for the
224 lookup process is:
226 .. code-block:: none
228   construct a query object from a query set and query handler
229   lock the session
230   lodge query against requested symbols, collect required materializers (if any)
231   unlock the session
232   dispatch materializers (if any)
234 In this context a materializer is something that provides a working definition
235 of a symbol upon request. Usually materializers are just wrappers for compilers,
236 but they may also wrap a jit-linker directly (if the program representation
237 backing the definitions is an object file), or may even be a class that writes
238 bits directly into memory (for example, if the definitions are
239 stubs). Materialization is the blanket term for any actions (compiling, linking,
240 splatting bits, registering with runtimes, etc.) that are required to generate a
241 symbol definition that is safe to call or access.
243 As each materializer completes its work it notifies the JITDylib, which in turn
244 notifies any query objects that are waiting on the newly materialized
245 definitions. Each query object maintains a count of the number of symbols that
246 it is still waiting on, and once this count reaches zero the query object calls
247 the query handler with a *SymbolMap* (a map of symbol names to addresses)
248 describing the result. If any symbol fails to materialize the query immediately
249 calls the query handler with an error.
251 The collected materialization units are sent to the ExecutionSession to be
252 dispatched, and the dispatch behavior can be set by the client. By default each
253 materializer is run on the calling thread. Clients are free to create new
254 threads to run materializers, or to send the work to a work queue for a thread
255 pool (this is what LLJIT/LLLazyJIT do).
257 Top Level APIs
258 ==============
260 Many of ORC's top-level APIs are visible in the example above:
262 - *ExecutionSession* represents the JIT'd program and provides context for the
263   JIT: It contains the JITDylibs, error reporting mechanisms, and dispatches the
264   materializers.
266 - *JITDylibs* provide the symbol tables.
268 - *Layers* (ObjLinkingLayer and CXXLayer) are wrappers around compilers and
269   allow clients to add uncompiled program representations supported by those
270   compilers to JITDylibs.
272 Several other important APIs are used explicitly. JIT clients need not be aware
273 of them, but Layer authors will use them:
275 - *MaterializationUnit* - When XXXLayer::add is invoked it wraps the given
276   program representation (in this example, C++ source) in a MaterializationUnit,
277   which is then stored in the JITDylib. MaterializationUnits are responsible for
278   describing the definitions they provide, and for unwrapping the program
279   representation and passing it back to the layer when compilation is required
280   (this ownership shuffle makes writing thread-safe layers easier, since the
281   ownership of the program representation will be passed back on the stack,
282   rather than having to be fished out of a Layer member, which would require
283   synchronization).
285 - *MaterializationResponsibility* - When a MaterializationUnit hands a program
286   representation back to the layer it comes with an associated
287   MaterializationResponsibility object. This object tracks the definitions
288   that must be materialized and provides a way to notify the JITDylib once they
289   are either successfully materialized or a failure occurs.
291 Handy utilities
292 ===============
294 TBD: absolute symbols, aliases, off-the-shelf layers.
296 Laziness
297 ========
299 Laziness in ORC is provided by a utility called "lazy-reexports". The aim of
300 this utility is to re-use the synchronization provided by the symbol lookup
301 mechanism to make it safe to lazily compile functions, even if calls to the
302 stub occur simultaneously on multiple threads of JIT'd code. It does this by
303 reducing lazy compilation to symbol lookup: The lazy stub performs a lookup of
304 its underlying definition on first call, updating the function body pointer
305 once the definition is available. If additional calls arrive on other threads
306 while compilation is ongoing they will be safely blocked by the normal lookup
307 synchronization guarantee (no result until the result is safe) and can also
308 proceed as soon as compilation completes.
310 TBD: Usage example.
312 Supporting Custom Compilers
313 ===========================
315 TBD.
317 Transitioning from ORCv1 to ORCv2
318 =================================
320 Since LLVM 7.0, new ORC development work has focused on adding support for
321 concurrent JIT compilation. The new APIs (including new layer interfaces and
322 implementations, and new utilities) that support concurrency are collectively
323 referred to as ORCv2, and the original, non-concurrent layers and utilities
324 are now referred to as ORCv1.
326 The majority of the ORCv1 layers and utilities were renamed with a 'Legacy'
327 prefix in LLVM 8.0, and have deprecation warnings attached in LLVM 9.0. In LLVM
328 10.0 ORCv1 will be removed entirely.
330 Transitioning from ORCv1 to ORCv2 should be easy for most clients. Most of the
331 ORCv1 layers and utilities have ORCv2 counterparts [2]_ that can be directly
332 substituted. However there are some design differences between ORCv1 and ORCv2
333 to be aware of:
335   1. ORCv2 fully adopts the JIT-as-linker model that began with MCJIT. Modules
336      (and other program representations, e.g. Object Files)  are no longer added
337      directly to JIT classes or layers. Instead, they are added to ``JITDylib``
338      instances *by* layers. The ``JITDylib`` determines *where* the definitions
339      reside, the layers determine *how* the definitions will be compiled.
340      Linkage relationships between ``JITDylibs`` determine how inter-module
341      references are resolved, and symbol resolvers are no longer used. See the
342      section `Design Overview`_ for more details.
344      Unless multiple JITDylibs are needed to model linkage relationsips, ORCv1
345      clients should place all code in the main JITDylib (returned by
346      ``ExecutionSession::getMainJITDylib()``). MCJIT clients should use LLJIT
347      (see `LLJIT and LLLazyJIT`_).
349   2. All JIT stacks now need an ``ExecutionSession`` instance. ExecutionSession
350      manages the string pool, error reporting, synchronization, and symbol
351      lookup.
353   3. ORCv2 uses uniqued strings (``SymbolStringPtr`` instances) rather than
354      string values in order to reduce memory overhead and improve lookup
355      performance. See the subsection `How to manage symbol strings`_.
357   4. IR layers require ThreadSafeModule instances, rather than
358      std::unique_ptr<Module>s. ThreadSafeModule is a wrapper that ensures that
359      Modules that use the same LLVMContext are not accessed concurrently.
360      See `How to use ThreadSafeModule and ThreadSafeContext`_.
362   5. Symbol lookup is no longer handled by layers. Instead, there is a
363      ``lookup`` method on JITDylib that takes a list of JITDylibs to scan.
365      .. code-block:: c++
367        ExecutionSession ES;
368        JITDylib &JD1 = ...;
369        JITDylib &JD2 = ...;
371        auto Sym = ES.lookup({&JD1, &JD2}, ES.intern("_main"));
373   6. Module removal is not yet supported. There is no equivalent of the
374      layer concept removeModule/removeObject methods. Work on resource tracking
375      and removal in ORCv2 is ongoing.
377 For code examples and suggestions of how to use the ORCv2 APIs, please see
378 the section `How-tos`_.
380 How-tos
381 =======
383 How to manage symbol strings
384 ############################
386 Symbol strings in ORC are uniqued to improve lookup performance, reduce memory
387 overhead, and allow symbol names to function as efficient keys. To get the
388 unique ``SymbolStringPtr`` for a string value, call the
389 ``ExecutionSession::intern`` method:
391   .. code-block:: c++
393     ExecutionSession ES;
394     /// ...
395     auto MainSymbolName = ES.intern("main");
397 If you wish to perform lookup using the C/IR name of a symbol you will also
398 need to apply the platform linker-mangling before interning the string. On
399 Linux this mangling is a no-op, but on other platforms it usually involves
400 adding a prefix to the string (e.g. '_' on Darwin). The mangling scheme is
401 based on the DataLayout for the target. Given a DataLayout and an
402 ExecutionSession, you can create a MangleAndInterner function object that
403 will perform both jobs for you:
405   .. code-block:: c++
407     ExecutionSession ES;
408     const DataLayout &DL = ...;
409     MangleAndInterner Mangle(ES, DL);
411     // ...
413     // Portable IR-symbol-name lookup:
414     auto Sym = ES.lookup({&ES.getMainJITDylib()}, Mangle("main"));
416 How to create JITDylibs and set up linkage relationships
417 ########################################################
419 In ORC, all symbol definitions reside in JITDylibs. JITDylibs are created by
420 calling the ``ExecutionSession::createJITDylib`` method with a unique name:
422   .. code-block:: c++
424     ExecutionSession ES;
425     auto &JD = ES.createJITDylib("libFoo.dylib");
427 The JITDylib is owned by the ``ExecutionEngine`` instance and will be freed
428 when it is destroyed.
430 A JITDylib representing the JIT main program is created by ExecutionEngine by
431 default. A reference to it can be obtained by calling
432 ``ExecutionSession::getMainJITDylib()``:
434   .. code-block:: c++
436     ExecutionSession ES;
437     auto &MainJD = ES.getMainJITDylib();
439 How to use ThreadSafeModule and ThreadSafeContext
440 #################################################
442 ThreadSafeModule and ThreadSafeContext are wrappers around Modules and
443 LLVMContexts respectively. A ThreadSafeModule is a pair of a
444 std::unique_ptr<Module> and a (possibly shared) ThreadSafeContext value. A
445 ThreadSafeContext is a pair of a std::unique_ptr<LLVMContext> and a lock.
446 This design serves two purposes: providing a locking scheme and lifetime
447 management for LLVMContexts. The ThreadSafeContext may be locked to prevent
448 accidental concurrent access by two Modules that use the same LLVMContext.
449 The underlying LLVMContext is freed once all ThreadSafeContext values pointing
450 to it are destroyed, allowing the context memory to be reclaimed as soon as
451 the Modules referring to it are destroyed.
453 ThreadSafeContexts can be explicitly constructed from a
454 std::unique_ptr<LLVMContext>:
456   .. code-block:: c++
458     ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
460 ThreadSafeModules can be constructed from a pair of a std::unique_ptr<Module>
461 and a ThreadSafeContext value. ThreadSafeContext values may be shared between
462 multiple ThreadSafeModules:
464   .. code-block:: c++
466     ThreadSafeModule TSM1(
467       std::make_unique<Module>("M1", *TSCtx.getContext()), TSCtx);
469     ThreadSafeModule TSM2(
470       std::make_unique<Module>("M2", *TSCtx.getContext()), TSCtx);
472 Before using a ThreadSafeContext, clients should ensure that either the context
473 is only accessible on the current thread, or that the context is locked. In the
474 example above (where the context is never locked) we rely on the fact that both
475 ``TSM1`` and ``TSM2``, and TSCtx are all created on one thread. If a context is
476 going to be shared between threads then it must be locked before any accessing
477 or creating any Modules attached to it. E.g.
479   .. code-block:: c++
481     ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
483     ThreadPool TP(NumThreads);
484     JITStack J;
486     for (auto &ModulePath : ModulePaths) {
487       TP.async(
488         [&]() {
489           auto Lock = TSCtx.getLock();
490           auto M = loadModuleOnContext(ModulePath, TSCtx.getContext());
491           J.addModule(ThreadSafeModule(std::move(M), TSCtx));
492         });
493     }
495     TP.wait();
497 To make exclusive access to Modules easier to manage the ThreadSafeModule class
498 provides a convenience function, ``withModuleDo``, that implicitly (1) locks the
499 associated context, (2) runs a given function object, (3) unlocks the context,
500 and (3) returns the result generated by the function object. E.g.
502   .. code-block:: c++
504     ThreadSafeModule TSM = getModule(...);
506     // Dump the module:
507     size_t NumFunctionsInModule =
508       TSM.withModuleDo(
509         [](Module &M) { // <- Context locked before entering lambda.
510           return M.size();
511         } // <- Context unlocked after leaving.
512       );
514 Clients wishing to maximize possibilities for concurrent compilation will want
515 to create every new ThreadSafeModule on a new ThreadSafeContext. For this
516 reason a convenience constructor for ThreadSafeModule is provided that implicitly
517 constructs a new ThreadSafeContext value from a std::unique_ptr<LLVMContext>:
519   .. code-block:: c++
521     // Maximize concurrency opportunities by loading every module on a
522     // separate context.
523     for (const auto &IRPath : IRPaths) {
524       auto Ctx = std::make_unique<LLVMContext>();
525       auto M = std::make_unique<LLVMContext>("M", *Ctx);
526       CompileLayer.add(ES.getMainJITDylib(),
527                        ThreadSafeModule(std::move(M), std::move(Ctx)));
528     }
530 Clients who plan to run single-threaded may choose to save memory by loading
531 all modules on the same context:
533   .. code-block:: c++
535     // Save memory by using one context for all Modules:
536     ThreadSafeContext TSCtx(std::make_unique<LLVMContext>());
537     for (const auto &IRPath : IRPaths) {
538       ThreadSafeModule TSM(parsePath(IRPath, *TSCtx.getContext()), TSCtx);
539       CompileLayer.add(ES.getMainJITDylib(), ThreadSafeModule(std::move(TSM));
540     }
542 How to Add Process and Library Symbols to the JITDylibs
543 =======================================================
545 JIT'd code typically needs access to symbols in the host program or in
546 supporting libraries. References to process symbols can be "baked in" to code
547 as it is compiled by turning external references into pre-resolved integer
548 constants, however this ties the JIT'd code to the current process's virtual
549 memory layout (meaning that it can not be cached between runs) and makes
550 debugging lower level program representations difficult (as all external
551 references are opaque integer values). A bettor solution is to maintain symbolic
552 external references and let the jit-linker bind them for you at runtime. To
553 allow the JIT linker to find these external definitions their addresses must
554 be added to a JITDylib that the JIT'd definitions link against.
556 Adding definitions for external symbols could be done using the absoluteSymbols
557 function:
559   .. code-block:: c++
561     const DataLayout &DL = getDataLayout();
562     MangleAndInterner Mangle(ES, DL);
564     auto &JD = ES.getMainJITDylib();
566     JD.define(
567       absoluteSymbols({
568         { Mangle("puts"), pointerToJITTargetAddress(&puts)},
569         { Mangle("gets"), pointerToJITTargetAddress(&getS)}
570       }));
572 Manually adding absolute symbols for a large or changing interface is cumbersome
573 however, so ORC provides an alternative to generate new definitions on demand:
574 *definition generators*. If a definition generator is attached to a JITDylib,
575 then any unsuccessful lookup on that JITDylib will fall back to calling the
576 definition generator, and the definition generator may choose to generate a new
577 definition for the missing symbols. Of particular use here is the
578 ``DynamicLibrarySearchGenerator`` utility. This can be used to reflect the whole
579 exported symbol set of the process or a specific dynamic library, or a subset
580 of either of these determined by a predicate.
582 For example, to load the whole interface of a runtime library:
584   .. code-block:: c++
586     const DataLayout &DL = getDataLayout();
587     auto &JD = ES.getMainJITDylib();
589     JD.setGenerator(DynamicLibrarySearchGenerator::Load("/path/to/lib"
590                                                         DL.getGlobalPrefix()));
592     // IR added to JD can now link against all symbols exported by the library
593     // at '/path/to/lib'.
594     CompileLayer.add(JD, loadModule(...));
596 Or, to expose a whitelisted set of symbols from the main process:
598   .. code-block:: c++
600     const DataLayout &DL = getDataLayout();
601     MangleAndInterner Mangle(ES, DL);
603     auto &JD = ES.getMainJITDylib();
605     DenseSet<SymbolStringPtr> Whitelist({
606         Mangle("puts"),
607         Mangle("gets")
608       });
610     // Use GetForCurrentProcess with a predicate function that checks the
611     // whitelist.
612     JD.setGenerator(
613       DynamicLibrarySearchGenerator::GetForCurrentProcess(
614         DL.getGlobalPrefix(),
615         [&](const SymbolStringPtr &S) { return Whitelist.count(S); }));
617     // IR added to JD can now link against any symbols exported by the process
618     // and contained in the whitelist.
619     CompileLayer.add(JD, loadModule(...));
621 Future Features
622 ===============
624 TBD: Speculative compilation. Object Caches.
626 .. [1] Formats/architectures vary in terms of supported features. MachO and
627        ELF tend to have better support than COFF. Patches very welcome!
629 .. [2] The ``LazyEmittingLayer``, ``RemoteObjectClientLayer`` and
630        ``RemoteObjectServerLayer`` do not have counterparts in the new
631        system. In the case of ``LazyEmittingLayer`` it was simply no longer
632        needed: in ORCv2, deferring compilation until symbols are looked up is
633        the default. The removal of ``RemoteObjectClientLayer`` and
634        ``RemoteObjectServerLayer`` means that JIT stacks can no longer be split
635        across processes, however this functionality appears not to have been
636        used.
638 .. [3] Weak definitions are currently handled correctly within dylibs, but if
639        multiple dylibs provide a weak definition of a symbol then each will end
640        up with its own definition (similar to how weak definitions are handled
641        in Windows DLLs). This will be fixed in the future.