xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/Orc/Speculation.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
18bcb0991SDimitry Andric //===---------- speculation.cpp - Utilities for Speculation ----------===//
28bcb0991SDimitry Andric //
38bcb0991SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48bcb0991SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
58bcb0991SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68bcb0991SDimitry Andric //
78bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
88bcb0991SDimitry Andric 
98bcb0991SDimitry Andric #include "llvm/ExecutionEngine/Orc/Speculation.h"
108bcb0991SDimitry Andric #include "llvm/IR/BasicBlock.h"
118bcb0991SDimitry Andric #include "llvm/IR/Function.h"
128bcb0991SDimitry Andric #include "llvm/IR/IRBuilder.h"
138bcb0991SDimitry Andric #include "llvm/IR/Instruction.h"
148bcb0991SDimitry Andric #include "llvm/IR/Instructions.h"
158bcb0991SDimitry Andric #include "llvm/IR/LLVMContext.h"
168bcb0991SDimitry Andric #include "llvm/IR/Module.h"
178bcb0991SDimitry Andric #include "llvm/IR/Type.h"
188bcb0991SDimitry Andric #include "llvm/IR/Verifier.h"
198bcb0991SDimitry Andric #include "llvm/Support/Debug.h"
208bcb0991SDimitry Andric 
218bcb0991SDimitry Andric #include <vector>
228bcb0991SDimitry Andric 
238bcb0991SDimitry Andric namespace llvm {
248bcb0991SDimitry Andric 
258bcb0991SDimitry Andric namespace orc {
268bcb0991SDimitry Andric 
278bcb0991SDimitry Andric // ImplSymbolMap methods
288bcb0991SDimitry Andric void ImplSymbolMap::trackImpls(SymbolAliasMap ImplMaps, JITDylib *SrcJD) {
298bcb0991SDimitry Andric   assert(SrcJD && "Tracking on Null Source .impl dylib");
308bcb0991SDimitry Andric   std::lock_guard<std::mutex> Lockit(ConcurrentAccess);
318bcb0991SDimitry Andric   for (auto &I : ImplMaps) {
328bcb0991SDimitry Andric     auto It = Maps.insert({I.first, {I.second.Aliasee, SrcJD}});
338bcb0991SDimitry Andric     // check rationale when independent dylibs have same symbol name?
348bcb0991SDimitry Andric     assert(It.second && "ImplSymbols are already tracked for this Symbol?");
358bcb0991SDimitry Andric     (void)(It);
368bcb0991SDimitry Andric   }
378bcb0991SDimitry Andric }
388bcb0991SDimitry Andric 
398bcb0991SDimitry Andric // Trigger Speculative Compiles.
408bcb0991SDimitry Andric void Speculator::speculateForEntryPoint(Speculator *Ptr, uint64_t StubId) {
418bcb0991SDimitry Andric   assert(Ptr && " Null Address Received in orc_speculate_for ");
428bcb0991SDimitry Andric   Ptr->speculateFor(StubId);
438bcb0991SDimitry Andric }
448bcb0991SDimitry Andric 
458bcb0991SDimitry Andric Error Speculator::addSpeculationRuntime(JITDylib &JD,
468bcb0991SDimitry Andric                                         MangleAndInterner &Mangle) {
478bcb0991SDimitry Andric   JITEvaluatedSymbol ThisPtr(pointerToJITTargetAddress(this),
488bcb0991SDimitry Andric                              JITSymbolFlags::Exported);
498bcb0991SDimitry Andric   JITEvaluatedSymbol SpeculateForEntryPtr(
508bcb0991SDimitry Andric       pointerToJITTargetAddress(&speculateForEntryPoint),
518bcb0991SDimitry Andric       JITSymbolFlags::Exported);
528bcb0991SDimitry Andric   return JD.define(absoluteSymbols({
538bcb0991SDimitry Andric       {Mangle("__orc_speculator"), ThisPtr},                // Data Symbol
548bcb0991SDimitry Andric       {Mangle("__orc_speculate_for"), SpeculateForEntryPtr} // Callable Symbol
558bcb0991SDimitry Andric   }));
568bcb0991SDimitry Andric }
578bcb0991SDimitry Andric 
588bcb0991SDimitry Andric // If two modules, share the same LLVMContext, different threads must
598bcb0991SDimitry Andric // not access them concurrently without locking the associated LLVMContext
608bcb0991SDimitry Andric // this implementation follows this contract.
618bcb0991SDimitry Andric void IRSpeculationLayer::emit(MaterializationResponsibility R,
628bcb0991SDimitry Andric                               ThreadSafeModule TSM) {
638bcb0991SDimitry Andric 
648bcb0991SDimitry Andric   assert(TSM && "Speculation Layer received Null Module ?");
658bcb0991SDimitry Andric   assert(TSM.getContext().getContext() != nullptr &&
668bcb0991SDimitry Andric          "Module with null LLVMContext?");
678bcb0991SDimitry Andric 
688bcb0991SDimitry Andric   // Instrumentation of runtime calls, lock the Module
698bcb0991SDimitry Andric   TSM.withModuleDo([this, &R](Module &M) {
708bcb0991SDimitry Andric     auto &MContext = M.getContext();
718bcb0991SDimitry Andric     auto SpeculatorVTy = StructType::create(MContext, "Class.Speculator");
728bcb0991SDimitry Andric     auto RuntimeCallTy = FunctionType::get(
738bcb0991SDimitry Andric         Type::getVoidTy(MContext),
748bcb0991SDimitry Andric         {SpeculatorVTy->getPointerTo(), Type::getInt64Ty(MContext)}, false);
758bcb0991SDimitry Andric     auto RuntimeCall =
768bcb0991SDimitry Andric         Function::Create(RuntimeCallTy, Function::LinkageTypes::ExternalLinkage,
778bcb0991SDimitry Andric                          "__orc_speculate_for", &M);
788bcb0991SDimitry Andric     auto SpeclAddr = new GlobalVariable(
798bcb0991SDimitry Andric         M, SpeculatorVTy, false, GlobalValue::LinkageTypes::ExternalLinkage,
808bcb0991SDimitry Andric         nullptr, "__orc_speculator");
818bcb0991SDimitry Andric 
828bcb0991SDimitry Andric     IRBuilder<> Mutator(MContext);
838bcb0991SDimitry Andric 
848bcb0991SDimitry Andric     // QueryAnalysis allowed to transform the IR source, one such example is
858bcb0991SDimitry Andric     // Simplify CFG helps the static branch prediction heuristics!
868bcb0991SDimitry Andric     for (auto &Fn : M.getFunctionList()) {
878bcb0991SDimitry Andric       if (!Fn.isDeclaration()) {
888bcb0991SDimitry Andric 
898bcb0991SDimitry Andric         auto IRNames = QueryAnalysis(Fn);
908bcb0991SDimitry Andric         // Instrument and register if Query has result
918bcb0991SDimitry Andric         if (IRNames.hasValue()) {
928bcb0991SDimitry Andric 
938bcb0991SDimitry Andric           // Emit globals for each function.
948bcb0991SDimitry Andric           auto LoadValueTy = Type::getInt8Ty(MContext);
958bcb0991SDimitry Andric           auto SpeculatorGuard = new GlobalVariable(
968bcb0991SDimitry Andric               M, LoadValueTy, false, GlobalValue::LinkageTypes::InternalLinkage,
978bcb0991SDimitry Andric               ConstantInt::get(LoadValueTy, 0),
988bcb0991SDimitry Andric               "__orc_speculate.guard.for." + Fn.getName());
99*5ffd83dbSDimitry Andric           SpeculatorGuard->setAlignment(Align(1));
1008bcb0991SDimitry Andric           SpeculatorGuard->setUnnamedAddr(GlobalValue::UnnamedAddr::Local);
1018bcb0991SDimitry Andric 
1028bcb0991SDimitry Andric           BasicBlock &ProgramEntry = Fn.getEntryBlock();
1038bcb0991SDimitry Andric           // Create BasicBlocks before the program's entry basicblock
1048bcb0991SDimitry Andric           BasicBlock *SpeculateBlock = BasicBlock::Create(
1058bcb0991SDimitry Andric               MContext, "__orc_speculate.block", &Fn, &ProgramEntry);
1068bcb0991SDimitry Andric           BasicBlock *SpeculateDecisionBlock = BasicBlock::Create(
1078bcb0991SDimitry Andric               MContext, "__orc_speculate.decision.block", &Fn, SpeculateBlock);
1088bcb0991SDimitry Andric 
1098bcb0991SDimitry Andric           assert(SpeculateDecisionBlock == &Fn.getEntryBlock() &&
1108bcb0991SDimitry Andric                  "SpeculateDecisionBlock not updated?");
1118bcb0991SDimitry Andric           Mutator.SetInsertPoint(SpeculateDecisionBlock);
1128bcb0991SDimitry Andric 
1138bcb0991SDimitry Andric           auto LoadGuard =
1148bcb0991SDimitry Andric               Mutator.CreateLoad(LoadValueTy, SpeculatorGuard, "guard.value");
1158bcb0991SDimitry Andric           // if just loaded value equal to 0,return true.
1168bcb0991SDimitry Andric           auto CanSpeculate =
1178bcb0991SDimitry Andric               Mutator.CreateICmpEQ(LoadGuard, ConstantInt::get(LoadValueTy, 0),
1188bcb0991SDimitry Andric                                    "compare.to.speculate");
1198bcb0991SDimitry Andric           Mutator.CreateCondBr(CanSpeculate, SpeculateBlock, &ProgramEntry);
1208bcb0991SDimitry Andric 
1218bcb0991SDimitry Andric           Mutator.SetInsertPoint(SpeculateBlock);
1228bcb0991SDimitry Andric           auto ImplAddrToUint =
1238bcb0991SDimitry Andric               Mutator.CreatePtrToInt(&Fn, Type::getInt64Ty(MContext));
1248bcb0991SDimitry Andric           Mutator.CreateCall(RuntimeCallTy, RuntimeCall,
1258bcb0991SDimitry Andric                              {SpeclAddr, ImplAddrToUint});
1268bcb0991SDimitry Andric           Mutator.CreateStore(ConstantInt::get(LoadValueTy, 1),
1278bcb0991SDimitry Andric                               SpeculatorGuard);
1288bcb0991SDimitry Andric           Mutator.CreateBr(&ProgramEntry);
1298bcb0991SDimitry Andric 
1308bcb0991SDimitry Andric           assert(Mutator.GetInsertBlock()->getParent() == &Fn &&
1318bcb0991SDimitry Andric                  "IR builder association mismatch?");
1328bcb0991SDimitry Andric           S.registerSymbols(internToJITSymbols(IRNames.getValue()),
1338bcb0991SDimitry Andric                             &R.getTargetJITDylib());
1348bcb0991SDimitry Andric         }
1358bcb0991SDimitry Andric       }
1368bcb0991SDimitry Andric     }
1378bcb0991SDimitry Andric   });
1388bcb0991SDimitry Andric 
1398bcb0991SDimitry Andric   assert(!TSM.withModuleDo([](const Module &M) { return verifyModule(M); }) &&
1408bcb0991SDimitry Andric          "Speculation Instrumentation breaks IR?");
1418bcb0991SDimitry Andric 
1428bcb0991SDimitry Andric   NextLayer.emit(std::move(R), std::move(TSM));
1438bcb0991SDimitry Andric }
1448bcb0991SDimitry Andric 
1458bcb0991SDimitry Andric } // namespace orc
1468bcb0991SDimitry Andric } // namespace llvm
147