aot_llvm_extra.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <llvm/Passes/StandardInstrumentations.h>
  6. #include <llvm/Support/Error.h>
  7. #include <llvm/ADT/None.h>
  8. #include <llvm/ADT/Optional.h>
  9. #include <llvm/ADT/SmallVector.h>
  10. #include <llvm/ADT/Twine.h>
  11. #include <llvm/ADT/Triple.h>
  12. #include <llvm/Analysis/TargetTransformInfo.h>
  13. #include <llvm/CodeGen/TargetPassConfig.h>
  14. #include <llvm/ExecutionEngine/ExecutionEngine.h>
  15. #include <llvm/MC/MCSubtargetInfo.h>
  16. #include <llvm/Support/TargetSelect.h>
  17. #include <llvm/Target/TargetMachine.h>
  18. #include <llvm-c/Core.h>
  19. #include <llvm-c/ExecutionEngine.h>
  20. #include <llvm-c/Initialization.h>
  21. #include <llvm/ExecutionEngine/GenericValue.h>
  22. #include <llvm/ExecutionEngine/JITEventListener.h>
  23. #include <llvm/ExecutionEngine/RTDyldMemoryManager.h>
  24. #include <llvm/ExecutionEngine/Orc/LLJIT.h>
  25. #include <llvm/IR/DerivedTypes.h>
  26. #include <llvm/IR/Module.h>
  27. #include <llvm/IR/Instructions.h>
  28. #include <llvm/IR/IntrinsicInst.h>
  29. #include <llvm/IR/PassManager.h>
  30. #include <llvm/Support/CommandLine.h>
  31. #include <llvm/Support/ErrorHandling.h>
  32. #include <llvm/Target/CodeGenCWrappers.h>
  33. #include <llvm/Target/TargetMachine.h>
  34. #include <llvm/Target/TargetOptions.h>
  35. #include <llvm/Transforms/Utils/LowerMemIntrinsics.h>
  36. #include <llvm/Transforms/Vectorize/LoopVectorize.h>
  37. #include <llvm/Transforms/Vectorize/LoadStoreVectorizer.h>
  38. #include <llvm/Transforms/Vectorize/SLPVectorizer.h>
  39. #include <llvm/Transforms/Scalar/LoopRotation.h>
  40. #include <llvm/Transforms/Scalar/SimpleLoopUnswitch.h>
  41. #include <llvm/Transforms/Scalar/LICM.h>
  42. #include <llvm/Transforms/Scalar/GVN.h>
  43. #include <llvm/Passes/PassBuilder.h>
  44. #include <llvm/Analysis/TargetLibraryInfo.h>
  45. #if LLVM_VERSION_MAJOR >= 12
  46. #include <llvm/Analysis/AliasAnalysis.h>
  47. #endif
  48. #include <llvm/ProfileData/InstrProf.h>
  49. #include <cstring>
  50. #include "../aot/aot_runtime.h"
  51. #include "aot_llvm.h"
  52. using namespace llvm;
  53. using namespace llvm::orc;
  54. LLVM_C_EXTERN_C_BEGIN
  55. bool
  56. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str);
  57. void
  58. aot_add_expand_memory_op_pass(LLVMPassManagerRef pass);
  59. void
  60. aot_add_simple_loop_unswitch_pass(LLVMPassManagerRef pass);
  61. void
  62. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module);
  63. LLVM_C_EXTERN_C_END
  64. ExitOnError ExitOnErr;
  65. class ExpandMemoryOpPass : public PassInfoMixin<ExpandMemoryOpPass>
  66. {
  67. public:
  68. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  69. };
  70. PreservedAnalyses
  71. ExpandMemoryOpPass::run(Function &F, FunctionAnalysisManager &AM)
  72. {
  73. SmallVector<MemIntrinsic *, 16> MemCalls;
  74. /* Iterate over all instructions in the function, looking for memcpy,
  75. * memmove, and memset. When we find one, expand it into a loop. */
  76. for (auto &BB : F) {
  77. for (auto &Inst : BB) {
  78. if (auto *Memcpy = dyn_cast_or_null<MemCpyInst>(&Inst)) {
  79. MemCalls.push_back(Memcpy);
  80. }
  81. else if (auto *Memmove = dyn_cast_or_null<MemMoveInst>(&Inst)) {
  82. MemCalls.push_back(Memmove);
  83. }
  84. else if (auto *Memset = dyn_cast_or_null<MemSetInst>(&Inst)) {
  85. MemCalls.push_back(Memset);
  86. }
  87. }
  88. }
  89. for (MemIntrinsic *MemCall : MemCalls) {
  90. if (MemCpyInst *Memcpy = dyn_cast<MemCpyInst>(MemCall)) {
  91. Function *ParentFunc = Memcpy->getParent()->getParent();
  92. const TargetTransformInfo &TTI =
  93. AM.getResult<TargetIRAnalysis>(*ParentFunc);
  94. expandMemCpyAsLoop(Memcpy, TTI);
  95. Memcpy->eraseFromParent();
  96. }
  97. else if (MemMoveInst *Memmove = dyn_cast<MemMoveInst>(MemCall)) {
  98. expandMemMoveAsLoop(Memmove);
  99. Memmove->eraseFromParent();
  100. }
  101. else if (MemSetInst *Memset = dyn_cast<MemSetInst>(MemCall)) {
  102. expandMemSetAsLoop(Memset);
  103. Memset->eraseFromParent();
  104. }
  105. }
  106. PreservedAnalyses PA;
  107. PA.preserveSet<CFGAnalyses>();
  108. return PA;
  109. }
  110. bool
  111. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str)
  112. {
  113. #if WASM_ENABLE_SIMD != 0
  114. if (!arch_c_str || !cpu_c_str) {
  115. return false;
  116. }
  117. llvm::SmallVector<std::string, 1> targetAttributes;
  118. llvm::Triple targetTriple(arch_c_str, "", "");
  119. auto targetMachine =
  120. std::unique_ptr<llvm::TargetMachine>(llvm::EngineBuilder().selectTarget(
  121. targetTriple, "", std::string(cpu_c_str), targetAttributes));
  122. if (!targetMachine) {
  123. return false;
  124. }
  125. const llvm::Triple::ArchType targetArch =
  126. targetMachine->getTargetTriple().getArch();
  127. const llvm::MCSubtargetInfo *subTargetInfo =
  128. targetMachine->getMCSubtargetInfo();
  129. if (subTargetInfo == nullptr) {
  130. return false;
  131. }
  132. if (targetArch == llvm::Triple::x86_64) {
  133. return subTargetInfo->checkFeatures("+sse4.1");
  134. }
  135. else if (targetArch == llvm::Triple::aarch64) {
  136. return subTargetInfo->checkFeatures("+neon");
  137. }
  138. else {
  139. return false;
  140. }
  141. #else
  142. (void)arch_c_str;
  143. (void)cpu_c_str;
  144. return true;
  145. #endif /* WASM_ENABLE_SIMD */
  146. }
  147. void
  148. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module)
  149. {
  150. TargetMachine *TM =
  151. reinterpret_cast<TargetMachine *>(comp_ctx->target_machine);
  152. PipelineTuningOptions PTO;
  153. PTO.LoopVectorization = true;
  154. PTO.SLPVectorization = true;
  155. PTO.LoopUnrolling = true;
  156. #if LLVM_VERSION_MAJOR >= 16
  157. Optional<PGOOptions> PGO = std::nullopt;
  158. #else
  159. Optional<PGOOptions> PGO = llvm::None;
  160. #endif
  161. if (comp_ctx->enable_llvm_pgo) {
  162. /* Disable static counter allocation for value profiler,
  163. it will be allocated by runtime */
  164. const char *argv[] = { "", "-vp-static-alloc=false" };
  165. cl::ParseCommandLineOptions(2, argv);
  166. PGO = PGOOptions("", "", "", PGOOptions::IRInstr);
  167. }
  168. else if (comp_ctx->use_prof_file) {
  169. PGO = PGOOptions(comp_ctx->use_prof_file, "", "", PGOOptions::IRUse);
  170. }
  171. #ifdef DEBUG_PASS
  172. PassInstrumentationCallbacks PIC;
  173. PassBuilder PB(TM, PTO, PGO, &PIC);
  174. #else
  175. #if LLVM_VERSION_MAJOR == 12
  176. PassBuilder PB(false, TM, PTO, PGO);
  177. #else
  178. PassBuilder PB(TM, PTO, PGO);
  179. #endif
  180. #endif
  181. /* Register all the basic analyses with the managers */
  182. LoopAnalysisManager LAM;
  183. FunctionAnalysisManager FAM;
  184. CGSCCAnalysisManager CGAM;
  185. ModuleAnalysisManager MAM;
  186. /* Register the target library analysis directly and give it a
  187. customized preset TLI */
  188. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  189. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  190. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  191. /* Register the AA manager first so that our version is the one used */
  192. AAManager AA = PB.buildDefaultAAPipeline();
  193. FAM.registerPass([&] { return std::move(AA); });
  194. #ifdef DEBUG_PASS
  195. StandardInstrumentations SI(true, false);
  196. SI.registerCallbacks(PIC, &FAM);
  197. #endif
  198. PB.registerFunctionAnalyses(FAM);
  199. PB.registerLoopAnalyses(LAM);
  200. PB.registerModuleAnalyses(MAM);
  201. PB.registerCGSCCAnalyses(CGAM);
  202. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  203. #if LLVM_VERSION_MAJOR <= 13
  204. PassBuilder::OptimizationLevel OL;
  205. switch (comp_ctx->opt_level) {
  206. case 0:
  207. OL = PassBuilder::OptimizationLevel::O0;
  208. break;
  209. case 1:
  210. OL = PassBuilder::OptimizationLevel::O1;
  211. break;
  212. case 2:
  213. OL = PassBuilder::OptimizationLevel::O2;
  214. break;
  215. case 3:
  216. default:
  217. OL = PassBuilder::OptimizationLevel::O3;
  218. break;
  219. }
  220. #else
  221. OptimizationLevel OL;
  222. switch (comp_ctx->opt_level) {
  223. case 0:
  224. OL = OptimizationLevel::O0;
  225. break;
  226. case 1:
  227. OL = OptimizationLevel::O1;
  228. break;
  229. case 2:
  230. OL = OptimizationLevel::O2;
  231. break;
  232. case 3:
  233. default:
  234. OL = OptimizationLevel::O3;
  235. break;
  236. }
  237. #endif /* end of LLVM_VERSION_MAJOR */
  238. bool disable_llvm_lto = comp_ctx->disable_llvm_lto;
  239. #if WASM_ENABLE_SPEC_TEST != 0
  240. disable_llvm_lto = true;
  241. #endif
  242. Module *M = reinterpret_cast<Module *>(module);
  243. if (disable_llvm_lto) {
  244. for (Function &F : *M) {
  245. F.addFnAttr("disable-tail-calls", "true");
  246. }
  247. }
  248. ModulePassManager MPM;
  249. if (comp_ctx->is_jit_mode) {
  250. const char *Passes =
  251. "mem2reg,instcombine,simplifycfg,jump-threading,indvars";
  252. ExitOnErr(PB.parsePassPipeline(MPM, Passes));
  253. }
  254. else {
  255. FunctionPassManager FPM;
  256. /* Apply Vectorize related passes for AOT mode */
  257. FPM.addPass(LoopVectorizePass());
  258. FPM.addPass(SLPVectorizerPass());
  259. FPM.addPass(LoadStoreVectorizerPass());
  260. if (comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file) {
  261. /* LICM pass: loop invariant code motion, attempting to remove
  262. as much code from the body of a loop as possible. Experiments
  263. show it is good to enable it when pgo is enabled. */
  264. #if LLVM_VERSION_MAJOR >= 15
  265. LICMOptions licm_opt;
  266. FPM.addPass(
  267. createFunctionToLoopPassAdaptor(LICMPass(licm_opt), true));
  268. #else
  269. FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), true));
  270. #endif
  271. }
  272. /*
  273. FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
  274. FPM.addPass(createFunctionToLoopPassAdaptor(SimpleLoopUnswitchPass()));
  275. */
  276. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  277. if (comp_ctx->llvm_passes) {
  278. ExitOnErr(PB.parsePassPipeline(MPM, comp_ctx->llvm_passes));
  279. }
  280. if (!disable_llvm_lto) {
  281. /* Apply LTO for AOT mode */
  282. if (comp_ctx->comp_data->func_count >= 10
  283. || comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file)
  284. /* Add the pre-link optimizations if the func count
  285. is large enough or PGO is enabled */
  286. MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(OL));
  287. else
  288. MPM.addPass(PB.buildLTODefaultPipeline(OL, NULL));
  289. }
  290. else {
  291. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  292. }
  293. /* Run specific passes for AOT indirect mode in last since general
  294. optimization may create some intrinsic function calls like
  295. llvm.memset, so let's remove these function calls here. */
  296. if (comp_ctx->is_indirect_mode) {
  297. FunctionPassManager FPM1;
  298. FPM1.addPass(ExpandMemoryOpPass());
  299. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM1)));
  300. }
  301. }
  302. MPM.run(*M, MAM);
  303. }
  304. char *
  305. aot_compress_aot_func_names(AOTCompContext *comp_ctx, uint32 *p_size)
  306. {
  307. std::vector<std::string> NameStrs;
  308. std::string Result;
  309. char buf[32], *compressed_str;
  310. uint32 compressed_str_len, i;
  311. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  312. snprintf(buf, sizeof(buf), "%s%d", AOT_FUNC_PREFIX, i);
  313. std::string str(buf);
  314. NameStrs.push_back(str);
  315. }
  316. if (collectPGOFuncNameStrings(NameStrs, true, Result)) {
  317. aot_set_last_error("collect pgo func name strings failed");
  318. return NULL;
  319. }
  320. compressed_str_len = Result.size();
  321. if (!(compressed_str = (char *)wasm_runtime_malloc(compressed_str_len))) {
  322. aot_set_last_error("allocate memory failed");
  323. return NULL;
  324. }
  325. bh_memcpy_s(compressed_str, compressed_str_len, Result.c_str(),
  326. compressed_str_len);
  327. *p_size = compressed_str_len;
  328. return compressed_str;
  329. }