aot_llvm_extra.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <llvm/ADT/SmallVector.h>
  6. #include <llvm/ADT/Twine.h>
  7. #include <llvm/ADT/Triple.h>
  8. #include <llvm/Analysis/TargetTransformInfo.h>
  9. #include <llvm/CodeGen/TargetPassConfig.h>
  10. #include <llvm/ExecutionEngine/ExecutionEngine.h>
  11. #include <llvm/MC/MCSubtargetInfo.h>
  12. #include <llvm/Support/TargetSelect.h>
  13. #include <llvm/Target/TargetMachine.h>
  14. #include <llvm-c/Core.h>
  15. #include <llvm-c/ExecutionEngine.h>
  16. #include <llvm-c/Initialization.h>
  17. #include <llvm/ExecutionEngine/GenericValue.h>
  18. #include <llvm/ExecutionEngine/JITEventListener.h>
  19. #include <llvm/ExecutionEngine/RTDyldMemoryManager.h>
  20. #include <llvm/ExecutionEngine/Orc/LLJIT.h>
  21. #include <llvm/IR/DerivedTypes.h>
  22. #include <llvm/IR/Module.h>
  23. #include <llvm/IR/Instructions.h>
  24. #include <llvm/IR/IntrinsicInst.h>
  25. #include <llvm/IR/LegacyPassManager.h>
  26. #include <llvm/Support/CommandLine.h>
  27. #include <llvm/Support/ErrorHandling.h>
  28. #include <llvm/Target/CodeGenCWrappers.h>
  29. #include <llvm/Target/TargetMachine.h>
  30. #include <llvm/Target/TargetOptions.h>
  31. #include <llvm/Transforms/Utils/LowerMemIntrinsics.h>
  32. #include <llvm/Transforms/Vectorize/LoopVectorize.h>
  33. #include <llvm/Transforms/Vectorize/LoadStoreVectorizer.h>
  34. #include <llvm/Transforms/Vectorize/SLPVectorizer.h>
  35. #include <llvm/Transforms/Scalar/LoopRotation.h>
  36. #include <llvm/Transforms/Scalar/SimpleLoopUnswitch.h>
  37. #include <llvm/Transforms/Scalar/LICM.h>
  38. #include <llvm/Transforms/Scalar/GVN.h>
  39. #include <llvm/Passes/PassBuilder.h>
  40. #include <llvm/Analysis/TargetLibraryInfo.h>
  41. #if LLVM_VERSION_MAJOR >= 12
  42. #include <llvm/Analysis/AliasAnalysis.h>
  43. #endif
  44. #include <cstring>
  45. #if WASM_ENABLE_LAZY_JIT != 0
  46. #include "../aot/aot_runtime.h"
  47. #endif
  48. #include "aot_llvm.h"
  49. using namespace llvm;
  50. using namespace llvm::orc;
  51. extern "C" {
  52. LLVMBool
  53. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  54. LLVMModuleRef M,
  55. LLVMMCJITCompilerOptions *PassedOptions,
  56. size_t SizeOfPassedOptions, char **OutError);
  57. bool
  58. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str);
  59. void
  60. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass);
  61. void
  62. aot_func_disable_tce(LLVMValueRef func);
  63. void
  64. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx);
  65. }
  66. static TargetMachine *
  67. unwrap(LLVMTargetMachineRef P)
  68. {
  69. return reinterpret_cast<TargetMachine *>(P);
  70. }
  71. LLVMBool
  72. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  73. LLVMModuleRef M,
  74. LLVMMCJITCompilerOptions *PassedOptions,
  75. size_t SizeOfPassedOptions, char **OutError)
  76. {
  77. LLVMMCJITCompilerOptions options;
  78. // If the user passed a larger sized options struct, then they were compiled
  79. // against a newer LLVM. Tell them that something is wrong.
  80. if (SizeOfPassedOptions > sizeof(options)) {
  81. *OutError = strdup("Refusing to use options struct that is larger than "
  82. "my own; assuming LLVM library mismatch.");
  83. return 1;
  84. }
  85. // Defend against the user having an old version of the API by ensuring that
  86. // any fields they didn't see are cleared. We must defend against fields
  87. // being set to the bitwise equivalent of zero, and assume that this means
  88. // "do the default" as if that option hadn't been available.
  89. LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
  90. memcpy(&options, PassedOptions, SizeOfPassedOptions);
  91. TargetOptions targetOptions;
  92. targetOptions.EnableFastISel = options.EnableFastISel;
  93. std::unique_ptr<Module> Mod(unwrap(M));
  94. if (Mod) {
  95. // Set function attribute "frame-pointer" based on
  96. // NoFramePointerElim.
  97. for (auto &F : *Mod) {
  98. auto Attrs = F.getAttributes();
  99. StringRef Value = options.NoFramePointerElim ? "all" : "none";
  100. #if LLVM_VERSION_MAJOR <= 13
  101. Attrs =
  102. Attrs.addAttribute(F.getContext(), AttributeList::FunctionIndex,
  103. "frame-pointer", Value);
  104. #else
  105. Attrs = Attrs.addAttributeAtIndex(F.getContext(),
  106. AttributeList::FunctionIndex,
  107. "frame-pointer", Value);
  108. #endif
  109. F.setAttributes(Attrs);
  110. }
  111. }
  112. std::string Error;
  113. bool JIT;
  114. char *host_cpu = LLVMGetHostCPUName();
  115. if (!host_cpu) {
  116. *OutError = NULL;
  117. return false;
  118. }
  119. std::string mcpu(host_cpu);
  120. LLVMDisposeMessage(host_cpu);
  121. EngineBuilder builder(std::move(Mod));
  122. builder.setEngineKind(EngineKind::JIT)
  123. .setErrorStr(&Error)
  124. .setMCPU(mcpu)
  125. .setOptLevel((CodeGenOpt::Level)options.OptLevel)
  126. .setTargetOptions(targetOptions);
  127. if (Optional<CodeModel::Model> CM = unwrap(options.CodeModel, JIT))
  128. builder.setCodeModel(*CM);
  129. if (options.MCJMM)
  130. builder.setMCJITMemoryManager(
  131. std::unique_ptr<RTDyldMemoryManager>(unwrap(options.MCJMM)));
  132. if (ExecutionEngine *JIT = builder.create()) {
  133. *OutJIT = wrap(JIT);
  134. return 0;
  135. }
  136. *OutError = strdup(Error.c_str());
  137. return 1;
  138. }
  139. class ExpandMemoryOpPass : public llvm::ModulePass
  140. {
  141. public:
  142. static char ID;
  143. ExpandMemoryOpPass()
  144. : ModulePass(ID)
  145. {}
  146. bool runOnModule(Module &M) override;
  147. bool expandMemIntrinsicUses(Function &F);
  148. StringRef getPassName() const override
  149. {
  150. return "Expand memory operation intrinsics";
  151. }
  152. void getAnalysisUsage(AnalysisUsage &AU) const override
  153. {
  154. AU.addRequired<TargetTransformInfoWrapperPass>();
  155. }
  156. };
  157. char ExpandMemoryOpPass::ID = 0;
  158. bool
  159. ExpandMemoryOpPass::expandMemIntrinsicUses(Function &F)
  160. {
  161. Intrinsic::ID ID = F.getIntrinsicID();
  162. bool Changed = false;
  163. for (auto I = F.user_begin(), E = F.user_end(); I != E;) {
  164. Instruction *Inst = cast<Instruction>(*I);
  165. ++I;
  166. switch (ID) {
  167. case Intrinsic::memcpy:
  168. {
  169. auto *Memcpy = cast<MemCpyInst>(Inst);
  170. Function *ParentFunc = Memcpy->getParent()->getParent();
  171. const TargetTransformInfo &TTI =
  172. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  173. *ParentFunc);
  174. expandMemCpyAsLoop(Memcpy, TTI);
  175. Changed = true;
  176. Memcpy->eraseFromParent();
  177. break;
  178. }
  179. case Intrinsic::memmove:
  180. {
  181. auto *Memmove = cast<MemMoveInst>(Inst);
  182. expandMemMoveAsLoop(Memmove);
  183. Changed = true;
  184. Memmove->eraseFromParent();
  185. break;
  186. }
  187. case Intrinsic::memset:
  188. {
  189. auto *Memset = cast<MemSetInst>(Inst);
  190. expandMemSetAsLoop(Memset);
  191. Changed = true;
  192. Memset->eraseFromParent();
  193. break;
  194. }
  195. default:
  196. break;
  197. }
  198. }
  199. return Changed;
  200. }
  201. bool
  202. ExpandMemoryOpPass::runOnModule(Module &M)
  203. {
  204. bool Changed = false;
  205. for (Function &F : M) {
  206. if (!F.isDeclaration())
  207. continue;
  208. switch (F.getIntrinsicID()) {
  209. case Intrinsic::memcpy:
  210. case Intrinsic::memmove:
  211. case Intrinsic::memset:
  212. if (expandMemIntrinsicUses(F))
  213. Changed = true;
  214. break;
  215. default:
  216. break;
  217. }
  218. }
  219. return Changed;
  220. }
  221. void
  222. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass)
  223. {
  224. unwrap(pass)->add(new ExpandMemoryOpPass());
  225. }
  226. bool
  227. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str)
  228. {
  229. #if WASM_ENABLE_SIMD != 0
  230. if (!arch_c_str || !cpu_c_str) {
  231. return false;
  232. }
  233. llvm::SmallVector<std::string, 1> targetAttributes;
  234. llvm::Triple targetTriple(arch_c_str, "", "");
  235. auto targetMachine =
  236. std::unique_ptr<llvm::TargetMachine>(llvm::EngineBuilder().selectTarget(
  237. targetTriple, "", std::string(cpu_c_str), targetAttributes));
  238. if (!targetMachine) {
  239. return false;
  240. }
  241. const llvm::Triple::ArchType targetArch =
  242. targetMachine->getTargetTriple().getArch();
  243. const llvm::MCSubtargetInfo *subTargetInfo =
  244. targetMachine->getMCSubtargetInfo();
  245. if (subTargetInfo == nullptr) {
  246. return false;
  247. }
  248. if (targetArch == llvm::Triple::x86_64) {
  249. return subTargetInfo->checkFeatures("+sse4.1");
  250. }
  251. else if (targetArch == llvm::Triple::aarch64) {
  252. return subTargetInfo->checkFeatures("+neon");
  253. }
  254. else {
  255. return false;
  256. }
  257. #else
  258. (void)arch_c_str;
  259. (void)cpu_c_str;
  260. return true;
  261. #endif /* WASM_ENABLE_SIMD */
  262. }
  263. #if WASM_ENABLE_LAZY_JIT != 0
  264. #if LLVM_VERSION_MAJOR < 12
  265. LLVMOrcJITTargetMachineBuilderRef
  266. LLVMOrcJITTargetMachineBuilderFromTargetMachine(LLVMTargetMachineRef TM);
  267. LLVMOrcJITTargetMachineBuilderRef
  268. LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(LLVMTargetMachineRef TM)
  269. {
  270. return LLVMOrcJITTargetMachineBuilderFromTargetMachine(TM);
  271. }
  272. #endif
  273. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLJITBuilder, LLVMOrcLLJITBuilderRef)
  274. void
  275. LLVMOrcLLJITBuilderSetNumCompileThreads(LLVMOrcLLJITBuilderRef orcjit_builder,
  276. unsigned num_compile_threads)
  277. {
  278. unwrap(orcjit_builder)->setNumCompileThreads(num_compile_threads);
  279. }
  280. void *
  281. aot_lookup_orcjit_func(LLVMOrcLLJITRef orc_lazyjit, void *module_inst,
  282. uint32 func_idx)
  283. {
  284. char func_name[32], buf[128], *err_msg = NULL;
  285. LLVMErrorRef error;
  286. LLVMOrcJITTargetAddress func_addr = 0;
  287. AOTModuleInstance *aot_inst = (AOTModuleInstance *)module_inst;
  288. AOTModule *aot_module = (AOTModule *)aot_inst->aot_module.ptr;
  289. void **func_ptrs = (void **)aot_inst->func_ptrs.ptr;
  290. /**
  291. * No need to lock the func_ptr[func_idx] here as it is basic
  292. * data type, the load/store for it can be finished by one cpu
  293. * instruction, and there can be only one cpu instruction
  294. * loading/storing at the same time.
  295. */
  296. if (func_ptrs[func_idx])
  297. return func_ptrs[func_idx];
  298. snprintf(func_name, sizeof(func_name), "%s%d", AOT_FUNC_PREFIX,
  299. func_idx - aot_module->import_func_count);
  300. if ((error = LLVMOrcLLJITLookup(orc_lazyjit, &func_addr, func_name))) {
  301. err_msg = LLVMGetErrorMessage(error);
  302. snprintf(buf, sizeof(buf), "failed to lookup orcjit function: %s",
  303. err_msg);
  304. aot_set_exception(aot_inst, buf);
  305. LLVMDisposeErrorMessage(err_msg);
  306. return NULL;
  307. }
  308. func_ptrs[func_idx] = (void *)func_addr;
  309. return (void *)func_addr;
  310. }
  311. #endif /* end of WASM_ENABLE_LAZY_JIT != 0 */
  312. void
  313. aot_func_disable_tce(LLVMValueRef func)
  314. {
  315. Function *F = unwrap<Function>(func);
  316. auto Attrs = F->getAttributes();
  317. #if LLVM_VERSION_MAJOR <= 13
  318. Attrs = Attrs.addAttribute(F->getContext(), AttributeList::FunctionIndex,
  319. "disable-tail-calls", "true");
  320. #else
  321. Attrs =
  322. Attrs.addAttributeAtIndex(F->getContext(), AttributeList::FunctionIndex,
  323. "disable-tail-calls", "true");
  324. #endif
  325. F->setAttributes(Attrs);
  326. }
  327. #if LLVM_VERSION_MAJOR >= 12
  328. void
  329. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx)
  330. {
  331. Module *M;
  332. TargetMachine *TM = unwrap(comp_ctx->target_machine);
  333. bool disable_llvm_lto = false;
  334. LoopAnalysisManager LAM;
  335. FunctionAnalysisManager FAM;
  336. CGSCCAnalysisManager CGAM;
  337. ModuleAnalysisManager MAM;
  338. PipelineTuningOptions PTO;
  339. PTO.LoopVectorization = true;
  340. PTO.SLPVectorization = true;
  341. PTO.LoopUnrolling = true;
  342. #if LLVM_VERSION_MAJOR == 12
  343. PassBuilder PB(false, TM, PTO);
  344. #else
  345. PassBuilder PB(TM, PTO);
  346. #endif
  347. // Register the target library analysis directly and give it a
  348. // customized preset TLI.
  349. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  350. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  351. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  352. // Register the AA manager first so that our version is the one used.
  353. AAManager AA = PB.buildDefaultAAPipeline();
  354. FAM.registerPass([&] { return std::move(AA); });
  355. // Register all the basic analyses with the managers.
  356. PB.registerModuleAnalyses(MAM);
  357. PB.registerCGSCCAnalyses(CGAM);
  358. PB.registerFunctionAnalyses(FAM);
  359. PB.registerLoopAnalyses(LAM);
  360. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  361. ModulePassManager MPM;
  362. #if LLVM_VERSION_MAJOR <= 13
  363. PassBuilder::OptimizationLevel OL;
  364. switch (comp_ctx->opt_level) {
  365. case 0:
  366. OL = PassBuilder::OptimizationLevel::O0;
  367. break;
  368. case 1:
  369. OL = PassBuilder::OptimizationLevel::O1;
  370. break;
  371. case 2:
  372. OL = PassBuilder::OptimizationLevel::O2;
  373. break;
  374. case 3:
  375. default:
  376. OL = PassBuilder::OptimizationLevel::O3;
  377. break;
  378. }
  379. #else
  380. OptimizationLevel OL;
  381. switch (comp_ctx->opt_level) {
  382. case 0:
  383. OL = OptimizationLevel::O0;
  384. break;
  385. case 1:
  386. OL = OptimizationLevel::O1;
  387. break;
  388. case 2:
  389. OL = OptimizationLevel::O2;
  390. break;
  391. case 3:
  392. default:
  393. OL = OptimizationLevel::O3;
  394. break;
  395. }
  396. #endif /* end of LLVM_VERSION_MAJOR */
  397. if (comp_ctx->disable_llvm_lto) {
  398. disable_llvm_lto = true;
  399. }
  400. #if WASM_ENABLE_SPEC_TEST != 0
  401. disable_llvm_lto = true;
  402. #endif
  403. if (disable_llvm_lto) {
  404. uint32 i;
  405. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  406. aot_func_disable_tce(comp_ctx->func_ctxes[i]->func);
  407. }
  408. }
  409. if (comp_ctx->is_jit_mode) {
  410. /* Apply normal pipeline for JIT mode, without
  411. Vectorize related passes, without LTO */
  412. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  413. }
  414. else {
  415. FunctionPassManager FPM;
  416. /* Apply Vectorize related passes for AOT mode */
  417. FPM.addPass(LoopVectorizePass());
  418. FPM.addPass(SLPVectorizerPass());
  419. FPM.addPass(LoadStoreVectorizerPass());
  420. /*
  421. FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
  422. FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
  423. FPM.addPass(createFunctionToLoopPassAdaptor(SimpleLoopUnswitchPass()));
  424. */
  425. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  426. if (!disable_llvm_lto) {
  427. /* Apply LTO for AOT mode */
  428. #if LLVM_VERSION_MAJOR < 14
  429. MPM.addPass(PB.buildLTODefaultPipeline(OL, NULL));
  430. #else
  431. MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(OL));
  432. #endif
  433. }
  434. else {
  435. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  436. }
  437. }
  438. #if WASM_ENABLE_LAZY_JIT == 0
  439. M = unwrap(comp_ctx->module);
  440. MPM.run(*M, MAM);
  441. #else
  442. uint32 i;
  443. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  444. M = unwrap(comp_ctx->modules[i]);
  445. MPM.run(*M, MAM);
  446. }
  447. #endif
  448. }
  449. #endif /* end of LLVM_VERSION_MAJOR >= 12 */