1
0
mirror of https://github.com/RPCS3/llvm-mirror.git synced 2024-10-19 02:52:53 +02:00
Commit Graph

2830 Commits

Author SHA1 Message Date
Lang Hames
02bae0a8ff [ORC][JITLink] Switch to unique ownership for EHFrameRegistrars.
This will make stateful registrars (e.g. a future TargetProcessControl based
registrar) easier to deal with.
2020-08-26 16:59:45 -07:00
Kai Nacke
79d0f5426e [SystemZ/ZOS]__(de)register_frame are not available on z/OS.
The functions `__register_frame`/`__deregister_frame` are not
available on z/OS, so add a guard to not use them.

Reviewed By: lhames, abhina.sreeskantharajan

Differential Revision: https://reviews.llvm.org/D84787
2020-08-17 09:00:09 -04:00
Lang Hames
90bd74632c [JITLink][MachO] Use correct symbol scope when N_PEXT is set and N_EXT unset.
MachOLinkGraphBuilder has been treating these as hidden, but they should be
treated as local.

Symbols with N_PEXT set and N_EXT unset are produced when hidden symbols are
run through 'ld -r' without passing -keep_private_externs. They will show up
under 'nm -m' as "was private extern", hence the name of the test cases.

Testcase commited as relocatable object to ensure that the test suite doesn't
depend on having 'ld -r' available.
2020-08-15 15:53:33 -07:00
Stefan Gränitz
cc0c266c03 [ORC][NFC] Refactor loop to determine name of init symbol in IRMaterializationUnit
This loop caused me a little headache once, because I didn't see the assigned variable is a member. The refactored version appears more readable to me.

Differential Revision: https://reviews.llvm.org/D85922
2020-08-14 11:34:44 +02:00
Stefan Gränitz
6fbf5cb68f [ORC][NFC] Fix typo in comment 2020-08-13 21:14:20 +02:00
Stefan Gränitz
4f0d2712f5 [ORC] cloneToNewContext() can work with a const-ref to ThreadSafeModule 2020-08-13 21:01:21 +02:00
Lang Hames
03af0b44e9 [JITLink][MachO] Return an error when MachO TLV relocations are encountered.
MachO TLV relocations aren't supported yet. Error out rather than falling
through to llvm_unreachable.
2020-08-13 11:19:35 -07:00
Lang Hames
ce159bf33c [llvm-jitlink] Update llvm-jitlink to use TargetProcessControl. 2020-08-10 17:19:48 -07:00
Lang Hames
94684e8bbe [JITLink][MachO][AArch64] More PAGEOFF12 relocation fixes.
Correctly sign extend the addend, and fix implicit shift operand decoding
(it incorrectly returned 0 for some cases), and check that the initial
encoded immediate is 0.
2020-08-05 21:09:45 -07:00
Lang Hames
7d59db37b7 [JITLink][AArch64] Handle addends on PAGE21 / PAGEOFF12 relocations. 2020-08-05 08:50:46 -07:00
Lang Hames
633245f148 [JITLink][AArch64] Improve debug output for addend relocations. 2020-08-05 08:50:46 -07:00
David Turner
221f10ac36 Do not map read-only data memory sections with EXECUTE flags.
The code in SectionMemoryManager.cpp unnecessarily maps
read-only data sections with the READ+EXECUTE flags. This is
undesirable from a security stand-point.

Moreover, on the Fuchsia platform, which is now very strict
about mapping pages with the EXECUTE permission, this simply
fails, because the section's pages were initially allocated
with only the READ+WRITE flags.

A more detailed description of the issue can be found in this
public SwiftShader bug:

  https://issuetracker.google.com/issues/154586551

This patch just restrict the mapping to the READ flag for ROData
sections. Code sections are still mapped with READ+EXECUTE as
expected.

Reviewed By: lhames

Differential Revision: https://reviews.llvm.org/D78574
2020-08-05 10:51:48 +02:00
Lang Hames
ec5336f4a3 [llvm-jitlink] Add support for static archives and MachO universal archives.
Archives can now be specified as input files the same way that object
files are. Archives will always be linked after all objects (regardless
of the relative order of the inputs) but before any dynamic libraries or
process symbols.

This patch also relaxes matching for slice triples in
StaticLibraryDefinitionGenerator in order to support this feature:
Vendors need not match if the source vendor is unknown.
2020-08-03 12:58:00 -07:00
Lang Hames
b014cb8f2f [llvm-jitlink] Add -phony-externals option to suppress unresolved externals.
The -phony-externals option adds a generator which explicitly defines any
otherwise unresolved externals as null. This transforms link-time
unresolved-symbol errors into potential runtime null pointer accesses
(if an unresolved external is actually accessed during execution).

This option can be useful in -harness mode to avoid having to mock a
large number of symbols that are not reachable at runtime (e.g. unused
methods referenced by a class vtable).
2020-08-01 18:33:44 -07:00
Hans Wennborg
30c3d4b6b4 RuntimeDyldELF: report_fatal_error instead of asserting for unimplemented relocations (PR46816)
This fixes the ExecutionEngine/MCJIT/stubs-sm-pic.ll test in no-asserts
builds which is set to XFAIL on some platforms like 32-bit x86. More
importantly, we probably don't want to silently error in these cases.

Differential revision: https://reviews.llvm.org/D84390
2020-07-31 20:06:47 +02:00
Lang Hames
6ca1bd0130 [llvm-jitlink] Add -harness option to llvm-jitlink.
The -harness option enables new testing use-cases for llvm-jitlink. It takes a
list of objects to treat as a test harness for any regular objects passed to
llvm-jitlink.

If any files are passed using the -harness option then the following
transformations are applied to all other files:

  (1) Symbols definitions that are referenced by the harness files are promoted
      to default scope. (This enables access to statics from test harness).

  (2) Symbols definitions that clash with definitions in the harness files are
      deleted. (This enables interposition by test harness).

  (3) All other definitions in regular files are demoted to local scope.
      (This causes untested code to be dead stripped, reducing memory cost and
      eliminating spurious unresolved symbol errors from untested code).

These transformations allow the harness files to reference and interpose
symbols in the regular object files, which can be used to support execution
tests (including fuzz tests) of functions in relocatable objects produced by a
build.
2020-07-30 15:26:19 -07:00
Lang Hames
eeb8251d74 [JITLink] Allow JITLinkContext::notifyResolved to return an Error.
This allows clients to detect invalid transformations applied by JITLink passes
(e.g. inserting or removing symbols in unexpected ways) and terminate linking
with an error.

This change is used to simplify the error propagation logic in
ObjectLinkingLayer.
2020-07-30 15:26:18 -07:00
Lang Hames
c3522a840c [ORC] Remove a redundant call to getTargetMemory. 2020-07-26 17:34:31 -07:00
Lang Hames
ef607c6171 [ORC] Rename TargetProcessControl DynamicLibraryHandle and loadLibrary.
The new names, DylibHandle and loadDylib, are more concise and make
clear that these utilities are for loading dynamic libraries, not static
ones.
2020-07-25 15:21:43 -07:00
Lang Hames
8dd38c568c [ORC] Don't require PageSize or Triple during TargetProcessControl construction
Subclasses will commonly gather that information from a remote during
construction, in which case they won't have meaningful values to pass to
TargetProcessControl's constructor.
2020-07-25 15:21:43 -07:00
Lang Hames
85d946b864 [ORC] Enable use of TargetProcessControl::getMemMgr with ObjectLinkingLayer.
This patch makes ownership of the JITLinkMemoryManager by ObjectLinkingLayer
optional: the layer can still own the memory manager but no longer has to.

