blob: 99bf53bc3afa88cb116eb4408de523490b6ccae5 [file] [log] [blame]
Lang Hames68c9b8d2018-06-18 18:01:43 +00001//===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Lang Hames68c9b8d2018-06-18 18:01:43 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h"
10#include "llvm/IR/Mangler.h"
11#include "llvm/IR/Module.h"
Lang Hames68c9b8d2018-06-18 18:01:43 +000012
13using namespace llvm;
14using namespace llvm::orc;
15
Lang Hames98440292018-09-29 23:49:57 +000016static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM,
17 StringRef Suffix,
18 GVPredicate ShouldExtract) {
Lang Hames6a941342018-06-26 21:35:48 +000019
Lang Hames98440292018-09-29 23:49:57 +000020 auto DeleteExtractedDefs = [](GlobalValue &GV) {
21 // Bump the linkage: this global will be provided by the external module.
22 GV.setLinkage(GlobalValue::ExternalLinkage);
Lang Hames6a941342018-06-26 21:35:48 +000023
Lang Hames98440292018-09-29 23:49:57 +000024 // Delete the definition in the source module.
Lang Hames8d76c712018-09-26 01:24:12 +000025 if (isa<Function>(GV)) {
26 auto &F = cast<Function>(GV);
27 F.deleteBody();
28 F.setPersonalityFn(nullptr);
29 } else if (isa<GlobalVariable>(GV)) {
30 cast<GlobalVariable>(GV).setInitializer(nullptr);
Lang Hames98440292018-09-29 23:49:57 +000031 } else if (isa<GlobalAlias>(GV)) {
32 // We need to turn deleted aliases into function or variable decls based
33 // on the type of their aliasee.
34 auto &A = cast<GlobalAlias>(GV);
35 Constant *Aliasee = A.getAliasee();
36 assert(A.hasName() && "Anonymous alias?");
37 assert(Aliasee->hasName() && "Anonymous aliasee");
38 std::string AliasName = A.getName();
39
40 if (isa<Function>(Aliasee)) {
41 auto *F = cloneFunctionDecl(*A.getParent(), *cast<Function>(Aliasee));
42 A.replaceAllUsesWith(F);
43 A.eraseFromParent();
44 F->setName(AliasName);
45 } else if (isa<GlobalVariable>(Aliasee)) {
46 auto *G = cloneGlobalVariableDecl(*A.getParent(),
47 *cast<GlobalVariable>(Aliasee));
48 A.replaceAllUsesWith(G);
49 A.eraseFromParent();
50 G->setName(AliasName);
51 } else
52 llvm_unreachable("Alias to unsupported type");
Lang Hames8d76c712018-09-26 01:24:12 +000053 } else
54 llvm_unreachable("Unsupported global type");
Lang Hames8d76c712018-09-26 01:24:12 +000055 };
Lang Hames68c9b8d2018-06-18 18:01:43 +000056
Lang Hames98440292018-09-29 23:49:57 +000057 auto NewTSMod = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs);
Lang Hames8d76c712018-09-26 01:24:12 +000058 auto &M = *NewTSMod.getModule();
59 M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str());
Lang Hames68c9b8d2018-06-18 18:01:43 +000060
Lang Hames8d76c712018-09-26 01:24:12 +000061 return NewTSMod;
Lang Hames7bd89702018-07-05 19:01:27 +000062}
63
Lang Hames68c9b8d2018-06-18 18:01:43 +000064namespace llvm {
65namespace orc {
66
Lang Hames98440292018-09-29 23:49:57 +000067class PartitioningIRMaterializationUnit : public IRMaterializationUnit {
Lang Hames68c9b8d2018-06-18 18:01:43 +000068public:
Lang Hames98440292018-09-29 23:49:57 +000069 PartitioningIRMaterializationUnit(ExecutionSession &ES, ThreadSafeModule TSM,
Lang Hames8b942742018-10-16 20:13:06 +000070 VModuleKey K, CompileOnDemandLayer &Parent)
71 : IRMaterializationUnit(ES, std::move(TSM), std::move(K)),
72 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000073
Lang Hames98440292018-09-29 23:49:57 +000074 PartitioningIRMaterializationUnit(
75 ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags,
76 SymbolNameToDefinitionMap SymbolToDefinition,
Lang Hames079df9a2018-10-15 22:56:10 +000077 CompileOnDemandLayer &Parent)
Lang Hames8b942742018-10-16 20:13:06 +000078 : IRMaterializationUnit(std::move(TSM), std::move(K),
79 std::move(SymbolFlags),
Lang Hames68c9b8d2018-06-18 18:01:43 +000080 std::move(SymbolToDefinition)),
Lang Hamesfd0c1e712018-07-20 18:31:50 +000081 Parent(Parent) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +000082
83private:
84 void materialize(MaterializationResponsibility R) override {
Lang Hames98440292018-09-29 23:49:57 +000085 Parent.emitPartition(std::move(R), std::move(TSM),
86 std::move(SymbolToDefinition));
Lang Hames68c9b8d2018-06-18 18:01:43 +000087 }
88
Lang Hamescb5702c32018-10-06 23:02:06 +000089 void discard(const JITDylib &V, const SymbolStringPtr &Name) override {
Lang Hames68c9b8d2018-06-18 18:01:43 +000090 // All original symbols were materialized by the CODLayer and should be
91 // final. The function bodies provided by M should never be overridden.
92 llvm_unreachable("Discard should never be called on an "
93 "ExtractingIRMaterializationUnit");
94 }
95
Lang Hames7bd89702018-07-05 19:01:27 +000096 mutable std::mutex SourceModuleMutex;
Lang Hames079df9a2018-10-15 22:56:10 +000097 CompileOnDemandLayer &Parent;
Lang Hames68c9b8d2018-06-18 18:01:43 +000098};
99
Lang Hames079df9a2018-10-15 22:56:10 +0000100Optional<CompileOnDemandLayer::GlobalValueSet>
101CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) {
Lang Hames98440292018-09-29 23:49:57 +0000102 return std::move(Requested);
103}
104
Lang Hames079df9a2018-10-15 22:56:10 +0000105Optional<CompileOnDemandLayer::GlobalValueSet>
106CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) {
Lang Hames98440292018-09-29 23:49:57 +0000107 return None;
108}
109
Lang Hames079df9a2018-10-15 22:56:10 +0000110CompileOnDemandLayer::CompileOnDemandLayer(
Lang Hamesd8048672018-09-26 05:08:29 +0000111 ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr,
Lang Hames8d76c712018-09-26 01:24:12 +0000112 IndirectStubsManagerBuilder BuildIndirectStubsManager)
Lang Hamesd8048672018-09-26 05:08:29 +0000113 : IRLayer(ES), BaseLayer(BaseLayer), LCTMgr(LCTMgr),
Lang Hames8d76c712018-09-26 01:24:12 +0000114 BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {}
Lang Hames68c9b8d2018-06-18 18:01:43 +0000115
Lang Hames079df9a2018-10-15 22:56:10 +0000116void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000117 this->Partition = std::move(Partition);
Lang Hames68c9b8d2018-06-18 18:01:43 +0000118}
119
Lang Hames8b942742018-10-16 20:13:06 +0000120void CompileOnDemandLayer::emit(MaterializationResponsibility R,
121 ThreadSafeModule TSM) {
Lang Hames98440292018-09-29 23:49:57 +0000122 assert(TSM.getModule() && "Null module");
123
Lang Hames68c9b8d2018-06-18 18:01:43 +0000124 auto &ES = getExecutionSession();
Lang Hames8d76c712018-09-26 01:24:12 +0000125 auto &M = *TSM.getModule();
Lang Hames68c9b8d2018-06-18 18:01:43 +0000126
Lang Hames98440292018-09-29 23:49:57 +0000127 // First, do some cleanup on the module:
128 cleanUpModule(M);
129
130 // Now sort the callables and non-callables, build re-exports and lodge the
131 // actual module with the implementation dylib.
132 auto &PDR = getPerDylibResources(R.getTargetJITDylib());
Lang Hames68c9b8d2018-06-18 18:01:43 +0000133
Lang Hames8d76c712018-09-26 01:24:12 +0000134 MangleAndInterner Mangle(ES, M.getDataLayout());
Lang Hames98440292018-09-29 23:49:57 +0000135 SymbolAliasMap NonCallables;
136 SymbolAliasMap Callables;
137 for (auto &GV : M.global_values()) {
Lang Hamesbf6603e2018-10-09 20:44:32 +0000138 if (GV.isDeclaration() || GV.hasLocalLinkage() || GV.hasAppendingLinkage())
Lang Hames68c9b8d2018-06-18 18:01:43 +0000139 continue;
140
Lang Hames98440292018-09-29 23:49:57 +0000141 auto Name = Mangle(GV.getName());
142 auto Flags = JITSymbolFlags::fromGlobalValue(GV);
143 if (Flags.isCallable())
144 Callables[Name] = SymbolAliasMapEntry(Name, Flags);
145 else
146 NonCallables[Name] = SymbolAliasMapEntry(Name, Flags);
Lang Hames68c9b8d2018-06-18 18:01:43 +0000147 }
148
Lang Hames98440292018-09-29 23:49:57 +0000149 // Create a partitioning materialization unit and lodge it with the
150 // implementation dylib.
151 if (auto Err = PDR.getImplDylib().define(
152 llvm::make_unique<PartitioningIRMaterializationUnit>(
Lang Hames8b942742018-10-16 20:13:06 +0000153 ES, std::move(TSM), R.getVModuleKey(), *this))) {
Lang Hames68c9b8d2018-06-18 18:01:43 +0000154 ES.reportError(std::move(Err));
155 R.failMaterialization();
156 return;
157 }
158
Lang Hames23cb2e72018-10-23 23:01:39 +0000159 R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables), true));
Lang Hames98440292018-09-29 23:49:57 +0000160 R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(),
161 std::move(Callables)));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000162}
163
Lang Hames079df9a2018-10-15 22:56:10 +0000164CompileOnDemandLayer::PerDylibResources &
165CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) {
Lang Hamesd8048672018-09-26 05:08:29 +0000166 auto I = DylibResources.find(&TargetD);
167 if (I == DylibResources.end()) {
Lang Hames23cb2e72018-10-23 23:01:39 +0000168 auto &ImplD = getExecutionSession().createJITDylib(
169 TargetD.getName() + ".impl", false);
170 TargetD.withSearchOrderDo([&](const JITDylibSearchList &TargetSearchOrder) {
171 auto NewSearchOrder = TargetSearchOrder;
172 assert(!NewSearchOrder.empty() &&
173 NewSearchOrder.front().first == &TargetD &&
174 NewSearchOrder.front().second == true &&
175 "TargetD must be at the front of its own search order and match "
176 "non-exported symbol");
177 NewSearchOrder.insert(std::next(NewSearchOrder.begin()), {&ImplD, true});
178 ImplD.setSearchOrder(std::move(NewSearchOrder), false);
Lang Hamesd8048672018-09-26 05:08:29 +0000179 });
180 PerDylibResources PDR(ImplD, BuildIndirectStubsManager());
181 I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first;
182 }
183
184 return I->second;
Lang Hames68c9b8d2018-06-18 18:01:43 +0000185}
186
Lang Hames079df9a2018-10-15 22:56:10 +0000187void CompileOnDemandLayer::cleanUpModule(Module &M) {
Lang Hames98440292018-09-29 23:49:57 +0000188 for (auto &F : M.functions()) {
189 if (F.isDeclaration())
190 continue;
191
192 if (F.hasAvailableExternallyLinkage()) {
193 F.deleteBody();
194 F.setPersonalityFn(nullptr);
195 continue;
196 }
197 }
198}
199
Lang Hames079df9a2018-10-15 22:56:10 +0000200void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) {
Lang Hames98440292018-09-29 23:49:57 +0000201 // Expands the partition to ensure the following rules hold:
202 // (1) If any alias is in the partition, its aliasee is also in the partition.
203 // (2) If any aliasee is in the partition, its aliases are also in the
204 // partiton.
205 // (3) If any global variable is in the partition then all global variables
206 // are in the partition.
207 assert(!Partition.empty() && "Unexpected empty partition");
208
209 const Module &M = *(*Partition.begin())->getParent();
210 bool ContainsGlobalVariables = false;
211 std::vector<const GlobalValue *> GVsToAdd;
212
213 for (auto *GV : Partition)
214 if (isa<GlobalAlias>(GV))
215 GVsToAdd.push_back(
216 cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee()));
217 else if (isa<GlobalVariable>(GV))
218 ContainsGlobalVariables = true;
219
220 for (auto &A : M.aliases())
221 if (Partition.count(cast<GlobalValue>(A.getAliasee())))
222 GVsToAdd.push_back(&A);
223
224 if (ContainsGlobalVariables)
225 for (auto &G : M.globals())
226 GVsToAdd.push_back(&G);
227
228 for (auto *GV : GVsToAdd)
229 Partition.insert(GV);
230}
231
Lang Hames079df9a2018-10-15 22:56:10 +0000232void CompileOnDemandLayer::emitPartition(
Lang Hames98440292018-09-29 23:49:57 +0000233 MaterializationResponsibility R, ThreadSafeModule TSM,
234 IRMaterializationUnit::SymbolNameToDefinitionMap Defs) {
235
236 // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the
237 // extracted module key, extracted module, and source module key
238 // together. This could be used, for example, to provide a specific
239 // memory manager instance to the linking layer.
240
241 auto &ES = getExecutionSession();
242
243 GlobalValueSet RequestedGVs;
244 for (auto &Name : R.getRequestedSymbols()) {
245 assert(Defs.count(Name) && "No definition for symbol");
246 RequestedGVs.insert(Defs[Name]);
247 }
248
249 auto GVsToExtract = Partition(RequestedGVs);
250
251 // Take a 'None' partition to mean the whole module (as opposed to an empty
252 // partition, which means "materialize nothing"). Emit the whole module
253 // unmodified to the base layer.
254 if (GVsToExtract == None) {
255 Defs.clear();
Lang Hames8b942742018-10-16 20:13:06 +0000256 BaseLayer.emit(std::move(R), std::move(TSM));
Lang Hames98440292018-09-29 23:49:57 +0000257 return;
258 }
259
260 // If the partition is empty, return the whole module to the symbol table.
261 if (GVsToExtract->empty()) {
262 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
263 std::move(TSM), R.getSymbols(), std::move(Defs), *this));
264 return;
265 }
266
Lang Hamesbf6603e2018-10-09 20:44:32 +0000267 // Ok -- we actually need to partition the symbols. Promote the symbol
268 // linkages/names.
269 // FIXME: We apply this once per partitioning. It's safe, but overkill.
270 {
271 auto PromotedGlobals = PromoteSymbols(*TSM.getModule());
272 if (!PromotedGlobals.empty()) {
273 MangleAndInterner Mangle(ES, TSM.getModule()->getDataLayout());
274 SymbolFlagsMap SymbolFlags;
275 for (auto &GV : PromotedGlobals)
276 SymbolFlags[Mangle(GV->getName())] =
277 JITSymbolFlags::fromGlobalValue(*GV);
278 if (auto Err = R.defineMaterializing(SymbolFlags)) {
279 ES.reportError(std::move(Err));
280 R.failMaterialization();
281 return;
282 }
283 }
284 }
285
Lang Hames98440292018-09-29 23:49:57 +0000286 expandPartition(*GVsToExtract);
287
288 // Extract the requested partiton (plus any necessary aliases) and
289 // put the rest back into the impl dylib.
290 auto ShouldExtract = [&](const GlobalValue &GV) -> bool {
291 return GVsToExtract->count(&GV);
292 };
293
294 auto ExtractedTSM = extractSubModule(TSM, ".submodule", ShouldExtract);
Lang Hames98440292018-09-29 23:49:57 +0000295 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>(
Lang Hames8b942742018-10-16 20:13:06 +0000296 ES, std::move(TSM), R.getVModuleKey(), *this));
Lang Hames98440292018-09-29 23:49:57 +0000297
Lang Hames8b942742018-10-16 20:13:06 +0000298 BaseLayer.emit(std::move(R), std::move(ExtractedTSM));
Lang Hames68c9b8d2018-06-18 18:01:43 +0000299}
300
301} // end namespace orc
302} // end namespace llvm