LLVM  10.0.0
Layer.cpp
Go to the documentation of this file.
1 //===-------------------- Layer.cpp - Layer interfaces --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm/IR/Constants.h"
11 #include "llvm/Object/ObjectFile.h"
12 #include "llvm/Support/Debug.h"
13 
14 #define DEBUG_TYPE "orc"
15 
16 namespace llvm {
17 namespace orc {
18 
20 
22  return JD.define(std::make_unique<BasicIRLayerMaterializationUnit>(
23  *this, *getManglingOptions(), std::move(TSM), std::move(K)));
24 }
25 
27  const ManglingOptions &MO,
29  : MaterializationUnit(SymbolFlagsMap(), std::move(K)), TSM(std::move(TSM)) {
30 
31  assert(this->TSM && "Module must not be null");
32 
33  MangleAndInterner Mangle(ES, this->TSM.getModuleUnlocked()->getDataLayout());
34  this->TSM.withModuleDo([&](Module &M) {
35  for (auto &G : M.global_values()) {
36  // Skip globals that don't generate symbols.
37  if (!G.hasName() || G.isDeclaration() || G.hasLocalLinkage() ||
38  G.hasAvailableExternallyLinkage() || G.hasAppendingLinkage())
39  continue;
40 
41  // thread locals generate different symbols depending on whether or not
42  // emulated TLS is enabled.
43  if (G.isThreadLocal() && MO.EmulatedTLS) {
44  auto &GV = cast<GlobalVariable>(G);
45 
46  auto Flags = JITSymbolFlags::fromGlobalValue(GV);
47 
48  auto EmuTLSV = Mangle(("__emutls_v." + GV.getName()).str());
49  SymbolFlags[EmuTLSV] = Flags;
50  SymbolToDefinition[EmuTLSV] = &GV;
51 
52  // If this GV has a non-zero initializer we'll need to emit an
53  // __emutls.t symbol too.
54  if (GV.hasInitializer()) {
55  const auto *InitVal = GV.getInitializer();
56 
57  // Skip zero-initializers.
58  if (isa<ConstantAggregateZero>(InitVal))
59  continue;
60  const auto *InitIntValue = dyn_cast<ConstantInt>(InitVal);
61  if (InitIntValue && InitIntValue->isZero())
62  continue;
63 
64  auto EmuTLST = Mangle(("__emutls_t." + GV.getName()).str());
65  SymbolFlags[EmuTLST] = Flags;
66  }
67  continue;
68  }
69 
70  // Otherwise we just need a normal linker mangling.
71  auto MangledName = Mangle(G.getName());
73  SymbolToDefinition[MangledName] = &G;
74  }
75  });
76 }
77 
81  : MaterializationUnit(std::move(SymbolFlags), std::move(K)),
82  TSM(std::move(TSM)), SymbolToDefinition(std::move(SymbolToDefinition)) {}
83 
85  if (TSM)
86  return TSM.withModuleDo(
87  [](const Module &M) -> StringRef { return M.getModuleIdentifier(); });
88  return "<null module>";
89 }
90 
91 void IRMaterializationUnit::discard(const JITDylib &JD,
92  const SymbolStringPtr &Name) {
94  dbgs() << "In " << JD.getName() << " discarding " << *Name << " from MU@"
95  << this << " (" << getName() << ")\n";
96  }););
97 
98  auto I = SymbolToDefinition.find(Name);
99  assert(I != SymbolToDefinition.end() &&
100  "Symbol not provided by this MU, or previously discarded");
101  assert(!I->second->isDeclaration() &&
102  "Discard should only apply to definitions");
103  I->second->setLinkage(GlobalValue::AvailableExternallyLinkage);
104  SymbolToDefinition.erase(I);
105 }
106 
109  : IRMaterializationUnit(L.getExecutionSession(), MO, std::move(TSM),
110  std::move(K)),
111  L(L), K(std::move(K)) {}
112 
113 void BasicIRLayerMaterializationUnit::materialize(
115 
116  // Throw away the SymbolToDefinition map: it's not usable after we hand
117  // off the module.
118  SymbolToDefinition.clear();
119 
120  // If cloneToNewContextOnEmit is set, clone the module now.
123 
124 #ifndef NDEBUG
125  auto &ES = R.getTargetJITDylib().getExecutionSession();
126  auto &N = R.getTargetJITDylib().getName();
127 #endif // NDEBUG
128 
129  LLVM_DEBUG(ES.runSessionLocked(
130  [&]() { dbgs() << "Emitting, for " << N << ", " << *this << "\n"; }););
131  L.emit(std::move(R), std::move(TSM));
132  LLVM_DEBUG(ES.runSessionLocked([&]() {
133  dbgs() << "Finished emitting, for " << N << ", " << *this << "\n";
134  }););
135 }
136 
138 
140 
141 Error ObjectLayer::add(JITDylib &JD, std::unique_ptr<MemoryBuffer> O,
142  VModuleKey K) {
143  auto ObjMU = BasicObjectLayerMaterializationUnit::Create(*this, std::move(K),
144  std::move(O));
145  if (!ObjMU)
146  return ObjMU.takeError();
147  return JD.define(std::move(*ObjMU));
148 }
149 
152  std::unique_ptr<MemoryBuffer> O) {
153  auto SymbolFlags =
154  getObjectSymbolFlags(L.getExecutionSession(), O->getMemBufferRef());
155 
156  if (!SymbolFlags)
157  return SymbolFlags.takeError();
158 
159  return std::unique_ptr<BasicObjectLayerMaterializationUnit>(
160  new BasicObjectLayerMaterializationUnit(L, K, std::move(O),
161  std::move(*SymbolFlags)));
162 }
163 
165  ObjectLayer &L, VModuleKey K, std::unique_ptr<MemoryBuffer> O,
167  : MaterializationUnit(std::move(SymbolFlags), std::move(K)), L(L),
168  O(std::move(O)) {}
169 
171  if (O)
172  return O->getBufferIdentifier();
173  return "<null object>";
174 }
175 
176 void BasicObjectLayerMaterializationUnit::materialize(
178  L.emit(std::move(R), std::move(O));
179 }
180 
181 void BasicObjectLayerMaterializationUnit::discard(const JITDylib &JD,
182  const SymbolStringPtr &Name) {
183  // FIXME: Support object file level discard. This could be done by building a
184  // filter to pass to the object layer along with the object itself.
185 }
186 
188  MemoryBufferRef ObjBuffer) {
189  auto Obj = object::ObjectFile::createObjectFile(ObjBuffer);
190 
191  if (!Obj)
192  return Obj.takeError();
193 
195  for (auto &Sym : (*Obj)->symbols()) {
196  // Skip symbols not defined in this object file.
197  if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
198  continue;
199 
200  // Skip symbols that are not global.
201  if (!(Sym.getFlags() & object::BasicSymbolRef::SF_Global))
202  continue;
203 
204  auto Name = Sym.getName();
205  if (!Name)
206  return Name.takeError();
207  auto InternedName = ES.intern(*Name);
208  auto SymFlags = JITSymbolFlags::fromObjectSymbol(Sym);
209  if (!SymFlags)
210  return SymFlags.takeError();
211  SymbolFlags[InternedName] = std::move(*SymFlags);
212  }
213 
214  return SymbolFlags;
215 }
216 
217 } // End namespace orc.
218 } // End namespace llvm.
bool getCloneToNewContextOnEmit() const
Returns the current value of the CloneToNewContextOnEmit flag.
Definition: Layer.h:94
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:175
static JITSymbolFlags fromGlobalValue(const GlobalValue &GV)
Construct a JITSymbolFlags value based on the flags of the given global value.
Definition: JITSymbol.cpp:21
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
StringRef getName() const override
Return the ModuleIdentifier as the name for this MaterializationUnit.
Definition: Layer.cpp:84
SymbolNameToDefinitionMap SymbolToDefinition
Definition: Layer.h:57
Available for inspection, not emission.
Definition: GlobalValue.h:49
auto withModuleDo(Func &&F) -> decltype(F(std::declval< Module &>()))
Locks the associated ThreadSafeContext and calls the given function on the contained Module...
static Expected< JITSymbolFlags > fromObjectSymbol(const object::SymbolRef &Symbol)
Construct a JITSymbolFlags value based on the flags of the given libobject symbol.
Definition: JITSymbol.cpp:40
StringRef getName() const override
Return the buffer&#39;s identifier as the name for this MaterializationUnit.
Definition: Layer.cpp:170
Materializes the given object file (represented by a MemoryBuffer instance) by calling &#39;emit&#39; on the ...
Definition: Layer.h:149
Definition: BitVector.h:937
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1076
BasicObjectLayerMaterializationUnit(ObjectLayer &L, VModuleKey K, std::unique_ptr< MemoryBuffer > O, SymbolFlagsMap SymbolFlags)
Definition: Layer.cpp:164
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
SymbolFlagsMap SymbolFlags
Definition: Core.h:580
Error define(std::unique_ptr< MaterializationUnitType > &&MU)
Define all symbols provided by the materialization unit to be part of this JITDylib.
Definition: Core.h:1253
SymbolFlags
Symbol flags.
Definition: Symbol.h:25
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition: Core.h:1310
std::map< SymbolStringPtr, GlobalValue * > SymbolNameToDefinitionMap
Definition: Layer.h:34
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
virtual Error add(JITDylib &JD, ThreadSafeModule TSM, VModuleKey K=VModuleKey())
Adds a MaterializationUnit representing the given IR to the given JITDylib.
Definition: Layer.cpp:21
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:434
IRMaterializationUnit is a convenient base class for MaterializationUnits wrapping LLVM IR...
Definition: Layer.h:28
ExecutionSession & getExecutionSession()
Returns the execution session for this layer.
Definition: Layer.h:132
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition: Core.h:448
const IRMaterializationUnit::ManglingOptions *& getManglingOptions() const
Get the mangling options for this layer.
Definition: Layer.h:76
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:808
Pointer to a pooled string representing a symbol name.
virtual void emit(MaterializationResponsibility R, ThreadSafeModule TSM)=0
Emit should materialize the given IR.
ThreadSafeModule TSM
Definition: Layer.h:56
Expected< SymbolFlagsMap > getObjectSymbolFlags(ExecutionSession &ES, MemoryBufferRef ObjBuffer)
Returns a SymbolFlagsMap for the object file represented by the given buffer, or an error if the buff...
Definition: Layer.cpp:187
ObjectLayer(ExecutionSession &ES)
Definition: Layer.cpp:137
This file contains the declarations for the subclasses of Constant, which represent the different fla...
IRMaterializationUnit(ExecutionSession &ES, const ManglingOptions &MO, ThreadSafeModule TSM, VModuleKey K)
Create an IRMaterializationLayer.
Definition: Layer.cpp:26
An LLVM Module together with a shared ThreadSafeContext.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:211
virtual void emit(MaterializationResponsibility R, std::unique_ptr< MemoryBuffer > O)=0
Emit should materialize the given IR.
virtual Error add(JITDylib &JD, std::unique_ptr< MemoryBuffer > O, VModuleKey K=VModuleKey())
Adds a MaterializationUnit representing the given IR to the given JITDylib.
Definition: Layer.cpp:141
Interface for layers that accept LLVM IR.
Definition: Layer.h:64
A MaterializationUnit represents a set of symbol definitions that can be materialized as a group...
Definition: Core.h:550
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
An ExecutionSession represents a running JIT program.
Definition: Core.h:1058
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Module * getModuleUnlocked()
Get a raw pointer to the contained module without locking the context.
static Expected< std::unique_ptr< BasicObjectLayerMaterializationUnit > > Create(ObjectLayer &L, VModuleKey K, std::unique_ptr< MemoryBuffer > O)
Definition: Layer.cpp:151
uint8_t uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:42
BasicIRLayerMaterializationUnit(IRLayer &L, const ManglingOptions &MO, ThreadSafeModule TSM, VModuleKey K)
Definition: Layer.cpp:107
auto runSessionLocked(Func &&F) -> decltype(F())
Run the given lambda with the session mutex locked.
Definition: Core.h:1082
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
const std::string & getName() const
Get the name for this JITDylib.
Definition: Core.h:805
ThreadSafeModule cloneToNewContext(ThreadSafeModule &TSMW, GVPredicate ShouldCloneDef=GVPredicate(), GVModifier UpdateClonedDefSource=GVModifier())
Clones the given module on to a new context.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
virtual ~ObjectLayer()
Definition: Layer.cpp:139
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
virtual ~IRLayer()
Definition: Layer.cpp:19
Interface for Layers that accept object files.
Definition: Layer.h:126
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
#define LLVM_DEBUG(X)
Definition: Debug.h:122
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:774
iterator_range< global_value_iterator > global_values()
Definition: Module.cpp:392