Evevntually we want to move to a state where ObjectLinkingLayer never owns its
memory manager. For now allowing optional ownership makes it easier to develop
classes that can dynamically use either RTDyldObjectLinkingLayer, which owns
its memory managers, or ObjectLinkingLayer (e.g. LLJIT).
2020-07-23 16:18:57 -07:00
Simon Pilgrim
51c99e5a66 Speculation.h - remove unnecessary includes. NFC. 2020-07-23 11:58:23 +01:00
Lang Hames
6f874be76d [ORC] Add a TargetProcessControl-based dynamic library search generator.
TPCDynamicLibrarySearchGenerator uses a TargetProcessControl instance to
load libraries and search for symbol addresses in a target process. It
can be used in place of a DynamicLibrarySearchGenerator to enable
target-process agnostic lookup.
2020-07-22 16:19:24 -07:00
Lang Hames
abf1154870 [ExecutionEngine] Initialize near block hint in SectionMemoryManager.
When allocating a new memory block in SectionMemoryManager, initialize
the Near hint for the other memory groups if they have not been set
already.

Patch by Dana Koch. Thanks Dana!
2020-07-20 14:40:54 -07:00
Lang Hames
431c554507 [ORC] Refactor TrampolinePool to reduce virtual function calls.
Virtual function calls are now only made when the pool needs to be
grown to accommodate o new request.
2020-07-19 22:38:41 -07:00
Lang Hames
d1e90bdbbe [JITLink][MachO] Tidy up debugging output for relocation parsing.
Identify relocations by (section name, offset) pairs, rather than plain
vmaddrs. This makes it easier to cross-reference debugging output for
relocations with output from standard object inspection tools (otool,
readelf, objdump, etc.).
2020-07-19 19:45:50 -07:00
Lang Hames
69d6a0c172 [JITLink][MachO] Fix handling of non-extern UNSIGNED pair of SUBTRACTOR relocs.
When processing a MachO SUBTRACTOR/UNSIGNED pair, if the UNSIGNED target
is non-extern then check the r_symbolnum field of the relocation to find
the targeted section and use the section's address to find 'ToSymbol'.

Previously 'ToSymbol' was found by loading the initial value stored at
the fixup location and treating this as an address to search for. This
is incorrect, however: the initial value includes the addend and will
point to the wrong block if the addend is less than zero or greater than
the block size.

rdar://65756694
2020-07-19 10:22:55 -07:00
Logan Smith
435cea1283 [llvm][NFC] Add missing 'override's 2020-07-17 17:35:59 -07:00
David Tenty
b0aea9c3d7 [z/OS][AIX] Move lambda definition to fix build problem
This is a follow on change to eed19bd8 and contains a fix for a build
failure that occurs on both z/OS and AIX as a result of this commit:

https://reviews.llvm.org/rG670915094462d831e3733e5b01a76471b8cf6dd8.
2020-07-17 10:08:01 -04:00
Benjamin Kramer
1ba25f1bd7 Make helpers static. NFC. 2020-07-17 13:49:11 +02:00
Lang Hames
6cda7d4909 [ORC] Switch from initializer lists to named arguments to work around MSVC.
MSVC doesn't like some of the initializer list uses in 0e940d55f8a.
Switch to named arguments to work around this.
2020-07-16 15:58:31 -07:00
Lang Hames
0a5b56b9cd [ORC] Add more explicit casts to fix a narrowing conversion errors. 2020-07-16 15:37:18 -07:00
Lang Hames
9358e00666 [ORC] Add explicit cast to fix a narrowing conversion error. 2020-07-16 15:33:02 -07:00
Lang Hames
757f986da8 [ORC] Add TargetProcessControl and TPCIndirectionUtils APIs.
TargetProcessControl is a new API for communicating with JIT target processes.
It supports memory allocation and access, and inspection of some process
properties, e.g. the target proces triple and page size.

Centralizing these APIs allows utilities written against TargetProcessControl
to remain independent of the communication procotol with the target process
(which may be direct memory access/allocation for in-process JITing, or may
involve some form of IPC or RPC).

An initial set of TargetProcessControl-based utilities for lazy compilation is
provided by the TPCIndirectionUtils class.

An initial implementation of TargetProcessControl for in-process JITing
is provided by the SelfTargetProcessControl class.

An example program showing how the APIs can be used is provided in
llvm/examples/OrcV2Examples/LLJITWithTargetProcessControl.
2020-07-16 15:09:13 -07:00
Jared Wyles
3a74adf066 [jitlink] Adding support for PCRel32GOTLoad in ELF x86 for the jitlinker
Summary: This adds the basic support for GOT in elf x86.
Was able to just get away using the macho code by generalising the edges.
There will be a follow up patch to turn that into a generic utility for both of the x86 and Mach-O code.

This patch also lands support for relocations relative to symbol.

Reviewers: lhames

Subscribers: hiraditya, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D83748
2020-07-16 07:15:08 +10:00
Abhina Sreeskantharajan
14ef44b9eb [NFC] [AIX] [z/OS] Fix build failure on AIX and z/OS
Summary: This PR contains a build failure fix that occurs on both AIX and z/OS as a result of this commit https://reviews.llvm.org/rG670915094462d831e3733e5b01a76471b8cf6dd8.

Reviewers: uweigand, Kai, hubert.reinterpretcast, daltenty, lhames

Reviewed By: Kai, hubert.reinterpretcast, daltenty

Subscribers: SeanP, hiraditya, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D83889
2020-07-15 16:07:34 -04:00
Richard Smith
cc9b585279 Make LazyCallThroughManager destructor virtual rather than arranging for
all clients to delete it via the correct dynamic type.
2020-07-14 18:41:07 -07:00
Richard Smith
f972afbec0 Fix undefined behavior due to deleting an object with a non-virtual
destructor via a pointer of the wrong static type.

This caused crashes during deallocation in C++14 builds when using a
deallocator whose sized delete requires the size argument to be correct.

Also make the LazyCallThroughManager destructor protected to catch this
sort of bug in the future.
2020-07-14 17:17:20 -07:00
Lang Hames
55f9c4d2ce [ORC] Don't take ownership of the trampoline pool in LazyReexportsManager.
LazyReexportsManager instances use the trampoline pool, but they don't need to
own it. Keeping TrampolinePool ownership separate allows re-use of the
trampoline pool by other clients.
2020-07-14 10:56:45 -07:00
Lang Hames
16e50e0984 [ORC] Remove a spurious reinterpret_cast. 2020-07-13 12:39:24 -07:00
Lang Hames
be5f814275 [ORC] Generalize emit re-entry, stub, etc. APIs for working addr != link addr.
This patch generalizes the APIs for writing re-entry blocks, trampolines and
stubs to allow their final linked address to differ from the address of
their initial working memory. This will allow these routines to be used with
JITLinkMemoryManagers, which will in turn allow for unification of code paths
for in-process and cross-process lazy JITing.
2020-07-13 10:15:10 -07:00
Lang Hames
537809811c [ORC] Modify LazyCallThroughManager to support asynchronous resolution.
Asynchronous resolution is a better fit for handling reentry over
IPC/RPC where we want to avoid blocking a communication handler/thread.
2020-07-08 21:13:55 -07:00
Christopher Tetreault
b0b0a7801d [SVE] Remove calls to VectorType::getNumElements from ExecutionEngine
Reviewers: efriedma, lhames, sdesmalen, fpetrogalli

Reviewed By: lhames, sdesmalen

