blob: 241eb3600da748463aa8c7e461240153e581740e [file] [log] [blame]
Lang Hames68c9b8d2018-06-18 18:01:43 +00001//===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
11#include "llvm/IR/Mangler.h"
12#include "llvm/IR/Module.h"
Lang Hames68c9b8d2018-06-18 18:01:43 +000013
14using namespace llvm;
15using namespace llvm::orc;
16
Lang Hames98440292018-09-29 23:49:57 +000017static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,
18 StringRef Suffix,
19 GVPredicate ShouldExtract) {
Lang Hames6a941342018-06-26 21:35:48 +000020
Lang Hames98440292018-09-29 23:49:57 +000021 auto DeleteExtractedDefs = [](GlobalValue &GV) {
22 // Bump the linkage: this global will be provided by the external module.
23 GV.setLinkage(GlobalValue::ExternalLinkage);
Lang Hames6a941342018-06-26 21:35:48 +000024
Lang Hames98440292018-09-29 23:49:57 +000025 // Delete the definition in the source module.
Lang Hames8d76c712018-09-26 01:24:12 +000026 if (isa<Function>(GV)) {
27 auto &F = cast<Function>(GV);
28 F.deleteBody();
29 F.setPersonalityFn(nullptr);
30 } else if (isa<GlobalVariable>(GV)) {
31 cast<GlobalVariable>(GV).setInitializer(nullptr);
Lang Hames98440292018-09-29 23:49:57 +000032 } else if (isa<GlobalAlias>(GV)) {
33 // We need to turn deleted aliases into function or variable decls based
34 // on the type of their aliasee.
35 auto &A = cast<GlobalAlias>(GV);
36 Constant *Aliasee = A.getAliasee();
37 assert(A.hasName() && "Anonymous alias?");
38 assert(Aliasee->hasName() && "Anonymous aliasee");
39 std::string AliasName = A.getName();
40
41 if (isa<Function>(Aliasee)) {
42 auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));
43 A.replaceAllUsesWith(F);
44 A.eraseFromParent();
45 F->setName(AliasName);
46 } else if (isa<GlobalVariable>(Aliasee)) {
47 auto *G = cloneGlobalVariableDecl(*A.getParent(),
48 *cast<GlobalVariable>(Aliasee));
49 A.replaceAllUsesWith(G);
50 A.eraseFromParent();
51 G->setName(AliasName);
52 } else
53 llvm_unreachable("Alias to unsupported type");
Lang Hames8d76c712018-09-26 01:24:12 +000054 } else
55 llvm_unreachable("Unsupported global type");
Lang Hames8d76c712018-09-26 01:24:12 +000056 };
Lang Hames68c9b8d2018-06-18 18:01:43 +000057
Lang Hames98440292018-09-29 23:49:57 +000058 auto NewTSMod = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);
Lang Hames8d76c712018-09-26 01:24:12 +000059 auto &M = *NewTSMod.getModule();
60 M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());
Lang Hames68c9b8d2018-06-18 18:01:43 +000061
Lang Hames8d76c712018-09-26 01:24:12 +000062 return NewTSMod;
Lang Hames7bd89702018-07-05 19:01:27 +000063}
64
Lang Hames68c9b8d2018-06-18 18:01:43 +000065namespace llvm {
66namespace orc {
67
Lang Hames98440292018-09-29 23:49:57 +000068class PartitioningIRMaterializationUnit : public IRMaterializationUnit {
Lang Hames68c9b8d2018-06-18 18:01:43 +000069public:
Lang Hames98440292018-09-29 23:49:57 +000070 PartitioningIRMaterializationUnit(ExecutionSession &ES, ThreadSafeModule TSM,
Lang Hames8b942742018-10-16 20:13:06 +000071 VModuleKey K, CompileOnDemandLayer &Parent)
72 : IRMaterializationUnit(ES, std::move(TSM), std::move(K)),
73 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000074
Lang Hames98440292018-09-29 23:49:57 +000075 PartitioningIRMaterializationUnit(
76 ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags,
77 SymbolNameToDefinitionMap SymbolToDefinition,
Lang Hames079df9a2018-10-15 22:56:10 +000078 CompileOnDemandLayer &Parent)
Lang Hames8b942742018-10-16 20:13:06 +000079 : IRMaterializationUnit(std::move(TSM), std::move(K),
80 std::move(SymbolFlags),
Lang Hames68c9b8d2018-06-18 18:01:43 +000081 std::move(SymbolToDefinition)),
Lang Hamesfd0c1e712018-07-20 18:31:50 +000082 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000083
84private:
85 void materialize(MaterializationResponsibility R) override {
Lang Hames98440292018-09-29 23:49:57 +000086 Parent.emitPartition(std::move(R), std::move(TSM),
87 std::move(SymbolToDefinition));
Lang Hames68c9b8d2018-06-18 18:01:43 +000088 }
89
Lang Hamescb5702c32018-10-06 23:02:06 +000090 void discard(const JITDylib &V, const SymbolStringPtr &Name) override {
Lang Hames68c9b8d2018-06-18 18:01:43 +000091 // All original symbols were materialized by the CODLayer and should be
92 // final. The function bodies provided by M should never be overridden.
93 llvm_unreachable("Discard should never be called on an "
94 "ExtractingIRMaterializationUnit");
95 }
96
Lang Hames7bd89702018-07-05 19:01:27 +000097 mutable std::mutex SourceModuleMutex;
Lang Hames079df9a2018-10-15 22:56:10 +000098 CompileOnDemandLayer &Parent;
Lang Hames68c9b8d2018-06-18 18:01:43 +000099};
100
Lang Hames079df9a2018-10-15 22:56:10 +0000101Optional<CompileOnDemandLayer::GlobalValueSet>
102CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {
Lang Hames98440292018-09-29 23:49:57 +0000103 return std::move(Requested);
104}
105
Lang Hames079df9a2018-10-15 22:56:10 +0000106Optional<CompileOnDemandLayer::GlobalValueSet>
107CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {
Lang Hames98440292018-09-29 23:49:57 +0000108 return None;
109}
110
Lang Hames079df9a2018-10-15 22:56:10 +0000111CompileOnDemandLayer::CompileOnDemandLayer(
Lang Hamesd8048672018-09-26 05:08:29 +0000112 ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,
Lang Hames8d76c712018-09-26 01:24:12 +0000113 IndirectStubsManagerBuilder BuildIndirectStubsManager)
Lang Hamesd8048672018-09-26 05:08:29 +0000114 : IRLayer(ES), BaseLayer(BaseLayer), LCTMgr(LCTMgr),
Lang Hames8d76c712018-09-26 01:24:12 +0000115 BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +0000116
Lang Hames079df9a2018-10-15 22:56:10 +0000117void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000118 this->Partition = std::move(Partition);
Lang Hames68c9b8d2018-06-18 18:01:43 +0000119}
120
Lang Hames8b942742018-10-16 20:13:06 +0000121void CompileOnDemandLayer::emit(MaterializationResponsibility R,
122 ThreadSafeModule TSM) {
Lang Hames98440292018-09-29 23:49:57 +0000123 assert(TSM.getModule() && "Null module");
124
Lang Hames68c9b8d2018-06-18 18:01:43 +0000125 auto &ES = getExecutionSession();
Lang Hames8d76c712018-09-26 01:24:12 +0000126 auto &M = *TSM.getModule();
Lang Hames68c9b8d2018-06-18 18:01:43 +0000127
Lang Hames98440292018-09-29 23:49:57 +0000128 // First, do some cleanup on the module:
129 cleanUpModule(M);
130
131 // Now sort the callables and non-callables, build re-exports and lodge the
132 // actual module with the implementation dylib.
133 auto &PDR = getPerDylibResources(R.getTargetJITDylib());
Lang Hames68c9b8d2018-06-18 18:01:43 +0000134
Lang Hames8d76c712018-09-26 01:24:12 +0000135 MangleAndInterner Mangle(ES, M.getDataLayout());
Lang Hames98440292018-09-29 23:49:57 +0000136 SymbolAliasMap NonCallables;
137 SymbolAliasMap Callables;
138 for (auto &GV : M.global_values()) {
Lang Hamesbf6603e2018-10-09 20:44:32 +0000139 if (GV.isDeclaration() || GV.hasLocalLinkage() || GV.hasAppendingLinkage())
Lang Hames68c9b8d2018-06-18 18:01:43 +0000140 continue;
141
Lang Hames98440292018-09-29 23:49:57 +0000142 auto Name = Mangle(GV.getName());
143 auto Flags = JITSymbolFlags::fromGlobalValue(GV);
144 if (Flags.isCallable())
145 Callables[Name] = SymbolAliasMapEntry(Name, Flags);
146 else
147 NonCallables[Name] = SymbolAliasMapEntry(Name, Flags);
Lang Hames68c9b8d2018-06-18 18:01:43 +0000148 }
149
Lang Hames98440292018-09-29 23:49:57 +0000150 // Create a partitioning materialization unit and lodge it with the
151 // implementation dylib.
152 if (auto Err = PDR.getImplDylib().define(
153 llvm::make_unique<PartitioningIRMaterializationUnit>(
Lang Hames8b942742018-10-16 20:13:06 +0000154 ES, std::move(TSM), R.getVModuleKey(), *this))) {
Lang Hames68c9b8d2018-06-18 18:01:43 +0000155 ES.reportError(std::move(Err));
156 R.failMaterialization();
157 return;
158 }
159
Lang Hames23cb2e72018-10-23 23:01:39 +0000160 R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables), true));
Lang Hames98440292018-09-29 23:49:57 +0000161 R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(),
162 std::move(Callables)));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000163}
164
Lang Hames079df9a2018-10-15 22:56:10 +0000165CompileOnDemandLayer::PerDylibResources &
166CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {
Lang Hamesd8048672018-09-26 05:08:29 +0000167 auto I = DylibResources.find(&TargetD);
168 if (I == DylibResources.end()) {
Lang Hames23cb2e72018-10-23 23:01:39 +0000169 auto &ImplD = getExecutionSession().createJITDylib(
170 TargetD.getName() + ".impl", false);
171 TargetD.withSearchOrderDo([&](const JITDylibSearchList &TargetSearchOrder) {
172 auto NewSearchOrder = TargetSearchOrder;
173 assert(!NewSearchOrder.empty() &&
174 NewSearchOrder.front().first == &TargetD &&
175 NewSearchOrder.front().second == true &&
176 "TargetD must be at the front of its own search order and match "
177 "non-exported symbol");
178 NewSearchOrder.insert(std::next(NewSearchOrder.begin()), {&ImplD, true});
179 ImplD.setSearchOrder(std::move(NewSearchOrder), false);
Lang Hamesd8048672018-09-26 05:08:29 +0000180 });
181 PerDylibResources PDR(ImplD, BuildIndirectStubsManager());
182 I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first;
183 }
184
185 return I->second;
Lang Hames68c9b8d2018-06-18 18:01:43 +0000186}
187
Lang Hames079df9a2018-10-15 22:56:10 +0000188void CompileOnDemandLayer::cleanUpModule(Module &M) {
Lang Hames98440292018-09-29 23:49:57 +0000189 for (auto &F : M.functions()) {
190 if (F.isDeclaration())
191 continue;
192
193 if (F.hasAvailableExternallyLinkage()) {
194 F.deleteBody();
195 F.setPersonalityFn(nullptr);
196 continue;
197 }
198 }
199}
200
Lang Hames079df9a2018-10-15 22:56:10 +0000201void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000202 // Expands the partition to ensure the following rules hold:
203 // (1) If any alias is in the partition, its aliasee is also in the partition.
204 // (2) If any aliasee is in the partition, its aliases are also in the
205 // partiton.
206 // (3) If any global variable is in the partition then all global variables
207 // are in the partition.
208 assert(!Partition.empty() && "Unexpected empty partition");
209
210 const Module &M = *(*Partition.begin())->getParent();
211 bool ContainsGlobalVariables = false;
212 std::vector<const GlobalValue *> GVsToAdd;
213
214 for (auto *GV : Partition)
215 if (isa<GlobalAlias>(GV))
216 GVsToAdd.push_back(
217 cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));
218 else if (isa<GlobalVariable>(GV))
219 ContainsGlobalVariables = true;
220
221 for (auto &A : M.aliases())
222 if (Partition.count(cast<GlobalValue>(A.getAliasee())))
223 GVsToAdd.push_back(&A);
224
225 if (ContainsGlobalVariables)
226 for (auto &G : M.globals())
227 GVsToAdd.push_back(&G);
228
229 for (auto *GV : GVsToAdd)
230 Partition.insert(GV);
231}
232
Lang Hames079df9a2018-10-15 22:56:10 +0000233void CompileOnDemandLayer::emitPartition(
Lang Hames98440292018-09-29 23:49:57 +0000234 MaterializationResponsibility R, ThreadSafeModule TSM,
235 IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {
236
237 // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the
238 // extracted module key, extracted module, and source module key
239 // together. This could be used, for example, to provide a specific
240 // memory manager instance to the linking layer.
241
242 auto &ES = getExecutionSession();
243
244 GlobalValueSet RequestedGVs;
245 for (auto &Name : R.getRequestedSymbols()) {
246 assert(Defs.count(Name) && "No definition for symbol");
247 RequestedGVs.insert(Defs[Name]);
248 }
249
250 auto GVsToExtract = Partition(RequestedGVs);
251
252 // Take a 'None' partition to mean the whole module (as opposed to an empty
253 // partition, which means "materialize nothing"). Emit the whole module
254 // unmodified to the base layer.
255 if (GVsToExtract == None) {
256 Defs.clear();
Lang Hames8b942742018-10-16 20:13:06 +0000257 BaseLayer.emit(std::move(R), std::move(TSM));
Lang Hames98440292018-09-29 23:49:57 +0000258 return;
259 }
260
261 // If the partition is empty, return the whole module to the symbol table.
262 if (GVsToExtract->empty()) {
263 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
264 std::move(TSM), R.getSymbols(), std::move(Defs), *this));
265 return;
266 }
267
Lang Hamesbf6603e2018-10-09 20:44:32 +0000268 // Ok -- we actually need to partition the symbols. Promote the symbol
269 // linkages/names.
270 // FIXME: We apply this once per partitioning. It's safe, but overkill.
271 {
272 auto PromotedGlobals = PromoteSymbols(*TSM.getModule());
273 if (!PromotedGlobals.empty()) {
274 MangleAndInterner Mangle(ES, TSM.getModule()->getDataLayout());
275 SymbolFlagsMap SymbolFlags;
276 for (auto &GV : PromotedGlobals)
277 SymbolFlags[Mangle(GV->getName())] =
278 JITSymbolFlags::fromGlobalValue(*GV);
279 if (auto Err = R.defineMaterializing(SymbolFlags)) {
280 ES.reportError(std::move(Err));
281 R.failMaterialization();
282 return;
283 }
284 }
285 }
286
Lang Hames98440292018-09-29 23:49:57 +0000287 expandPartition(*GVsToExtract);
288
289 // Extract the requested partiton (plus any necessary aliases) and
290 // put the rest back into the impl dylib.
291 auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
292 return GVsToExtract->count(&GV);
293 };
294
295 auto ExtractedTSM = extractSubModule(TSM, ".submodule", ShouldExtract);
Lang Hames98440292018-09-29 23:49:57 +0000296 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
Lang Hames8b942742018-10-16 20:13:06 +0000297 ES, std::move(TSM), R.getVModuleKey(), *this));
Lang Hames98440292018-09-29 23:49:57 +0000298
Lang Hames8b942742018-10-16 20:13:06 +0000299 BaseLayer.emit(std::move(R), std::move(ExtractedTSM));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000300}
301
302} // end namespace orc
303} // end namespace llvm