LLVM  9.0.0svn
CompileOnDemandLayer.h
Go to the documentation of this file.
1 //===- CompileOnDemandLayer.h - Compile each function on demand -*- C++ -*-===//
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 //
9 // JIT layer for breaking up modules and inserting callbacks to allow
10 // individual functions to be compiled on demand.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
15 #define LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
16 
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/GlobalValue.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Mangler.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Support/Casting.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <functional>
48 #include <iterator>
49 #include <list>
50 #include <memory>
51 #include <set>
52 #include <string>
53 #include <utility>
54 #include <vector>
55 
56 namespace llvm {
57 
58 class Value;
59 
60 namespace orc {
61 
62 class ExtractingIRMaterializationUnit;
63 
64 class CompileOnDemandLayer : public IRLayer {
66 
67 public:
68  /// Builder for IndirectStubsManagers.
70  std::function<std::unique_ptr<IndirectStubsManager>()>;
71 
72  using GlobalValueSet = std::set<const GlobalValue *>;
73 
74  /// Partitioning function.
75  using PartitionFunction =
76  std::function<Optional<GlobalValueSet>(GlobalValueSet Requested)>;
77 
78  /// Off-the-shelf partitioning which compiles all requested symbols (usually
79  /// a single function at a time).
81 
82  /// Off-the-shelf partitioning which compiles whole modules whenever any
83  /// symbol in them is requested.
85 
86  /// Construct a CompileOnDemandLayer.
88  LazyCallThroughManager &LCTMgr,
89  IndirectStubsManagerBuilder BuildIndirectStubsManager);
90 
91  /// Sets the partition function.
93 
94  /// Emits the given module. This should not be called by clients: it will be
95  /// called by the JIT when a definition added via the add method is requested.
97 
98 private:
99  struct PerDylibResources {
100  public:
101  PerDylibResources(JITDylib &ImplD,
102  std::unique_ptr<IndirectStubsManager> ISMgr)
103  : ImplD(ImplD), ISMgr(std::move(ISMgr)) {}
104  JITDylib &getImplDylib() { return ImplD; }
105  IndirectStubsManager &getISManager() { return *ISMgr; }
106 
107  private:
108  JITDylib &ImplD;
109  std::unique_ptr<IndirectStubsManager> ISMgr;
110  };
111 
112  using PerDylibResourcesMap = std::map<const JITDylib *, PerDylibResources>;
113 
114  PerDylibResources &getPerDylibResources(JITDylib &TargetD);
115 
116  void cleanUpModule(Module &M);
117 
118  void expandPartition(GlobalValueSet &Partition);
119 
120  void emitPartition(MaterializationResponsibility R, ThreadSafeModule TSM,
122 
123  mutable std::mutex CODLayerMutex;
124 
125  IRLayer &BaseLayer;
126  LazyCallThroughManager &LCTMgr;
127  IndirectStubsManagerBuilder BuildIndirectStubsManager;
128  PerDylibResourcesMap DylibResources;
130  SymbolLinkagePromoter PromoteSymbols;
131 };
132 
133 /// Compile-on-demand layer.
134 ///
135 /// When a module is added to this layer a stub is created for each of its
136 /// function definitions. The stubs and other global values are immediately
137 /// added to the layer below. When a stub is called it triggers the extraction
138 /// of the function body from the original module. The extracted body is then
139 /// compiled and executed.
140 template <typename BaseLayerT,
141  typename CompileCallbackMgrT = JITCompileCallbackManager,
142  typename IndirectStubsMgrT = IndirectStubsManager>
144 private:
145  template <typename MaterializerFtor>
146  class LambdaMaterializer final : public ValueMaterializer {
147  public:
148  LambdaMaterializer(MaterializerFtor M) : M(std::move(M)) {}
149 
150  Value *materialize(Value *V) final { return M(V); }
151 
152  private:
153  MaterializerFtor M;
154  };
155 
156  template <typename MaterializerFtor>
157  LambdaMaterializer<MaterializerFtor>
158  createLambdaMaterializer(MaterializerFtor M) {
159  return LambdaMaterializer<MaterializerFtor>(std::move(M));
160  }
161 
162  // Provide type-erasure for the Modules and MemoryManagers.
163  template <typename ResourceT>
164  class ResourceOwner {
165  public:
166  ResourceOwner() = default;
167  ResourceOwner(const ResourceOwner &) = delete;
168  ResourceOwner &operator=(const ResourceOwner &) = delete;
169  virtual ~ResourceOwner() = default;
170 
171  virtual ResourceT& getResource() const = 0;
172  };
173 
174  template <typename ResourceT, typename ResourcePtrT>
175  class ResourceOwnerImpl : public ResourceOwner<ResourceT> {
176  public:
177  ResourceOwnerImpl(ResourcePtrT ResourcePtr)
178  : ResourcePtr(std::move(ResourcePtr)) {}
179 
180  ResourceT& getResource() const override { return *ResourcePtr; }
181 
182  private:
183  ResourcePtrT ResourcePtr;
184  };
185 
186  template <typename ResourceT, typename ResourcePtrT>
187  std::unique_ptr<ResourceOwner<ResourceT>>
188  wrapOwnership(ResourcePtrT ResourcePtr) {
189  using RO = ResourceOwnerImpl<ResourceT, ResourcePtrT>;
190  return llvm::make_unique<RO>(std::move(ResourcePtr));
191  }
192 
193  struct LogicalDylib {
195  std::unique_ptr<Module> SourceMod;
196  std::set<Function*> StubsToClone;
197  };
198 
199  using SourceModulesList = std::vector<SourceModuleEntry>;
200  using SourceModuleHandle = typename SourceModulesList::size_type;
201 
202  LogicalDylib() = default;
203 
204  LogicalDylib(VModuleKey K, std::shared_ptr<SymbolResolver> BackingResolver,
205  std::unique_ptr<IndirectStubsMgrT> StubsMgr)
206  : K(std::move(K)), BackingResolver(std::move(BackingResolver)),
207  StubsMgr(std::move(StubsMgr)) {}
208 
209  SourceModuleHandle addSourceModule(std::unique_ptr<Module> M) {
210  SourceModuleHandle H = SourceModules.size();
211  SourceModules.push_back(SourceModuleEntry());
212  SourceModules.back().SourceMod = std::move(M);
213  return H;
214  }
215 
216  Module& getSourceModule(SourceModuleHandle H) {
217  return *SourceModules[H].SourceMod;
218  }
219 
220  std::set<Function*>& getStubsToClone(SourceModuleHandle H) {
221  return SourceModules[H].StubsToClone;
222  }
223 
224  JITSymbol findSymbol(BaseLayerT &BaseLayer, const std::string &Name,
225  bool ExportedSymbolsOnly) {
226  if (auto Sym = StubsMgr->findStub(Name, ExportedSymbolsOnly))
227  return Sym;
228  for (auto BLK : BaseLayerVModuleKeys)
229  if (auto Sym = BaseLayer.findSymbolIn(BLK, Name, ExportedSymbolsOnly))
230  return Sym;
231  else if (auto Err = Sym.takeError())
232  return std::move(Err);
233  return nullptr;
234  }
235 
236  Error removeModulesFromBaseLayer(BaseLayerT &BaseLayer) {
237  for (auto &BLK : BaseLayerVModuleKeys)
238  if (auto Err = BaseLayer.removeModule(BLK))
239  return Err;
240  return Error::success();
241  }
242 
243  VModuleKey K;
244  std::shared_ptr<SymbolResolver> BackingResolver;
245  std::unique_ptr<IndirectStubsMgrT> StubsMgr;
246  SymbolLinkagePromoter PromoteSymbols;
247  SourceModulesList SourceModules;
248  std::vector<VModuleKey> BaseLayerVModuleKeys;
249  };
250 
251 public:
252 
253  /// Module partitioning functor.
254  using PartitioningFtor = std::function<std::set<Function*>(Function&)>;
255 
256  /// Builder for IndirectStubsManagers.
258  std::function<std::unique_ptr<IndirectStubsMgrT>()>;
259 
260  using SymbolResolverGetter =
261  std::function<std::shared_ptr<SymbolResolver>(VModuleKey K)>;
262 
263  using SymbolResolverSetter =
264  std::function<void(VModuleKey K, std::shared_ptr<SymbolResolver> R)>;
265 
266  /// Construct a compile-on-demand layer instance.
267  LegacyCompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer,
268  SymbolResolverGetter GetSymbolResolver,
269  SymbolResolverSetter SetSymbolResolver,
270  PartitioningFtor Partition,
271  CompileCallbackMgrT &CallbackMgr,
272  IndirectStubsManagerBuilderT CreateIndirectStubsManager,
273  bool CloneStubsIntoPartitions = true)
274  : ES(ES), BaseLayer(BaseLayer),
275  GetSymbolResolver(std::move(GetSymbolResolver)),
276  SetSymbolResolver(std::move(SetSymbolResolver)),
277  Partition(std::move(Partition)), CompileCallbackMgr(CallbackMgr),
278  CreateIndirectStubsManager(std::move(CreateIndirectStubsManager)),
279  CloneStubsIntoPartitions(CloneStubsIntoPartitions) {}
280 
282  // FIXME: Report error on log.
283  while (!LogicalDylibs.empty())
284  consumeError(removeModule(LogicalDylibs.begin()->first));
285  }
286 
287  /// Add a module to the compile-on-demand layer.
288  Error addModule(VModuleKey K, std::unique_ptr<Module> M) {
289 
290  assert(!LogicalDylibs.count(K) && "VModuleKey K already in use");
291  auto I = LogicalDylibs.insert(
292  LogicalDylibs.end(),
293  std::make_pair(K, LogicalDylib(K, GetSymbolResolver(K),
294  CreateIndirectStubsManager())));
295 
296  return addLogicalModule(I->second, std::move(M));
297  }
298 
299  /// Add extra modules to an existing logical module.
300  Error addExtraModule(VModuleKey K, std::unique_ptr<Module> M) {
301  return addLogicalModule(LogicalDylibs[K], std::move(M));
302  }
303 
304  /// Remove the module represented by the given key.
305  ///
306  /// This will remove all modules in the layers below that were derived from
307  /// the module represented by K.
309  auto I = LogicalDylibs.find(K);
310  assert(I != LogicalDylibs.end() && "VModuleKey K not valid here");
311  auto Err = I->second.removeModulesFromBaseLayer(BaseLayer);
312  LogicalDylibs.erase(I);
313  return Err;
314  }
315 
316  /// Search for the given named symbol.
317  /// @param Name The name of the symbol to search for.
318  /// @param ExportedSymbolsOnly If true, search only for exported symbols.
319  /// @return A handle for the given named symbol, if it exists.
320  JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly) {
321  for (auto &KV : LogicalDylibs) {
322  if (auto Sym = KV.second.StubsMgr->findStub(Name, ExportedSymbolsOnly))
323  return Sym;
324  if (auto Sym = findSymbolIn(KV.first, Name, ExportedSymbolsOnly))
325  return Sym;
326  else if (auto Err = Sym.takeError())
327  return std::move(Err);
328  }
329  return BaseLayer.findSymbol(Name, ExportedSymbolsOnly);
330  }
331 
332  /// Get the address of a symbol provided by this layer, or some layer
333  /// below this one.
334  JITSymbol findSymbolIn(VModuleKey K, const std::string &Name,
335  bool ExportedSymbolsOnly) {
336  assert(LogicalDylibs.count(K) && "VModuleKey K is not valid here");
337  return LogicalDylibs[K].findSymbol(BaseLayer, Name, ExportedSymbolsOnly);
338  }
339 
340  /// Update the stub for the given function to point at FnBodyAddr.
341  /// This can be used to support re-optimization.
342  /// @return true if the function exists and the stub is updated, false
343  /// otherwise.
344  //
345  // FIXME: We should track and free associated resources (unused compile
346  // callbacks, uncompiled IR, and no-longer-needed/reachable function
347  // implementations).
348  Error updatePointer(std::string FuncName, JITTargetAddress FnBodyAddr) {
349  //Find out which logical dylib contains our symbol
350  auto LDI = LogicalDylibs.begin();
351  for (auto LDE = LogicalDylibs.end(); LDI != LDE; ++LDI) {
352  if (auto LMResources =
353  LDI->getLogicalModuleResourcesForSymbol(FuncName, false)) {
354  Module &SrcM = LMResources->SourceModule->getResource();
355  std::string CalledFnName = mangle(FuncName, SrcM.getDataLayout());
356  if (auto Err = LMResources->StubsMgr->updatePointer(CalledFnName,
357  FnBodyAddr))
358  return Err;
359  return Error::success();
360  }
361  }
362  return make_error<JITSymbolNotFound>(FuncName);
363  }
364 
365 private:
366  Error addLogicalModule(LogicalDylib &LD, std::unique_ptr<Module> SrcMPtr) {
367 
368  // Rename anonymous globals and promote linkage to ensure that everything
369  // will resolve properly after we partition SrcM.
370  LD.PromoteSymbols(*SrcMPtr);
371 
372  // Create a logical module handle for SrcM within the logical dylib.
373  Module &SrcM = *SrcMPtr;
374  auto LMId = LD.addSourceModule(std::move(SrcMPtr));
375 
376  // Create stub functions.
377  const DataLayout &DL = SrcM.getDataLayout();
378  {
379  typename IndirectStubsMgrT::StubInitsMap StubInits;
380  for (auto &F : SrcM) {
381  // Skip declarations.
382  if (F.isDeclaration())
383  continue;
384 
385  // Skip weak functions for which we already have definitions.
386  auto MangledName = mangle(F.getName(), DL);
387  if (F.hasWeakLinkage() || F.hasLinkOnceLinkage()) {
388  if (auto Sym = LD.findSymbol(BaseLayer, MangledName, false))
389  continue;
390  else if (auto Err = Sym.takeError())
391  return std::move(Err);
392  }
393 
394  // Record all functions defined by this module.
395  if (CloneStubsIntoPartitions)
396  LD.getStubsToClone(LMId).insert(&F);
397 
398  // Create a callback, associate it with the stub for the function,
399  // and set the compile action to compile the partition containing the
400  // function.
401  auto CompileAction = [this, &LD, LMId, &F]() -> JITTargetAddress {
402  if (auto FnImplAddrOrErr = this->extractAndCompile(LD, LMId, F))
403  return *FnImplAddrOrErr;
404  else {
405  // FIXME: Report error, return to 'abort' or something similar.
406  consumeError(FnImplAddrOrErr.takeError());
407  return 0;
408  }
409  };
410  if (auto CCAddr =
411  CompileCallbackMgr.getCompileCallback(std::move(CompileAction)))
412  StubInits[MangledName] =
413  std::make_pair(*CCAddr, JITSymbolFlags::fromGlobalValue(F));
414  else
415  return CCAddr.takeError();
416  }
417 
418  if (auto Err = LD.StubsMgr->createStubs(StubInits))
419  return Err;
420  }
421 
422  // If this module doesn't contain any globals, aliases, or module flags then
423  // we can bail out early and avoid the overhead of creating and managing an
424  // empty globals module.
425  if (SrcM.global_empty() && SrcM.alias_empty() &&
426  !SrcM.getModuleFlagsMetadata())
427  return Error::success();
428 
429  // Create the GlobalValues module.
430  auto GVsM = llvm::make_unique<Module>((SrcM.getName() + ".globals").str(),
431  SrcM.getContext());
432  GVsM->setDataLayout(DL);
433 
434  ValueToValueMapTy VMap;
435 
436  // Clone global variable decls.
437  for (auto &GV : SrcM.globals())
438  if (!GV.isDeclaration() && !VMap.count(&GV))
439  cloneGlobalVariableDecl(*GVsM, GV, &VMap);
440 
441  // And the aliases.
442  for (auto &A : SrcM.aliases())
443  if (!VMap.count(&A))
444  cloneGlobalAliasDecl(*GVsM, A, VMap);
445 
446  // Clone the module flags.
447  cloneModuleFlagsMetadata(*GVsM, SrcM, VMap);
448 
449  // Now we need to clone the GV and alias initializers.
450 
451  // Initializers may refer to functions declared (but not defined) in this
452  // module. Build a materializer to clone decls on demand.
453  auto Materializer = createLambdaMaterializer(
454  [&LD, &GVsM](Value *V) -> Value* {
455  if (auto *F = dyn_cast<Function>(V)) {
456  // Decls in the original module just get cloned.
457  if (F->isDeclaration())
458  return cloneFunctionDecl(*GVsM, *F);
459 
460  // Definitions in the original module (which we have emitted stubs
461  // for at this point) get turned into a constant alias to the stub
462  // instead.
463  const DataLayout &DL = GVsM->getDataLayout();
464  std::string FName = mangle(F->getName(), DL);
465  unsigned PtrBitWidth = DL.getPointerTypeSizeInBits(F->getType());
466  JITTargetAddress StubAddr =
467  LD.StubsMgr->findStub(FName, false).getAddress();
468 
469  ConstantInt *StubAddrCI =
470  ConstantInt::get(GVsM->getContext(), APInt(PtrBitWidth, StubAddr));
471  Constant *Init = ConstantExpr::getCast(Instruction::IntToPtr,
472  StubAddrCI, F->getType());
473  return GlobalAlias::create(F->getFunctionType(),
474  F->getType()->getAddressSpace(),
475  F->getLinkage(), F->getName(),
476  Init, GVsM.get());
477  }
478  // else....
479  return nullptr;
480  });
481 
482  // Clone the global variable initializers.
483  for (auto &GV : SrcM.globals())
484  if (!GV.isDeclaration())
485  moveGlobalVariableInitializer(GV, VMap, &Materializer);
486 
487  // Clone the global alias initializers.
488  for (auto &A : SrcM.aliases()) {
489  auto *NewA = cast<GlobalAlias>(VMap[&A]);
490  assert(NewA && "Alias not cloned?");
491  Value *Init = MapValue(A.getAliasee(), VMap, RF_None, nullptr,
492  &Materializer);
493  NewA->setAliasee(cast<Constant>(Init));
494  }
495 
496  // Build a resolver for the globals module and add it to the base layer.
497  auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol {
498  if (auto Sym = LD.StubsMgr->findStub(Name, false))
499  return Sym;
500 
501  if (auto Sym = LD.findSymbol(BaseLayer, Name, false))
502  return Sym;
503  else if (auto Err = Sym.takeError())
504  return std::move(Err);
505 
506  return nullptr;
507  };
508 
509  auto GVsResolver = createSymbolResolver(
510  [&LD, LegacyLookup](const SymbolNameSet &Symbols) {
511  auto RS = getResponsibilitySetWithLegacyFn(Symbols, LegacyLookup);
512 
513  if (!RS) {
515  RS.takeError(), errs(),
516  "CODLayer/GVsResolver responsibility set lookup failed: ");
517  return SymbolNameSet();
518  }
519 
520  if (RS->size() == Symbols.size())
521  return *RS;
522 
523  SymbolNameSet NotFoundViaLegacyLookup;
524  for (auto &S : Symbols)
525  if (!RS->count(S))
526  NotFoundViaLegacyLookup.insert(S);
527  auto RS2 =
528  LD.BackingResolver->getResponsibilitySet(NotFoundViaLegacyLookup);
529 
530  for (auto &S : RS2)
531  (*RS).insert(S);
532 
533  return *RS;
534  },
535  [this, &LD,
536  LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Query,
537  SymbolNameSet Symbols) {
538  auto NotFoundViaLegacyLookup =
539  lookupWithLegacyFn(ES, *Query, Symbols, LegacyLookup);
540  return LD.BackingResolver->lookup(Query, NotFoundViaLegacyLookup);
541  });
542 
543  SetSymbolResolver(LD.K, std::move(GVsResolver));
544 
545  if (auto Err = BaseLayer.addModule(LD.K, std::move(GVsM)))
546  return Err;
547 
548  LD.BaseLayerVModuleKeys.push_back(LD.K);
549 
550  return Error::success();
551  }
552 
553  static std::string mangle(StringRef Name, const DataLayout &DL) {
554  std::string MangledName;
555  {
556  raw_string_ostream MangledNameStream(MangledName);
557  Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
558  }
559  return MangledName;
560  }
561 
563  extractAndCompile(LogicalDylib &LD,
564  typename LogicalDylib::SourceModuleHandle LMId,
565  Function &F) {
566  Module &SrcM = LD.getSourceModule(LMId);
567 
568  // If F is a declaration we must already have compiled it.
569  if (F.isDeclaration())
570  return 0;
571 
572  // Grab the name of the function being called here.
573  std::string CalledFnName = mangle(F.getName(), SrcM.getDataLayout());
574 
575  JITTargetAddress CalledAddr = 0;
576  auto Part = Partition(F);
577  if (auto PartKeyOrErr = emitPartition(LD, LMId, Part)) {
578  auto &PartKey = *PartKeyOrErr;
579  for (auto *SubF : Part) {
580  std::string FnName = mangle(SubF->getName(), SrcM.getDataLayout());
581  if (auto FnBodySym = BaseLayer.findSymbolIn(PartKey, FnName, false)) {
582  if (auto FnBodyAddrOrErr = FnBodySym.getAddress()) {
583  JITTargetAddress FnBodyAddr = *FnBodyAddrOrErr;
584 
585  // If this is the function we're calling record the address so we can
586  // return it from this function.
587  if (SubF == &F)
588  CalledAddr = FnBodyAddr;
589 
590  // Update the function body pointer for the stub.
591  if (auto EC = LD.StubsMgr->updatePointer(FnName, FnBodyAddr))
592  return 0;
593 
594  } else
595  return FnBodyAddrOrErr.takeError();
596  } else if (auto Err = FnBodySym.takeError())
597  return std::move(Err);
598  else
599  llvm_unreachable("Function not emitted for partition");
600  }
601 
602  LD.BaseLayerVModuleKeys.push_back(PartKey);
603  } else
604  return PartKeyOrErr.takeError();
605 
606  return CalledAddr;
607  }
608 
609  template <typename PartitionT>
611  emitPartition(LogicalDylib &LD,
612  typename LogicalDylib::SourceModuleHandle LMId,
613  const PartitionT &Part) {
614  Module &SrcM = LD.getSourceModule(LMId);
615 
616  // Create the module.
617  std::string NewName = SrcM.getName();
618  for (auto *F : Part) {
619  NewName += ".";
620  NewName += F->getName();
621  }
622 
623  auto M = llvm::make_unique<Module>(NewName, SrcM.getContext());
624  M->setDataLayout(SrcM.getDataLayout());
625  ValueToValueMapTy VMap;
626 
627  auto Materializer = createLambdaMaterializer([&LD, &LMId,
628  &M](Value *V) -> Value * {
629  if (auto *GV = dyn_cast<GlobalVariable>(V))
630  return cloneGlobalVariableDecl(*M, *GV);
631 
632  if (auto *F = dyn_cast<Function>(V)) {
633  // Check whether we want to clone an available_externally definition.
634  if (!LD.getStubsToClone(LMId).count(F))
635  return cloneFunctionDecl(*M, *F);
636 
637  // Ok - we want an inlinable stub. For that to work we need a decl
638  // for the stub pointer.
639  auto *StubPtr = createImplPointer(*F->getType(), *M,
640  F->getName() + "$stub_ptr", nullptr);
641  auto *ClonedF = cloneFunctionDecl(*M, *F);
642  makeStub(*ClonedF, *StubPtr);
643  ClonedF->setLinkage(GlobalValue::AvailableExternallyLinkage);
644  ClonedF->addFnAttr(Attribute::AlwaysInline);
645  return ClonedF;
646  }
647 
648  if (auto *A = dyn_cast<GlobalAlias>(V)) {
649  auto *Ty = A->getValueType();
650  if (Ty->isFunctionTy())
651  return Function::Create(cast<FunctionType>(Ty),
652  GlobalValue::ExternalLinkage, A->getName(),
653  M.get());
654 
655  return new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage,
656  nullptr, A->getName(), nullptr,
658  A->getType()->getAddressSpace());
659  }
660 
661  return nullptr;
662  });
663 
664  // Create decls in the new module.
665  for (auto *F : Part)
666  cloneFunctionDecl(*M, *F, &VMap);
667 
668  // Move the function bodies.
669  for (auto *F : Part)
670  moveFunctionBody(*F, VMap, &Materializer);
671 
672  auto K = ES.allocateVModule();
673 
674  auto LegacyLookup = [this, &LD](const std::string &Name) -> JITSymbol {
675  return LD.findSymbol(BaseLayer, Name, false);
676  };
677 
678  // Create memory manager and symbol resolver.
680  [&LD, LegacyLookup](const SymbolNameSet &Symbols) {
681  auto RS = getResponsibilitySetWithLegacyFn(Symbols, LegacyLookup);
682  if (!RS) {
684  RS.takeError(), errs(),
685  "CODLayer/SubResolver responsibility set lookup failed: ");
686  return SymbolNameSet();
687  }
688 
689  if (RS->size() == Symbols.size())
690  return *RS;
691 
692  SymbolNameSet NotFoundViaLegacyLookup;
693  for (auto &S : Symbols)
694  if (!RS->count(S))
695  NotFoundViaLegacyLookup.insert(S);
696 
697  auto RS2 =
698  LD.BackingResolver->getResponsibilitySet(NotFoundViaLegacyLookup);
699 
700  for (auto &S : RS2)
701  (*RS).insert(S);
702 
703  return *RS;
704  },
705  [this, &LD, LegacyLookup](std::shared_ptr<AsynchronousSymbolQuery> Q,
706  SymbolNameSet Symbols) {
707  auto NotFoundViaLegacyLookup =
708  lookupWithLegacyFn(ES, *Q, Symbols, LegacyLookup);
709  return LD.BackingResolver->lookup(Q,
710  std::move(NotFoundViaLegacyLookup));
711  });
712  SetSymbolResolver(K, std::move(Resolver));
713 
714  if (auto Err = BaseLayer.addModule(std::move(K), std::move(M)))
715  return std::move(Err);
716 
717  return K;
718  }
719 
720  ExecutionSession &ES;
721  BaseLayerT &BaseLayer;
722  SymbolResolverGetter GetSymbolResolver;
723  SymbolResolverSetter SetSymbolResolver;
724  PartitioningFtor Partition;
725  CompileCallbackMgrT &CompileCallbackMgr;
726  IndirectStubsManagerBuilderT CreateIndirectStubsManager;
727 
728  std::map<VModuleKey, LogicalDylib> LogicalDylibs;
729  bool CloneStubsIntoPartitions;
730 };
731 
732 } // end namespace orc
733 
734 } // end namespace llvm
735 
736 #endif // LLVM_EXECUTIONENGINE_ORC_COMPILEONDEMANDLAYER_H
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Base class for managing collections of named indirect stubs.
Error removeModule(VModuleKey K)
Remove the module represented by the given key.
static JITSymbolFlags fromGlobalValue(const GlobalValue &GV)
Construct a JITSymbolFlags value based on the flags of the given global value.
Definition: JITSymbol.cpp:21
Represents a symbol in the JIT.
Definition: JITSymbol.h:237
This class represents lattice values for constants.
Definition: AllocatorList.h:23
GlobalAlias * cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA, ValueToValueMapTy &VMap)
Clone a global alias declaration into a new module.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
static Optional< GlobalValueSet > compileRequested(GlobalValueSet Requested)
Off-the-shelf partitioning which compiles all requested symbols (usually a single function at a time)...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void cloneModuleFlagsMetadata(Module &Dst, const Module &Src, ValueToValueMapTy &VMap)
Clone module flags metadata into the destination module.
Available for inspection, not emission.
Definition: GlobalValue.h:49
bool global_empty() const
Definition: Module.h:585
Externally visible function.
Definition: GlobalValue.h:48
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:227
F(f)
uint64_t VModuleKey
VModuleKey provides a unique identifier (allocated and managed by ExecutionSessions) for a module add...
Definition: Core.h:39
Promotes private symbols to global hidden, and renames to prevent clashes with other promoted symbols...
std::function< std::unique_ptr< IndirectStubsManager >()> IndirectStubsManagerBuilder
Builder for IndirectStubsManagers.
Target-independent base class for compile callback management.
Definition: BitVector.h:937
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:665
std::unique_ptr< LambdaSymbolResolver< typename std::remove_cv< typename std::remove_reference< GetResponsibilitySetFn >::type >::type, typename std::remove_cv< typename std::remove_reference< LookupFn >::type >::type > > createSymbolResolver(GetResponsibilitySetFn &&GetResponsibilitySet, LookupFn &&Lookup)
Creates a SymbolResolver implementation from the pair of supplied function objects.
Definition: Legacy.h:80
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module...
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:244
std::function< Optional< GlobalValueSet >(GlobalValueSet Requested)> PartitionFunction
Partitioning function.
This file contains the simple types necessary to represent the attributes associated with functions a...
void moveGlobalVariableInitializer(GlobalVariable &OrigGV, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, GlobalVariable *NewGV=nullptr)
Move global variable GV from its parent module to cloned global declaration in a different module...
std::map< SymbolStringPtr, GlobalValue * > SymbolNameToDefinitionMap
Definition: Layer.h:68
JITSymbol findSymbolIn(VModuleKey K, const std::string &Name, bool ExportedSymbolsOnly)
Get the address of a symbol provided by this layer, or some layer below this one. ...
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
This file implements a class to represent arbitrary precision integral constant values and operations...
void makeStub(Function &F, Value &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:154
Error addModule(VModuleKey K, std::unique_ptr< Module > M)
Add a module to the compile-on-demand layer.
Expected< SymbolNameSet > getResponsibilitySetWithLegacyFn(const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
Definition: Legacy.h:117
Error updatePointer(std::string FuncName, JITTargetAddress FnBodyAddr)
Update the stub for the given function to point at FnBodyAddr.
uint64_t JITTargetAddress
Represents an address in the target process&#39;s address space.
Definition: JITSymbol.h:40
std::function< void(VModuleKey K, std::shared_ptr< SymbolResolver > R)> SymbolResolverSetter
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
bool alias_empty() const
Definition: Module.h:625
DenseSet< SymbolStringPtr > SymbolNameSet
A set of symbol names (represented by SymbolStringPtrs for.
Definition: Core.h:43
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:50
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
Definition: Module.cpp:290
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define H(x, y, z)
Definition: MD5.cpp:57
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1854
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
Error addExtraModule(VModuleKey K, std::unique_ptr< Module > M)
Add extra modules to an existing logical module.
SymbolNameSet lookupWithLegacyFn(ExecutionSession &ES, AsynchronousSymbolQuery &Query, const SymbolNameSet &Symbols, FindSymbolFn FindSymbol)
Use the given legacy-style FindSymbol function (i.e.
Definition: Legacy.h:143
std::function< std::shared_ptr< SymbolResolver >(VModuleKey K)> SymbolResolverGetter
An LLVM Module together with a shared ThreadSafeContext.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:981
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:61
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
Definition: ValueMapper.h:205
Interface for layers that accept LLVM IR.
Definition: Layer.h:25
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
Module.h This file contains the declarations for the Module class.
size_type size() const
Definition: DenseSet.h:75
static Optional< GlobalValueSet > compileWholeModule(GlobalValueSet Requested)
Off-the-shelf partitioning which compiles whole modules whenever any symbol in them is requested...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:631
An ExecutionSession represents a running JIT program.
Definition: Core.h:696
Class for arbitrary precision integers.
Definition: APInt.h:69
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1539
CompileOnDemandLayer(ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr, IndirectStubsManagerBuilder BuildIndirectStubsManager)
Construct a CompileOnDemandLayer.
std::function< std::set< Function * >(Function &)> PartitioningFtor
Module partitioning functor.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
void setPartitionFunction(PartitionFunction Partition)
Sets the partition function.
#define I(x, y, z)
Definition: MD5.cpp:58
JITSymbol findSymbol(StringRef Name, bool ExportedSymbolsOnly)
Search for the given named symbol.
LegacyCompileOnDemandLayer(ExecutionSession &ES, BaseLayerT &BaseLayer, SymbolResolverGetter GetSymbolResolver, SymbolResolverSetter SetSymbolResolver, PartitioningFtor Partition, CompileCallbackMgrT &CallbackMgr, IndirectStubsManagerBuilderT CreateIndirectStubsManager, bool CloneStubsIntoPartitions=true)
Construct a compile-on-demand layer instance.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:205
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: ValueMap.h:157
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
LLVM Value Representation.
Definition: Value.h:72
std::function< std::unique_ptr< IndirectStubsMgrT >()> IndirectStubsManagerBuilderT
Builder for IndirectStubsManagers.
Manages a set of &#39;lazy call-through&#39; trampolines.
Definition: LazyReexports.h:36
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:111
iterator_range< global_iterator > globals()
Definition: Module.h:587
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
void emit(MaterializationResponsibility R, ThreadSafeModule TSM) override
Emits the given module.
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function &#39;F&#39; to a cloned function declaration in a different module (See related clo...
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:422
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
std::set< const GlobalValue * > GlobalValueSet
A symbol table that supports asynchoronous symbol queries.
Definition: Core.h:495
iterator_range< alias_iterator > aliases()
Definition: Module.h:627