Subscribers: tschuett, hiraditya, rkruppe, psnobl, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D82211
2020-06-30 11:05:38 -07:00
Guillaume Chatelet
90d9339006 [Alignment][NFC] migrate DataLayout::getPreferredAlignment
This patch is part of a series to introduce an Alignment type.
See this thread for context: http://lists.llvm.org/pipermail/llvm-dev/2019-July/133851.html
See this patch for the introduction of the type: https://reviews.llvm.org/D64790

Differential Revision: https://reviews.llvm.org/D82752
2020-06-29 11:24:36 +00:00
Lang Hames
832526028d [JITLink] Display host -> target address mapping in debugging output.
This can be helpful for sanity checking JITLink memory manager behavior.
2020-06-19 10:05:02 -07:00
Lang Hames
d94eb15087 [RuntimeDyld] Add dependence on Core.
Commit 498dd745f55 introduced a dependence on Core. This patch updates
LLVMbuild.txt to reflect this.
2020-06-15 11:14:27 -07:00
Lang Hames
710863f2b4 [ORC] Honor linker private global prefix on symbol names.
If a symbol name begins with the linker private global prefix (as
described by the DataLayout) then it should be treated as non-exported,
regardless of its LLVM IR visibility value.
2020-06-15 10:28:36 -07:00
Leonard Chan
d0ab705b24 [llvm][ELF][AArch64] Handle R_AARCH64_PLT32 relocation
This patch allows for usage of the @PLT modifier in AArch64 assembly which
lowers to an R_AARCH64_PLT32 relocation. See D81184 for handling this
relocation in lld.

Differential Revision: https://reviews.llvm.org/D81446
2020-06-10 11:34:16 -07:00
Lang Hames
1291eb9615 [ORC] Always use ObjectLinkingLayer/JITLink for MachO on x86-64 and arm64.
JITLink supports all code and relocation models, so there's no reason to
conditionalize using JITLink on the code or relocation model settings.

Clients wanting to use RTDyldObjectLinkingLayer/RuntimeDyld will now
need to use a custom object linking layer creator.
2020-06-05 21:02:29 -07:00
Lang Hames
5729b54948 [JITLink] Skip debug sections in MachO objects.
Debug sections will not be linked into the final executable and may contain
ambiguous relocations*. Skipping them avoids both some unnecessary processing
cost and the hassle of dealing with the problematic relocations.

* E.g. __debug_ranges contains non-extern relocations to the end of functions
hat begin with named symbols. Under the usual rules for interpreting non-extern
relocations these will be incorrectly associated with the following block, or
no block at all (if there is a gap between one block and the next).
2020-06-03 11:08:14 -07:00
Jared Wyles
a93205f987 [jitlink] R_X86_64_PC32 support for the elf x86 jitlinker
Summary:

Adding in our first relocation type, and all the required plumbing to support the rest in following patches

Differential Revision: https://reviews.llvm.org/D80613

Reviewer: lhames
2020-05-30 10:53:18 +10:00
Lang Hames
9acf657a35 [ORC] Add debugging output for LLJIT construction.
This can be handy for checking whether the LLJIT instance you're constructing
matches your expectations.
2020-05-28 20:31:50 -07:00
Lang Hames
4f5e68aaf3 [JITLink] Improve llvm-jitlink regression testing support for ELF.
This patch adds a jitlink pass, 'registerELFGraphInfo', that records section
and symbol information about each LinkGraph in the llvm-jitlink session object.
This allows symbols and sections to be referred to by name in llvm-jitlink
regression tests. This will enable a testcase to be written for
https://reviews.llvm.org/D80613.
2020-05-28 20:31:50 -07:00
David Blaikie
30e53f607c Roll variables into an LLVM_DEBUG block to address -Wunused-but-set-variable 2020-05-26 12:05:08 -07:00
Simon Pilgrim
103e684408 Fix msvc "switch statement contains 'default' but no 'case' labels" warning. NFC.
Stripped out the switch statement, but kept case labels as comments for future reference.
2020-05-22 10:49:10 +01:00
Lang Hames
ee91e79e53 [JITLink] Initial implementation of ELF / x86-64 support for JITLink.
This initial implementation supports section and symbol parsing, but no
relocation support. It enables JITLink to link and execute ELF relocatable
objects that do not require relocations.

Patch by Jared Wyles. Thanks Jared!

Differential Revision: https://reviews.llvm.org/D79832
2020-05-21 21:44:00 -07:00
Lang Hames
a145c06983 [ORC] Share ownership of JITDylibs between ExecutionSession and
MaterializationResponsibility.

MaterializationResponsibility objects provide a connection between a
materialization process (compiler, jit linker, etc.) and the JIT state held in
the ExecutionSession and JITDylib objects. Switching to shared ownership
extends the lifetime of JITDylibs to ensure they remain accessible until all
materializers targeting them have completed. This will allow (in a follow-up
patch) JITDylibs to be removed from the ExecutionSession and placed in a
pending-destruction state while they are kept alive to communicate errors
to/from any still-runnning materialization processes. The intent is to enable
JITDylibs to be safely removed even if they have running compiles targeting
them.
2020-05-10 16:37:17 -07:00
Lang Hames
7864e622b1 [ORC] Rename SearchOrder operations on JITDylib to LinkOrder.
Refering to the link order of a dylib better matches the terminology used in
static compilation. As upcoming patches will increase the number of places where
link order matters (for example when closing JITDylibs) it's better to get this
name change out of the way early.
2020-05-04 16:47:52 -07:00
Lang Hames
1493399b9d [JITLink] Fix missing ADDITIONAL_HEADER_DIRS for the LLVMJITLink component.
Also adds target_link_libraries.

Thanks to @jcmac for spotting this.
2020-05-04 12:58:09 -07:00
Lang Hames
65ff3816c6 [JITLink] Fix a typo in a comment.
Thanks to @jcmac for pointing this out.
2020-05-04 12:58:09 -07:00
Sam McCall
9e1817bf4e std::isspace -> llvm::isSpace (where locale should be ignored)
I've left out some cases where I wasn't totally sure this was right or
whether the include was ok (compiler-rt) or idiomatic (flang).
2020-05-02 15:36:04 +02:00
Xing GUO
0cc48af0ab [Object] Change ObjectFile::getSymbolValue() return type to Expected<uint64_t>
Summary:
In D77860, we have changed `getSymbolFlags()` return type to `Expected<uint32_t>`.
This change helps bubble the error further up the stack.

Reviewers: jhenderson, grimar, JDevlieghere, MaskRay

Reviewed By: jhenderson

Subscribers: hiraditya, MaskRay, rupprecht, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D79075
2020-05-02 14:04:44 +08:00
Craig Topper
8757f48ecf [IR] Replace all uses of CallBase::getCalledValue() with getCalledOperand().
This method has been commented as deprecated for a while. Remove
it and replace all uses with the equivalent getCalledOperand().

I also made a few cleanups in here. For example, to removes use
of getElementType on a pointer when we could just use getFunctionType
from the call.

Differential Revision: https://reviews.llvm.org/D78882
2020-04-27 22:17:03 -07:00
Lang Hames
59e4d993a0 [JITLink] Fix endianness bug fedd32e2fa36.
The ByteSwap_NN functions return their result rather than modifying their
argument in-place, so we need to write the result back to CPUType here.
2020-04-27 10:40:11 -07:00
Simon Pilgrim
fe37a7c733 MCJIT.h - reduce unnecessary includes to forward declarations. NFC. 2020-04-25 12:58:25 +01:00
Simon Pilgrim
1ad8ea0571 RuntimeDyldELF.h - make the object namespace explicit for ELFObjectFileBase. NFC. 2020-04-23 13:52:49 +01:00
Lang Hames
4713d7a998 [JITLink] Fix edge removal iterator invalidation.
This patch changes Block::removeEdge to return a valid iterator to the new next
element, and uses this to update the edge removal algorithm in
LinkGraph::splitBlock.
2020-04-22 14:16:46 -07:00
Lang Hames
2ccfae6930 [JITLink] Read MachO Header CPU field only in jitLink_MachO.
It's the only field we need in this function.
2020-04-22 14:16:46 -07:00
Christopher Tetreault
7f0438624e [SVE] Add new VectorType subclasses
Summary:
Introduce new types for fixed width and scalable vectors.

