1 //===----- CompileOnDemandLayer.cpp - Lazily emit IR on first call --------===// 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 #include "llvm/ExecutionEngine/Orc/CompileOnDemandLayer.h" 10 #include "llvm/IR/Mangler.h" 11 #include "llvm/IR/Module.h" 12 13 using namespace llvm; 14 using namespace llvm::orc; 15 16 static ThreadSafeModule extractSubModule(ThreadSafeModule &TSM, 17 StringRef Suffix, 18 GVPredicate ShouldExtract) { 19 20 auto DeleteExtractedDefs = [](GlobalValue &GV) { 21 // Bump the linkage: this global will be provided by the external module. 22 GV.setLinkage(GlobalValue::ExternalLinkage); 23 24 // Delete the definition in the source module. 25 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); 31 } 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"); 53 } else 54 llvm_unreachable("Unsupported global type"); 55 }; 56 57 auto NewTSM = cloneToNewContext(TSM, ShouldExtract, DeleteExtractedDefs); 58 NewTSM.withModuleDo([&](Module &M) { 59 M.setModuleIdentifier((M.getModuleIdentifier() + Suffix).str()); 60 }); 61 62 return NewTSM; 63 } 64 65 namespace llvm { 66 namespace orc { 67 68 class PartitioningIRMaterializationUnit : public IRMaterializationUnit { 69 public: 70 PartitioningIRMaterializationUnit(ExecutionSession &ES, ThreadSafeModule TSM, 71 VModuleKey K, CompileOnDemandLayer &Parent) 72 : IRMaterializationUnit(ES, std::move(TSM), std::move(K)), 73 Parent(Parent) {} 74 75 PartitioningIRMaterializationUnit( 76 ThreadSafeModule TSM, SymbolFlagsMap SymbolFlags, 77 SymbolNameToDefinitionMap SymbolToDefinition, 78 CompileOnDemandLayer &Parent) 79 : IRMaterializationUnit(std::move(TSM), std::move(K), 80 std::move(SymbolFlags), 81 std::move(SymbolToDefinition)), 82 Parent(Parent) {} 83 84 private: 85 void materialize(MaterializationResponsibility R) override { 86 Parent.emitPartition(std::move(R), std::move(TSM), 87 std::move(SymbolToDefinition)); 88 } 89 90 void discard(const JITDylib &V, const SymbolStringPtr &Name) override { 91 // 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 97 mutable std::mutex SourceModuleMutex; 98 CompileOnDemandLayer &Parent; 99 }; 100 101 Optional<CompileOnDemandLayer::GlobalValueSet> 102 CompileOnDemandLayer::compileRequested(GlobalValueSet Requested) { 103 return std::move(Requested); 104 } 105 106 Optional<CompileOnDemandLayer::GlobalValueSet> 107 CompileOnDemandLayer::compileWholeModule(GlobalValueSet Requested) { 108 return None; 109 } 110 111 CompileOnDemandLayer::CompileOnDemandLayer( 112 ExecutionSession &ES, IRLayer &BaseLayer, LazyCallThroughManager &LCTMgr, 113 IndirectStubsManagerBuilder BuildIndirectStubsManager) 114 : IRLayer(ES), BaseLayer(BaseLayer), LCTMgr(LCTMgr), 115 BuildIndirectStubsManager(std::move(BuildIndirectStubsManager)) {} 116 117 void CompileOnDemandLayer::setPartitionFunction(PartitionFunction Partition) { 118 this->Partition = std::move(Partition); 119 } 120 121 void CompileOnDemandLayer::emit(MaterializationResponsibility R, 122 ThreadSafeModule TSM) { 123 assert(TSM && "Null module"); 124 125 auto &ES = getExecutionSession(); 126 127 // Sort the callables and non-callables, build re-exports and lodge the 128 // actual module with the implementation dylib. 129 auto &PDR = getPerDylibResources(R.getTargetJITDylib()); 130 131 SymbolAliasMap NonCallables; 132 SymbolAliasMap Callables; 133 TSM.withModuleDo([&](Module &M) { 134 // First, do some cleanup on the module: 135 cleanUpModule(M); 136 137 MangleAndInterner Mangle(ES, M.getDataLayout()); 138 for (auto &GV : M.global_values()) { 139 if (GV.isDeclaration() || GV.hasLocalLinkage() || 140 GV.hasAppendingLinkage()) 141 continue; 142 143 auto Name = Mangle(GV.getName()); 144 auto Flags = JITSymbolFlags::fromGlobalValue(GV); 145 if (Flags.isCallable()) 146 Callables[Name] = SymbolAliasMapEntry(Name, Flags); 147 else 148 NonCallables[Name] = SymbolAliasMapEntry(Name, Flags); 149 } 150 }); 151 152 // Create a partitioning materialization unit and lodge it with the 153 // implementation dylib. 154 if (auto Err = PDR.getImplDylib().define( 155 llvm::make_unique<PartitioningIRMaterializationUnit>( 156 ES, std::move(TSM), R.getVModuleKey(), *this))) { 157 ES.reportError(std::move(Err)); 158 R.failMaterialization(); 159 return; 160 } 161 162 R.replace(reexports(PDR.getImplDylib(), std::move(NonCallables), true)); 163 R.replace(lazyReexports(LCTMgr, PDR.getISManager(), PDR.getImplDylib(), 164 std::move(Callables))); 165 } 166 167 CompileOnDemandLayer::PerDylibResources & 168 CompileOnDemandLayer::getPerDylibResources(JITDylib &TargetD) { 169 auto I = DylibResources.find(&TargetD); 170 if (I == DylibResources.end()) { 171 auto &ImplD = getExecutionSession().createJITDylib( 172 TargetD.getName() + ".impl", false); 173 TargetD.withSearchOrderDo([&](const JITDylibSearchList &TargetSearchOrder) { 174 auto NewSearchOrder = TargetSearchOrder; 175 assert(!NewSearchOrder.empty() && 176 NewSearchOrder.front().first == &TargetD && 177 NewSearchOrder.front().second == true && 178 "TargetD must be at the front of its own search order and match " 179 "non-exported symbol"); 180 NewSearchOrder.insert(std::next(NewSearchOrder.begin()), {&ImplD, true}); 181 ImplD.setSearchOrder(std::move(NewSearchOrder), false); 182 }); 183 PerDylibResources PDR(ImplD, BuildIndirectStubsManager()); 184 I = DylibResources.insert(std::make_pair(&TargetD, std::move(PDR))).first; 185 } 186 187 return I->second; 188 } 189 190 void CompileOnDemandLayer::cleanUpModule(Module &M) { 191 for (auto &F : M.functions()) { 192 if (F.isDeclaration()) 193 continue; 194 195 if (F.hasAvailableExternallyLinkage()) { 196 F.deleteBody(); 197 F.setPersonalityFn(nullptr); 198 continue; 199 } 200 } 201 } 202 203 void CompileOnDemandLayer::expandPartition(GlobalValueSet &Partition) { 204 // Expands the partition to ensure the following rules hold: 205 // (1) If any alias is in the partition, its aliasee is also in the partition. 206 // (2) If any aliasee is in the partition, its aliases are also in the 207 // partiton. 208 // (3) If any global variable is in the partition then all global variables 209 // are in the partition. 210 assert(!Partition.empty() && "Unexpected empty partition"); 211 212 const Module &M = *(*Partition.begin())->getParent(); 213 bool ContainsGlobalVariables = false; 214 std::vector<const GlobalValue *> GVsToAdd; 215 216 for (auto *GV : Partition) 217 if (isa<GlobalAlias>(GV)) 218 GVsToAdd.push_back( 219 cast<GlobalValue>(cast<GlobalAlias>(GV)->getAliasee())); 220 else if (isa<GlobalVariable>(GV)) 221 ContainsGlobalVariables = true; 222 223 for (auto &A : M.aliases()) 224 if (Partition.count(cast<GlobalValue>(A.getAliasee()))) 225 GVsToAdd.push_back(&A); 226 227 if (ContainsGlobalVariables) 228 for (auto &G : M.globals()) 229 GVsToAdd.push_back(&G); 230 231 for (auto *GV : GVsToAdd) 232 Partition.insert(GV); 233 } 234 235 void CompileOnDemandLayer::emitPartition( 236 MaterializationResponsibility R, ThreadSafeModule TSM, 237 IRMaterializationUnit::SymbolNameToDefinitionMap Defs) { 238 239 // FIXME: Need a 'notify lazy-extracting/emitting' callback to tie the 240 // extracted module key, extracted module, and source module key 241 // together. This could be used, for example, to provide a specific 242 // memory manager instance to the linking layer. 243 244 auto &ES = getExecutionSession(); 245 GlobalValueSet RequestedGVs; 246 for (auto &Name : R.getRequestedSymbols()) { 247 assert(Defs.count(Name) && "No definition for symbol"); 248 RequestedGVs.insert(Defs[Name]); 249 } 250 251 /// Perform partitioning with the context lock held, since the partition 252 /// function is allowed to access the globals to compute the partition. 253 auto GVsToExtract = 254 TSM.withModuleDo([&](Module &M) { return Partition(RequestedGVs); }); 255 256 // Take a 'None' partition to mean the whole module (as opposed to an empty 257 // partition, which means "materialize nothing"). Emit the whole module 258 // unmodified to the base layer. 259 if (GVsToExtract == None) { 260 Defs.clear(); 261 BaseLayer.emit(std::move(R), std::move(TSM)); 262 return; 263 } 264 265 // If the partition is empty, return the whole module to the symbol table. 266 if (GVsToExtract->empty()) { 267 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>( 268 std::move(TSM), R.getSymbols(), std::move(Defs), *this)); 269 return; 270 } 271 272 // Ok -- we actually need to partition the symbols. Promote the symbol 273 // linkages/names, expand the partition to include any required symbols 274 // (i.e. symbols that can't be separated from our partition), and 275 // then extract the partition. 276 // 277 // FIXME: We apply this promotion once per partitioning. It's safe, but 278 // overkill. 279 280 auto ExtractedTSM = 281 TSM.withModuleDo([&](Module &M) -> Expected<ThreadSafeModule> { 282 auto PromotedGlobals = PromoteSymbols(M); 283 if (!PromotedGlobals.empty()) { 284 MangleAndInterner Mangle(ES, M.getDataLayout()); 285 SymbolFlagsMap SymbolFlags; 286 for (auto &GV : PromotedGlobals) 287 SymbolFlags[Mangle(GV->getName())] = 288 JITSymbolFlags::fromGlobalValue(*GV); 289 if (auto Err = R.defineMaterializing(SymbolFlags)) 290 return std::move(Err); 291 } 292 293 expandPartition(*GVsToExtract); 294 295 // Extract the requested partiton (plus any necessary aliases) and 296 // put the rest back into the impl dylib. 297 auto ShouldExtract = [&](const GlobalValue &GV) -> bool { 298 return GVsToExtract->count(&GV); 299 }; 300 301 return extractSubModule(TSM, ".submodule", ShouldExtract); 302 }); 303 304 if (!ExtractedTSM) { 305 ES.reportError(ExtractedTSM.takeError()); 306 R.failMaterialization(); 307 return; 308 } 309 310 R.replace(llvm::make_unique<PartitioningIRMaterializationUnit>( 311 ES, std::move(TSM), R.getVModuleKey(), *this)); 312 BaseLayer.emit(std::move(R), std::move(*ExtractedTSM)); 313 } 314 315 } // end namespace orc 316 } // end namespace llvm 317