Does not remove getNumElements yet so as to not break code during transition
period.

Reviewers: deadalnix, efriedma, sdesmalen, craig.topper, huntergr

Reviewed By: sdesmalen

Subscribers: jholewinski, arsenm, jvesely, nhaehnle, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, liufengdb, kerbowa, Joonsoo, grosul1, frgossen, lldb-commits, tschuett, hiraditya, rkruppe, psnobl, llvm-commits

Tags: #llvm, #lldb

Differential Revision: https://reviews.llvm.org/D77587
2020-04-22 08:59:01 -07:00
Simon Pilgrim
46fa565705 RuntimeDyldImpl.h - remove unused Twine forward declaration. NFC. 2020-04-22 15:07:17 +01:00
Craig Topper
bb554c7b77 [CallSite removal] Remove unneeded includes of CallSite.h. NFC 2020-04-22 00:07:13 -07:00
Craig Topper
a51a057b22 [CallSite removal][ExecutionEngine] Use CallBase in the Interpreter. NFC
Differential Revision: https://reviews.llvm.org/D78475
2020-04-20 10:37:03 -07:00
Lang Hames
c0b552bc67 [ORC] Replace LLJIT::defineAbsolute with an LLJIT::define convenience method.
LLJIT::defineAbsolute did not mangle its Name argument, which is inconsistent
with the behavior of other LLJIT methods (e.g. lookup). Since it is currently
unused anyway, this commit replaces it with a generic 'define' convenience
method for adding MaterializationUnits to the main JITDylib. This simplifies
use of the generic absoluteSymbols function (as well as the symbolAlias,
reexports and other functions that generate MaterializationUnits) with LLJIT.
2020-04-18 14:16:54 -07:00
vgxbj
bbdc25ab11 [Object] Change uint32_t getSymbolFlags() to Expected<uint32_t> getSymbolFlags().
This change enables getSymbolFlags() to return errors which benefit error reporting in clients.

Differential Revision: https://reviews.llvm.org/D77860
2020-04-18 21:27:57 +08:00
Lang Hames
ce4983f5c3 [Object] Remove conditional layout of bitfields in MachO::relocation_info.
This removes the conditional layout of relocation_info bitfields that was
introduced in 3ccd677bf (svn r358839). The platform relocation_info
struct (defined in usr/include/mach-o/reloc.h) does not define the layout of
this struct differently on big-endian platforms and we want to keep the LLVM
and platform definitions in sync.

To fix the bug that 3ccd677bf addressed this patch modifies JITLink to construct
its relocation_info structs from the raw relocation words using shift and mask
operations.
2020-04-16 16:17:36 -07:00
Sergej Jaskiewicz
430e5ccef4 Introduce llvm::sys::Process::getProcessId() and adopt it
Differential Revision: https://reviews.llvm.org/D78022
2020-04-16 15:05:37 +03:00
Lang Hames
deddb8bde9 [ORC] Add an OrcV2 C API function for configuring TargetMachines. 2020-04-10 15:51:29 -07:00
Lang Hames
4315ffca85 [ORC] Require JITDylib to be specified when adding IR and objects in the C API. 2020-04-09 17:59:26 -07:00
Lang Hames
a737d1b399 [ORC] Add C API support for adding object files to an LLJIT instance. 2020-04-09 16:18:46 -07:00
Lang Hames
e2925289c9 [ORC] Expand the OrcV2 C API bindings.
Adds basic support for LLJITBuilder and DynamicLibrarySearchGenerator. This
allows C API clients to configure LLJIT to expose process symbols to JIT'd
code. An example of this is added in
llvm/examples/OrcV2CBindingsReflectProcessSymbols.
2020-04-09 16:18:46 -07:00
Lang Hames
6cbaa73f51 [ORC] Make mangling convenience methods part of the public API of LLJIT.
This saves clients from having to manually construct a MangleAndInterner.
2020-04-08 20:20:13 -07:00
Benjamin Kramer
97d5ac4c23 [RuntimeDyld] Replace hand-rolled endian conversion with support::endian. NFCI. 2020-04-06 13:22:53 +02:00
Lang Hames
5c93ab4970 [ORC] Add MachO universal binary support to StaticLibraryDefinitionGenerator.
Add a new overload of StaticLibraryDefinitionGenerator::Load that takes a triple
argument and supports loading archives from MachO universal binaries in addition
to regular archives.

The LLI tool is updated to use this overload.
2020-04-05 20:21:05 -07:00
Lang Hames
da5bdc7302 Re-apply 0071eaaf089, "[ORC] Export __cxa_atexit ...", with fixes.
Forgot to include part of the testcase. Thank to Nico for spotting that and
reverting!
2020-04-02 16:03:35 -07:00
Nico Weber
f66efc2783 Revert "[ORC] Export __cxa_atexit from the main JITDylib in LLJIT."
This reverts commit 0071eaaf0892d7ef733578312abefdcf84311071.
Inputs/noop-main.ll wasn't checked in, so this breaks check-llvm
everywhere.
2020-04-01 22:49:38 -04:00
Lang Hames
b3739f14b9 [ORC] Export __cxa_atexit from the main JITDylib in LLJIT.
Failure to export __cxa_atexit can lead to an attempt to import a definition
from the process itself (if __cxa_atexit is referenced from another JITDylib),
but the process definition will clash with the existing non-exported definition
to produce an unexpected DuplicateDefinitionError.

This patch fixes the immediate issue by exporting __cxa_atexit. It also fixes a
bug where atexit functions in other JITDylibs were not being run by adding a
copy of run_atexits_helper to every JITDylib.

A follow up patch will deal with the bug where definition generators are called
despite a non-exported definition being present.
2020-04-01 19:12:08 -07:00
Lang Hames
df818b7034 [ORC] Don't require a null-terminator on MemoryBuffers for objects in archives.
The MemoryBuffer::getMemBuffer method's RequiresNullTerminator parameter
defaults to true, but object files are not null terminated so we need to
explicitly pass false here.
2020-04-01 12:16:38 -07:00
Eli Friedman
db20f1e2c5 Remove "mask" operand from shufflevector.
Instead, represent the mask as out-of-line data in the instruction. This
should be more efficient in the places that currently use
getShuffleVector(), and paves the way for further changes to add new
shuffles for scalable vectors.

This doesn't change the syntax in textual IR. And I don't currently plan
to change the bitcode encoding in this patch, although we'll probably
need to do something once we extend shufflevector for scalable types.

I expect that once this is finished, we can then replace the raw "mask"
with something more appropriate for scalable vectors.  Not sure exactly
what this looks like at the moment, but there are a few different ways
we could handle it.  Maybe we could try to describe specific shuffles.
Or maybe we could define it in terms of a function to convert a fixed-length
array into an appropriate scalable vector, using a "step", or something
like that.

Differential Revision: https://reviews.llvm.org/D72467
2020-03-31 13:08:59 -07:00
Lang Hames
c9245d5323 [ORC] Introduce JITSymbolFlags::HasMaterializeSideEffectsOnly flag.
This flag can be used to mark a symbol as existing only for the purpose of
enabling materialization. Such a symbol can be looked up to trigger
materialization with the lookup returning only once materialization is
complete. Symbols with this flag will never resolve however (to avoid
permanently polluting the symbol table), and should only be looked up using
the SymbolLookupFlags::WeaklyReferencedSymbol flag. The primary use case for
this flag is initialization symbols.
2020-03-27 11:02:54 -07:00
Lang Hames
c31e638b4f [ORC] Don't create MaterializingInfo entries unnecessarily. 2020-03-27 11:02:54 -07:00
Alina Sbirlea
a5d6fe1986 [CFG/BasicBlock] Rename succ_const to const_succ. [NFC]
Summary:
Rename `succ_const_iterator` to `const_succ_iterator` and
`succ_const_range` to `const_succ_range` for consistency with the
predecessor iterators, and the corresponding iterators in
MachineBasicBlock.

Reviewers: nicholas, dblaikie, nlewycky

Subscribers: hiraditya, bmahjour, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75952
2020-03-25 12:40:55 -07:00
Lang Hames
885fe25f2c [ORC] Move ostream operators for debugging output out of Core.h.
DebugUtils.h seems like a more appropriate home for these.
2020-03-21 18:27:28 -07:00
Lang Hames
f9245f3da0 [ORC] Re-apply 98f2bb44610, enable JITEventListeners in OrcV2, with fixes.
Updates the object buffer ownership scheme in jitLinkForOrc and related
functions: Ownership of both the object::ObjectFile and underlying
MemoryBuffer is passed into jitLinkForOrc and passed back to the onEmit
callback once linking is complete. This avoids the use-after-free errors
that were seen in 98f2bb44610.
2020-03-19 16:30:08 -07:00
Lang Hames
dac63bbcfc [ORC] Don't use a platform mutex for LLJIT's GenericLLVMIRPlatformSupport class.
Along the same lines as eb918d8daf1: This code also had to acquire the session
mutex, and this could cause a deadlock under the wrong circumstances. This
patch updates GenericLLVMIRPlatformSupport to just use the session lock for
everything.
2020-03-19 11:03:34 -07:00
Lang Hames
2945504341 [ORC] Fix indentation in debugging output. 2020-03-19 11:02:56 -07:00
Lang Hames
f62b9d12ef [ORC] Use finer-grained and session locking in MachOPlatform to avoid deadlock.
In MachOPlatform, obtaining the link-order for a JITDylib requires locking the
session, but also needs to be part of a larger atomic operation that collates
initializer symbols tracked by the platform. Trying to do this under a separate
platform mutex leads to potential locking order issues, e.g.

T1 locks session then tries to lock platform to register a new init symbol
meanwhile
T2 locks platform then tries to lock session to obtain link order.

Removing the platform lock and performing all these operations under the session
lock eliminates this possibility.

At the same time we also need to collate init pointers from the
MachOPlatform::InitScraperPlugin, and we don't need or want to lock the session
for that. The new InitSeqMutex has been added to guard these init pointers, and
the session mutex is never obtained while the InitSeqMutex is held.
2020-03-19 11:02:56 -07:00
Lang Hames
ea57541031 [ORC] Don't waste time building empty replacement MaterializationUnits. 2020-03-19 11:02:56 -07:00
Lang Hames
91189ff985 [ORC] Bail out early if a replacement MaterializationUnit is empty.
The MU may define no symbols, but still contain a non-trivial destructor (e.g.
an LLVM IR module that has been stripped of all externally visible
definitions, but which still needs to lock its context to be destroyed).
Bailing out early ensures that we destroy the unit outside the session lock,
rather than under it which may cause deadlocks.

Also adds some extra sanity-checking assertions.
2020-03-19 11:02:56 -07:00
Fangrui Song
bb43600d6c [Object] Change ELFObjectFile<ELFT>::getFileFormatName() to use BFD names
Follow-up for D74433

What the function returns are almost standard BFD names, except that "ELF" is
in uppercase instead of lowercase.

This patch changes "ELF" to "elf" and changes ARM/AArch64 to use their BFD names.
MIPS and PPC64 have endianness differences as well, but this patch does not intend to address them.

Advantages:

* llvm-objdump: the "file format " line matches GNU objdump on ARM/AArch64 objects
* "file format " line can be extracted and fed into llvm-objcopy -O literally.
  (https://github.com/ClangBuiltLinux/linux/issues/779 has such a use case)

Affected tools: llvm-readobj, llvm-objdump, llvm-dwarfdump, MCJIT (internal implementation detail, not exposed)

Reviewed By: jhenderson

Differential Revision: https://reviews.llvm.org/D76046
2020-03-16 07:42:04 -07:00
Lang Hames
82ffd8566c Revert "[ORC] Enable JITEventListeners in the RTDyldObjectLinkingLayer."
This reverts commit 98f2bb4461072347dcca7d2b1b9571b3a6525801.

Reverting while I investigate bot failures.
2020-03-15 15:35:08 -07:00
Lang Hames
64ff6abf1f [ORC] Enable JITEventListeners in the RTDyldObjectLinkingLayer.
Enable use of ExecutionEngine JITEventListeners in RTDyldObjectLinkingLayer.
This allows existing MCJIT clients to more easily migrate to LLJIT / ORCv2.

Example usage in llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener.

Differential Revision: https://reviews.llvm.org/D75838
2020-03-15 15:14:46 -07:00
Lang Hames
13786f8eaf [ORC] Print symbol flags and materializer name in ExecutionSession::dump.
The extra information can be helpful in diagnosing JIT bugs.
2020-03-14 18:52:10 -07:00
Lang Hames
42492d3889 [JITLink][MachO] Re-apply b64afadf306, MachO linker-private support, with fixes.
Global symbols with linker-private prefixes should be resolvable across object
boundaries, but internal symbols with linker-private prefixes should not.
2020-03-14 18:36:15 -07:00
Lang Hames
80d993d0f0 Revert "[JITLink][MachO] Treat linker private symbols as hidden rather than private."
This reverts commit b64afadf306f284a684ee656c6eefbd43c192c8d.

Reverting while I investigate bot failures.
2020-03-14 16:52:25 -07:00
Lang Hames
16ceeef4af [JITLink][MachO] Treat linker private symbols as hidden rather than private.
Linker-private symbols should be resolvable across object file boundaries.
2020-03-14 16:33:15 -07:00
Lang Hames
4ce58a4d70 [Orc] Add basic OrcV2 C bindings and example.
Renames the llvm/examples/LLJITExamples directory to llvm/examples/OrcV2Examples
since it is becoming a home for all OrcV2 examples, not just LLJIT.

See http://llvm.org/PR31103.
2020-03-14 14:41:22 -07:00
Jan Korous
0fd46fd26a [LLJIT] Add std::move() as a workaround for older compilers
Clang 3.8 isn't able to bind the variable to rvalue-ref which breaks the build.
2020-03-13 15:25:25 -07:00
Lang Hames
c3e7231c1f [MCJIT] Check for RuntimeDyld errors in MCJIT::finalizeLoadedModules.
Patch based on https://reviews.llvm.org/D75912 by Alexander Shishkin. Thanks
Alexander!

To minimize disruption to existing clients, who may be relying on the fact that
unused references to unresolved symbols do not generate an error, this patch
makes error checking opt-in: Clients can call ExecutionEngine::hasError or
LLVMExecutionEngineGetError to check whether and error has occurred.

Differential revision: https://reviews.llvm.org/D75912
2020-03-13 13:58:41 -07:00
Lang Hames
2e64fe9bf7 [ORC] Enable exception handling in JIT'd code when using LLJIT on Darwin.
This patch enables exception handling in code added to LLJIT on Darwin by
adding an orc::EHFrameRegistrationPlugin instance to the ObjectLinkingLayer
(which is currently used on Darwin only).
2020-03-12 15:33:56 -07:00
Lang Hames
a043ecbcf2 [ORC] Add a mutex to guard EHFrameRegistrationPlugin data structures.
These may be accessed from multiple threads if concurrent materialization is
enabled in ORC.

Testcase coming in a follow-up patch that enables eh-frame registration for
LLJIT.
2020-03-12 15:33:56 -07:00
Lang Hames
851489e81b [JITLink] Read symbol linkage from the correct field.
MachO symbol linkage is described by the desc field of the nlist entry, not the
type field.
2020-03-11 20:04:54 -07:00
Lang Hames
3bba4369ea [ORC] Fix an overly aggressive assert.
It is ok to add dependencies on symbols that are ready, they should just be
skipped.
2020-03-11 20:04:54 -07:00
Lang Hames
6f6fbeb0c0 [ORC] Add some extra debugging output. 2020-03-11 20:04:54 -07:00
Reid Kleckner
61b0badcbd Drop a StringMap.h include, NFC
$ diff -u <(sort thedeps-before.txt) <(sort thedeps-after.txt) \
    | grep '^[-+] ' | sort | uniq -c | sort -nr
    231 -    llvm/include/llvm/ADT/StringMap.h
    171 -    llvm/include/llvm/Support/AllocatorBase.h
    142 -    llvm/include/llvm/Support/PointerLikeTypeTraits.h
2020-03-11 15:45:34 -07:00
Lang Hames
bc59809461 [RuntimeDyld][COFF] Build stubs for COFF dllimport symbols.
Summary:
Enables JIT-linking by RuntimeDyld of COFF objects that contain references to
dllimport symbols. This is done by recognizing symbols that start with the
reserved "__imp_" prefix and building a pointer entry to the target symbol in
the stubs area of the section. References to the "__imp_" symbol are updated to
point to this pointer.

Work in progress: The generic code is in place, but only RuntimeDyldCOFFX86_64
and RuntimeDyldCOFFI386 have been updated to look for and update references to
dllimport symbols.

Reviewers: compnerd

Subscribers: hiraditya, ributzka, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75884
2020-03-10 16:08:40 -07:00
Lang Hames
9a8419c639 [RuntimeDyld] Allow multi-line rtdyld-check and jitlink-check expressions.
This patch allows rtdyld-check / jitlink-check expressions to be extended over
multiple lines by terminating each line with a '\'. E.g.

  # llvm-rtdyld: *{8}X = \
  # llvm-rtdyld:   Y
  X:
    .quad Y

This will be used to break up some long lines in upcoming test cases.
2020-03-10 16:08:40 -07:00
Benjamin Kramer
5193ea06e9 Give helpers internal linkage. NFC. 2020-03-10 18:27:42 +01:00
serge-sans-paille
2cab2132ef Avoid dangling reference on SectionList
Bug spotted by https://cookieplmonster.github.io/2020/02/01/emulator-bug-llvm-bug/

Basically, holding references to object inside a resized vector is a bad idea.

Differential Revision: https://reviews.llvm.org/D75110
2020-03-05 09:42:24 +01:00
Lang Hames
87a444bd04 [ORC] Remove hard dependency on libobjc when using MachOPlatform with LLJIT.
The LLJIT::MachOPlatformSupport class used to unconditionally attempt to
register __objc_selrefs and __objc_classlist sections. If libobjc had not
been loaded this resulted in an assertion, even if no objc sections were
actually present. This patch replaces this unconditional registration with
a check that no objce sections are present if libobjc has not been loaded.
This will allow clients to use MachOPlatform with LLJIT without requiring
libobjc for non-objc code.
2020-03-04 21:49:28 -08:00
Stefan Gränitz
81cfd93bf4 [ORC] Decompose LazyCallThroughManager::callThroughToSymbol()
Summary: Decompose callThroughToSymbol() into findReexport(), resolveSymbol(), notifyResolved() and reportCallThroughError(). This allows derived classes to reuse the functionality while adding their own code in between.

Reviewers: lhames

Reviewed By: lhames

Subscribers: hiraditya, steven_wu, dexonsmith, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75084
2020-03-05 00:24:23 +01:00
Lang Hames
0046e8e4e8 [ORC] Add some debugging output for initializers.
This output can be useful in tracking down initialization failures in the JIT.
2020-03-04 12:38:25 -08:00
Lang Hames
af3fbf0d88 [ORC] Skip ST_File symbols in MaterializationUnit interfaces / resolution.
ST_File symbols aren't relevant for linking purposes, but can end up shadowing
real symbols if they're not filtered.

No test case yet: The ideal testcase for this would be an ELF llvm-jitlink test,
but llvm-jitlink support for ELF is still under development. We should add a
testcase for this once support lands in tree.
2020-03-03 16:15:44 -08:00
Lang Hames
efa76b5281 [JITLink] Fix a pointer-to-integer cast in jitlink::InProcessMemoryManager.
reinterpret_cast'ing the block base address directly to a uint64_t leaves the
high bits in an implementation-defined state, but JITLink expects them to be
zero. Switching to pointerToJITTargetAddress for the cast should fix this.

This should fix the jitlink test failures that we have seen on some of the
32-bit testers.
2020-03-03 13:53:00 -08:00
Lang Hames
ab72e4c1c4 [ORC] Make sure we add initializers to the SymbolFlags map for objects. 2020-03-03 09:33:37 -08:00
Lang Hames
675f5945b9 [ORC] Remove an out-of-date FIXME 2020-03-03 09:33:37 -08:00
Reid Kleckner
80428fb35f Avoid including FileSystem.h from MemoryBuffer.h
Lots of headers pass around MemoryBuffer objects, but very few open
them. Let those that do include FileSystem.h.

Saves ~250 includes of Chrono.h & FileSystem.h:

$ diff -u thedeps-before.txt thedeps-after.txt | grep '^[-+] ' | sort | uniq -c | sort -nr
    254 -    ../llvm/include/llvm/Support/FileSystem.h
    253 -    ../llvm/include/llvm/Support/Chrono.h
    237 -    ../llvm/include/llvm/Support/NativeFormatting.h
    237 -    ../llvm/include/llvm/Support/FormatProviders.h
    192 -    ../llvm/include/llvm/ADT/StringSwitch.h
    190 -    ../llvm/include/llvm/Support/FormatVariadicDetails.h
...

This requires duplicating the file_t typedef, which is unfortunate. I
sunk the choice of mapping mode down into the cpp file using variable
template specializations instead of class members in headers.
2020-02-29 12:30:23 -08:00
Stefan Gränitz
0becb69ddb [ExecutionEngine] Add JITSymbolFlags::fromSummary(GlobalValueSummary*)
Summary: A function that creates JITSymbolFlags from a GlobalValueSummary. Similar functions exist: fromGlobalValue(), fromObjectSymbol()

Reviewers: lhames

Reviewed By: lhames

Subscribers: hiraditya, steven_wu, dexonsmith, arphaman, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D75082
2020-02-29 11:54:03 +00:00
Lang Hames
e1f68ca3b5 [ORC] Remove the JITDylib::SymbolTableEntry::isInMaterializingState() method.
It was being used inconsistently. Uses have been replaced with direct checks
on the symbol state.
2020-02-25 16:44:12 -08:00
Benjamin Kramer
707b7beede [ORC] Remove spammy debug print 2020-02-24 12:10:13 +01:00
Lang Hames
7247401c11 [JITLink] Add a MachO x86-64 GOT and Stub bypass optimization.
This optimization bypasses GOT loads and calls/branches through stubs when the
ultimate target of the access/branch is found to be within range of the
reference.

Extra debugging output is also added to the generic JITLink algorithm and
basic GOT and Stubs builder utility to aid debugging.
2020-02-23 23:38:31 -08:00
Lang Hames
b6c9039962 [ORC] Update LLJIT to automatically run specially named initializer functions.
The GenericLLVMIRPlatformSupport class runs a transform on all LLVM IR added to
the LLJIT instance to replace instances of llvm.global_ctors with a specially
named function that runs the corresponing static initializers (See
(GlobalCtorDtorScraper from lib/ExecutionEngine/Orc/LLJIT.cpp). This patch
updates the GenericIRPlatform class to check for this specially named function
in other materialization units that are added to the JIT and, if found, add
the function to the initializer work queue. Doing this allows object files
that were compiled from IR and cached to be reloaded in subsequent JIT sessions
without their initializers being skipped.

To enable testing this patch also updates the lli tool's -jit-kind=orc-lazy mode
to respect the -enable-cache-manager and -object-cache-dir options, and modifies
the CompileOnDemandLayer to rename extracted submodules to include a hash of the
names of their symbol definitions. This allows a simple object caching scheme
based on module names (which was already implemented in lli) to work with the
lazy JIT.
2020-02-22 11:49:14 -08:00
Lang Hames
46f1687baa [ORC] Add errors for missing and extraneous symbol definitions.
This patch adds new errors and error checking to the ObjectLinkingLayer to
catch cases where a compiled or loaded object either:
(1) Contains definitions not covered by its responsibility set, or
(2) Is missing definitions that are covered by its responsibility set.

Proir to this patch providing the correct set of definitions was treated as
an API contract requirement, however this requires that the client be confident
in the correctness of the whole compiler / object-cache pipeline and results
in difficult-to-debug assertions upon failure. Treating this as a recoverable
error results in clearer diagnostics.

The performance overhead of this check is one comparison of densemap keys
(symbol string pointers) per linking object, which is minimal. If this overhead
ever becomes a problem we can add the check under a flag that can be turned off
if the client fully trusts the rest of the pipeline.
2020-02-22 11:49:14 -08:00
Hans Wennborg
e1296518ec Add #include <condition_variable> to fix build after 85fb997659b5
See https://reviews.llvm.org/D74300#1884614
2020-02-20 16:36:19 +01:00
Lang Hames
117fadbabd [ORC] Fix a missing move. 2020-02-19 14:27:31 -08:00
Lang Hames
900dc7edc7 [ORC] Add generic initializer/deinitializer support.
Initializers and deinitializers are used to implement C++ static constructors
and destructors, runtime registration for some languages (e.g. with the
Objective-C runtime for Objective-C/C++ code) and other tasks that would
typically be performed when a shared-object/dylib is loaded or unloaded by a
statically compiled program.

MCJIT and ORC have historically provided limited support for discovering and
running initializers/deinitializers by scanning the llvm.global_ctors and
llvm.global_dtors variables and recording the functions to be run. This approach
suffers from several drawbacks: (1) It only works for IR inputs, not for object
files (including cached JIT'd objects). (2) It only works for initializers
described by llvm.global_ctors and llvm.global_dtors, however not all
initializers are described in this way (Objective-C, for example, describes
initializers via specially named metadata sections). (3) To make the
initializer/deinitializer functions described by llvm.global_ctors and
llvm.global_dtors searchable they must be promoted to extern linkage, polluting
the JIT symbol table (extra care must be taken to ensure this promotion does
not result in symbol name clashes).

This patch introduces several interdependent changes to ORCv2 to support the
construction of new initialization schemes, and includes an implementation of a
backwards-compatible llvm.global_ctor/llvm.global_dtor scanning scheme, and a
MachO specific scheme that handles Objective-C runtime registration (if the
Objective-C runtime is available) enabling execution of LLVM IR compiled from
Objective-C and Swift.

The major changes included in this patch are:

(1) The MaterializationUnit and MaterializationResponsibility classes are
extended to describe an optional "initializer" symbol for the module (see the
getInitializerSymbol method on each class). The presence or absence of this
symbol indicates whether the module contains any initializers or
deinitializers. The initializer symbol otherwise behaves like any other:
searching for it triggers materialization.

(2) A new Platform interface is introduced in llvm/ExecutionEngine/Orc/Core.h
which provides the following callback interface:

  - Error setupJITDylib(JITDylib &JD): Can be used to install standard symbols
    in JITDylibs upon creation. E.g. __dso_handle.

  - Error notifyAdding(JITDylib &JD, const MaterializationUnit &MU): Generally
    used to record initializer symbols.

  - Error notifyRemoving(JITDylib &JD, VModuleKey K): Used to notify a platform
    that a module is being removed.

  Platform implementations can use these callbacks to track outstanding
initializers and implement a platform-specific approach for executing them. For
example, the MachOPlatform installs a plugin in the JIT linker to scan for both
__mod_inits sections (for C++ static constructors) and ObjC metadata sections.
If discovered, these are processed in the usual platform order: Objective-C
registration is carried out first, then static initializers are executed,
ensuring that calls to Objective-C from static initializers will be safe.

This patch updates LLJIT to use the new scheme for initialization. Two
LLJIT::PlatformSupport classes are implemented: A GenericIR platform and a MachO
platform. The GenericIR platform implements a modified version of the previous
llvm.global-ctor scraping scheme to provide support for Windows and
Linux. LLJIT's MachO platform uses the MachOPlatform class to provide MachO
specific initialization as described above.

Reviewers: sgraenitz, dblaikie

Subscribers: mgorny, hiraditya, mgrang, ributzka, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D74300
2020-02-19 13:59:32 -08:00
Alexandre Ganea
ae05eb086d [Support] On Windows, ensure hardware_concurrency() extends to all CPU sockets and all NUMA groups
The goal of this patch is to maximize CPU utilization on multi-socket or high core count systems, so that parallel computations such as LLD/ThinLTO can use all hardware threads in the system. Before this patch, on Windows, a maximum of 64 hardware threads could be used at most, in some cases dispatched only on one CPU socket.

== Background ==
Windows doesn't have a flat cpu_set_t like Linux. Instead, it projects hardware CPUs (or NUMA nodes) to applications through a concept of "processor groups". A "processor" is the smallest unit of execution on a CPU, that is, an hyper-thread if SMT is active; a core otherwise. There's a limit of 32-bit processors on older 32-bit versions of Windows, which later was raised to 64-processors with 64-bit versions of Windows. This limit comes from the affinity mask, which historically is represented by the sizeof(void*). Consequently, the concept of "processor groups" was introduced for dealing with systems with more than 64 hyper-threads.

By default, the Windows OS assigns only one "processor group" to each starting application, in a round-robin manner. If the application wants to use more processors, it needs to programmatically enable it, by assigning threads to other "processor groups". This also means that affinity cannot cross "processor group" boundaries; one can only specify a "preferred" group on start-up, but the application is free to allocate more groups if it wants to.

This creates a peculiar situation, where newer CPUs like the AMD EPYC 7702P (64-cores, 128-hyperthreads) are projected by the OS as two (2) "processor groups". This means that by default, an application can only use half of the cores. This situation could only get worse in the years to come, as dies with more cores will appear on the market.

== The problem ==
The heavyweight_hardware_concurrency() API was introduced so that only *one hardware thread per core* was used. Once that API returns, that original intention is lost, only the number of threads is retained. Consider a situation, on Windows, where the system has 2 CPU sockets, 18 cores each, each core having 2 hyper-threads, for a total of 72 hyper-threads. Both heavyweight_hardware_concurrency() and hardware_concurrency() currently return 36, because on Windows they are simply wrappers over std:🧵:hardware_concurrency() -- which can only return processors from the current "processor group".

== The changes in this patch ==
To solve this situation, we capture (and retain) the initial intention until the point of usage, through a new ThreadPoolStrategy class. The number of threads to use is deferred as late as possible, until the moment where the std::threads are created (ThreadPool in the case of ThinLTO).

When using hardware_concurrency(), setting ThreadCount to 0 now means to use all the possible hardware CPU (SMT) threads. Providing a ThreadCount above to the maximum number of threads will have no effect, the maximum will be used instead.
The heavyweight_hardware_concurrency() is similar to hardware_concurrency(), except that only one thread per hardware *core* will be used.

When LLVM_ENABLE_THREADS is OFF, the threading APIs will always return 1, to ensure any caller loops will be exercised at least once.

Differential Revision: https://reviews.llvm.org/D71775
2020-02-14 10:24:22 -05:00
Fangrui Song
e81ba0b0a3 [AsmPrinter] De-capitalize all AsmPrinter::Emit* but EmitInstruction
Similar to rL328848.
2020-02-13 17:06:24 -08:00
Lang Hames
b170349fb7 [ORC] Fix symbol dependence propagation algorithm in ObjectLinkingLayer.
ObjectLinkingLayer was not correctly propagating dependencies through local
symbols within an object. This could cause symbol lookup to return before a
searched-for symbol is ready if the following conditions are met:
(1) The definition of the symbol being searched for transitively depends on a
    local symbol within the same object, and that local symbol in turn
    transitively depends on an external symbol provided by some other module
    in the JIT.
(2) Concurrent compilation is enabled.
(3) Thread scheduling causes the lookup of the searched-for symbol to return
    before all transitive dependencies of the looked-up symbol are emitted.

This bug was found by inspection and has not been observed in practice.

A jitlink test case has been added to verify that symbol dependencies are
correctly propagated through local symbol definitions.
2020-02-11 12:56:41 -08:00
Lang Hames
1b4cebd3b1 [ORC] Add debug logging to JITDylib::addDependencies. 2020-02-11 12:56:40 -08:00
Bill Wendling
0816222e8f Revert "Remove redundant "std::move"s in return statements"
The build failed with

  error: call to deleted constructor of 'llvm::Error'

errors.

This reverts commit 1c2241a7936bf85aa68aef94bd40c3ba77d8ddf2.
2020-02-10 07:07:40 -08:00
Bill Wendling
e45b5f33f3 Remove redundant "std::move"s in return statements 2020-02-10 06:39:44 -08:00
Sylvestre Ledru
5c78d195eb Make StringRef's std::string conversion operator explicit
The build is currenly broken when perf or ffi are enabled for llvm

Just like in https://reviews.llvm.org/rG777180a32b61070a10dd330b4f038bf24e916af1
2020-02-01 15:43:45 +01:00
Benjamin Kramer
76555832b5 Another round of GCC5 fixes. 2020-01-29 02:09:24 +01:00
Benjamin Kramer
87d13166c7 Make llvm::StringRef to std::string conversions explicit.
This is how it should've been and brings it more in line with
std::string_view. There should be no functional change here.

This is mostly mechanical from a custom clang-tidy check, with a lot of
manual fixups. It uncovers a lot of minor inefficiencies.

This doesn't actually modify StringRef yet, I'll do that in a follow-up.
2020-01-28 23:25:25 +01:00
Guillaume Chatelet
af9e09671c [Alignment][NFC] Deprecate Align::None()
Summary:
This is a follow up on https://reviews.llvm.org/D71473#inline-647262.
There's a caveat here that `Align(1)` relies on the compiler understanding of `Log2_64` implementation to produce good code. One could use `Align()` as a replacement but I believe it is less clear that the alignment is one in that case.

Reviewers: xbolva00, courbet, bollu

Subscribers: arsenm, dylanmckay, sdardis, nemanjai, jvesely, nhaehnle, hiraditya, kbarton, jrtc27, atanasyan, jsji, Jim, kerbowa, cfe-commits, llvm-commits

Tags: #clang, #llvm

Differential Revision: https://reviews.llvm.org/D73099
2020-01-24 12:53:58 +01:00
Lang Hames
113c4918a7 [ORC] Fix a missing move in ce2207abaf9.
This should fix the build failure at
http://lab.llvm.org:8011/builders/clang-cmake-x86_64-sde-avx512-linux/builds/32524
and others.
2020-01-21 20:14:50 -08:00
Lang Hames
ac6d037b49 [ORC] Add support for emulated TLS to ORCv2.
This commit adds a ManglingOptions struct to IRMaterializationUnit, and replaces
IRCompileLayer::CompileFunction with a new IRCompileLayer::IRCompiler class. The
ManglingOptions struct defines the emulated-TLS state (via a bool member,
EmulatedTLS, which is true if emulated-TLS is enabled and false otherwise). The
IRCompileLayer::IRCompiler class wraps an IRCompiler (the same way that the
CompileFunction typedef used to), but adds a method to return the
IRCompileLayer::ManglingOptions that the compiler will use.

These changes allow us to correctly determine the symbols that will be produced
when a thread local global variable defined at the IR level is compiled with or
without emulated TLS. This is required for ORCv2, where MaterializationUnits
must declare their interface up-front.

Most ORCv2 clients should not require any changes. Clients writing custom IR
compilers will need to wrap their compiler in an IRCompileLayer::IRCompiler,
rather than an IRCompileLayer::CompileFunction, however this should be a
straightforward change (see modifications to CompileUtils.* in this patch for an
example).
2020-01-21 19:55:33 -08:00
Lang Hames
92390e491c [ORC] Add weak symbol support to defineMaterializing, fix for PR40074.
The MaterializationResponsibility::defineMaterializing method allows clients to
add new definitions that are in the process of being materialized to the JIT.
This patch adds support to defineMaterializing for symbols with weak linkage
where the new definitions may be rejected if another materializer concurrently
defines the same symbol. If a weak symbol is rejected it will not be added to
the MaterializationResponsibility's responsibility set. Clients can check for
membership in the responsibility set via the
MaterializationResponsibility::getSymbols() method before resolving any
such weak symbols.

This patch also adds code to RTDyldObjectLinkingLayer to tag COFF comdat symbols
introduced during codegen as weak, on the assumption that these are COFF comdat
constants. This fixes http://llvm.org/PR40074.
2020-01-19 10:46:07 -08:00
Lang Hames
afe0b073a6 [ORC] Set setCloneToNewContextOnEmit on LLJIT's transform layer when needed.
Based on Don Hinton's patch in https://reviews.llvm.org/D72406. This feature
was accidentally left out of e9e26c01cd865da678b1af6ba5f417c713956a66, and
would have pessimized concurrent compilation in the default case.

Thanks for spotting this Don!
2020-01-15 10:22:57 -08:00
Lang Hames
7f70888b46 [ORC] Simplify use of lazyReexports with LLJIT.
This patch makes the target triple available via the LLJIT interface, and moves
the IRTransformLayer from LLLazyJIT down into LLJIT. Together these changes make
it easier to use the lazyReexports utility with LLJIT, and to apply IR
transforms to code as it is compiled in LLJIT (rather than requiring transforms
to be applied manually before code is added). An code example is added in
llvm/examples/LLJITExamples/LLJITWithLazyReexports
2020-01-15 08:02:53 -08:00