aot_llvm_extra.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. Intrinsic::ID ID = F.getIntrinsicID();
  74. bool Changed = false;
  75. for (auto I = F.user_begin(), E = F.user_end(); I != E;) {
  76. Instruction *Inst = cast<Instruction>(*I);
  77. ++I;
  78. switch (ID) {
  79. case Intrinsic::memcpy:
  80. {
  81. auto *Memcpy = cast<MemCpyInst>(Inst);
  82. Function *ParentFunc = Memcpy->getParent()->getParent();
  83. const TargetTransformInfo &TTI =
  84. AM.getResult<TargetIRAnalysis>(*ParentFunc);
  85. expandMemCpyAsLoop(Memcpy, TTI);
  86. Memcpy->eraseFromParent();
  87. Changed = true;
  88. break;
  89. }
  90. case Intrinsic::memmove:
  91. {
  92. auto *Memmove = cast<MemMoveInst>(Inst);
  93. expandMemMoveAsLoop(Memmove);
  94. Memmove->eraseFromParent();
  95. Changed = true;
  96. break;
  97. }
  98. case Intrinsic::memset:
  99. {
  100. auto *Memset = cast<MemSetInst>(Inst);
  101. expandMemSetAsLoop(Memset);
  102. Memset->eraseFromParent();
  103. Changed = true;
  104. break;
  105. }
  106. default:
  107. break;
  108. }
  109. }
  110. PreservedAnalyses PA;
  111. PA.preserveSet<CFGAnalyses>();
  112. return PA;
  113. }
  114. bool
  115. aot_check_simd_compatibility(const char *arch_c_str, const char *cpu_c_str)
  116. {
  117. #if WASM_ENABLE_SIMD != 0
  118. if (!arch_c_str || !cpu_c_str) {
  119. return false;
  120. }
  121. llvm::SmallVector<std::string, 1> targetAttributes;
  122. llvm::Triple targetTriple(arch_c_str, "", "");
  123. auto targetMachine =
  124. std::unique_ptr<llvm::TargetMachine>(llvm::EngineBuilder().selectTarget(
  125. targetTriple, "", std::string(cpu_c_str), targetAttributes));
  126. if (!targetMachine) {
  127. return false;
  128. }
  129. const llvm::Triple::ArchType targetArch =
  130. targetMachine->getTargetTriple().getArch();
  131. const llvm::MCSubtargetInfo *subTargetInfo =
  132. targetMachine->getMCSubtargetInfo();
  133. if (subTargetInfo == nullptr) {
  134. return false;
  135. }
  136. if (targetArch == llvm::Triple::x86_64) {
  137. return subTargetInfo->checkFeatures("+sse4.1");
  138. }
  139. else if (targetArch == llvm::Triple::aarch64) {
  140. return subTargetInfo->checkFeatures("+neon");
  141. }
  142. else {
  143. return false;
  144. }
  145. #else
  146. (void)arch_c_str;
  147. (void)cpu_c_str;
  148. return true;
  149. #endif /* WASM_ENABLE_SIMD */
  150. }
  151. void
  152. aot_apply_llvm_new_pass_manager(AOTCompContext *comp_ctx, LLVMModuleRef module)
  153. {
  154. TargetMachine *TM =
  155. reinterpret_cast<TargetMachine *>(comp_ctx->target_machine);
  156. PipelineTuningOptions PTO;
  157. PTO.LoopVectorization = true;
  158. PTO.SLPVectorization = true;
  159. PTO.LoopUnrolling = true;
  160. #if LLVM_VERSION_MAJOR >= 16
  161. Optional<PGOOptions> PGO = std::nullopt;
  162. #else
  163. Optional<PGOOptions> PGO = llvm::None;
  164. #endif
  165. if (comp_ctx->enable_llvm_pgo) {
  166. /* Disable static counter allocation for value profiler,
  167. it will be allocated by runtime */
  168. const char *argv[] = { "", "-vp-static-alloc=false" };
  169. cl::ParseCommandLineOptions(2, argv);
  170. PGO = PGOOptions("", "", "", PGOOptions::IRInstr);
  171. }
  172. else if (comp_ctx->use_prof_file) {
  173. PGO = PGOOptions(comp_ctx->use_prof_file, "", "", PGOOptions::IRUse);
  174. }
  175. #ifdef DEBUG_PASS
  176. PassInstrumentationCallbacks PIC;
  177. PassBuilder PB(TM, PTO, PGO, &PIC);
  178. #else
  179. #if LLVM_VERSION_MAJOR == 12
  180. PassBuilder PB(false, TM, PTO, PGO);
  181. #else
  182. PassBuilder PB(TM, PTO, PGO);
  183. #endif
  184. #endif
  185. /* Register all the basic analyses with the managers */
  186. LoopAnalysisManager LAM;
  187. FunctionAnalysisManager FAM;
  188. CGSCCAnalysisManager CGAM;
  189. ModuleAnalysisManager MAM;
  190. /* Register the target library analysis directly and give it a
  191. customized preset TLI */
  192. std::unique_ptr<TargetLibraryInfoImpl> TLII(
  193. new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
  194. FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
  195. /* Register the AA manager first so that our version is the one used */
  196. AAManager AA = PB.buildDefaultAAPipeline();
  197. FAM.registerPass([&] { return std::move(AA); });
  198. #ifdef DEBUG_PASS
  199. StandardInstrumentations SI(true, false);
  200. SI.registerCallbacks(PIC, &FAM);
  201. #endif
  202. PB.registerFunctionAnalyses(FAM);
  203. PB.registerLoopAnalyses(LAM);
  204. PB.registerModuleAnalyses(MAM);
  205. PB.registerCGSCCAnalyses(CGAM);
  206. PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
  207. #if LLVM_VERSION_MAJOR <= 13
  208. PassBuilder::OptimizationLevel OL;
  209. switch (comp_ctx->opt_level) {
  210. case 0:
  211. OL = PassBuilder::OptimizationLevel::O0;
  212. break;
  213. case 1:
  214. OL = PassBuilder::OptimizationLevel::O1;
  215. break;
  216. case 2:
  217. OL = PassBuilder::OptimizationLevel::O2;
  218. break;
  219. case 3:
  220. default:
  221. OL = PassBuilder::OptimizationLevel::O3;
  222. break;
  223. }
  224. #else
  225. OptimizationLevel OL;
  226. switch (comp_ctx->opt_level) {
  227. case 0:
  228. OL = OptimizationLevel::O0;
  229. break;
  230. case 1:
  231. OL = OptimizationLevel::O1;
  232. break;
  233. case 2:
  234. OL = OptimizationLevel::O2;
  235. break;
  236. case 3:
  237. default:
  238. OL = OptimizationLevel::O3;
  239. break;
  240. }
  241. #endif /* end of LLVM_VERSION_MAJOR */
  242. bool disable_llvm_lto = comp_ctx->disable_llvm_lto;
  243. #if WASM_ENABLE_SPEC_TEST != 0
  244. disable_llvm_lto = true;
  245. #endif
  246. Module *M = reinterpret_cast<Module *>(module);
  247. if (disable_llvm_lto) {
  248. for (Function &F : *M) {
  249. F.addFnAttr("disable-tail-calls", "true");
  250. }
  251. }
  252. ModulePassManager MPM;
  253. if (comp_ctx->is_jit_mode) {
  254. const char *Passes =
  255. "mem2reg,instcombine,simplifycfg,jump-threading,indvars";
  256. ExitOnErr(PB.parsePassPipeline(MPM, Passes));
  257. }
  258. else {
  259. FunctionPassManager FPM;
  260. /* Apply Vectorize related passes for AOT mode */
  261. FPM.addPass(LoopVectorizePass());
  262. FPM.addPass(SLPVectorizerPass());
  263. FPM.addPass(LoadStoreVectorizerPass());
  264. /* Run specific passes for AOT indirect mode in last since general
  265. optimization may create some intrinsic function calls like
  266. llvm.memset, so let's remove these function calls here. */
  267. if (comp_ctx->is_indirect_mode) {
  268. FPM.addPass(ExpandMemoryOpPass());
  269. }
  270. if (comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file) {
  271. /* LICM pass: loop invariant code motion, attempting to remove
  272. as much code from the body of a loop as possible. Experiments
  273. show it is good to enable it when pgo is enabled. */
  274. #if LLVM_VERSION_MAJOR >= 15
  275. LICMOptions licm_opt;
  276. FPM.addPass(
  277. createFunctionToLoopPassAdaptor(LICMPass(licm_opt), true));
  278. #else
  279. FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), true));
  280. #endif
  281. }
  282. /*
  283. FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
  284. FPM.addPass(createFunctionToLoopPassAdaptor(SimpleLoopUnswitchPass()));
  285. */
  286. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  287. if (comp_ctx->llvm_passes) {
  288. ExitOnErr(PB.parsePassPipeline(MPM, comp_ctx->llvm_passes));
  289. }
  290. if (!disable_llvm_lto) {
  291. /* Apply LTO for AOT mode */
  292. if (comp_ctx->comp_data->func_count >= 10
  293. || comp_ctx->enable_llvm_pgo || comp_ctx->use_prof_file)
  294. /* Add the pre-link optimizations if the func count
  295. is large enough or PGO is enabled */
  296. MPM.addPass(PB.buildLTOPreLinkDefaultPipeline(OL));
  297. else
  298. MPM.addPass(PB.buildLTODefaultPipeline(OL, NULL));
  299. }
  300. else {
  301. MPM.addPass(PB.buildPerModuleDefaultPipeline(OL));
  302. }
  303. }
  304. MPM.run(*M, MAM);
  305. }
  306. char *
  307. aot_compress_aot_func_names(AOTCompContext *comp_ctx, uint32 *p_size)
  308. {
  309. std::vector<std::string> NameStrs;
  310. std::string Result;
  311. char buf[32], *compressed_str;
  312. uint32 compressed_str_len, i;
  313. for (i = 0; i < comp_ctx->func_ctx_count; i++) {
  314. snprintf(buf, sizeof(buf), "%s%d", AOT_FUNC_PREFIX, i);
  315. std::string str(buf);
  316. NameStrs.push_back(str);
  317. }
  318. if (collectPGOFuncNameStrings(NameStrs, true, Result)) {
  319. aot_set_last_error("collect pgo func name strings failed");
  320. return NULL;
  321. }
  322. compressed_str_len = Result.size();
  323. if (!(compressed_str = (char *)wasm_runtime_malloc(compressed_str_len))) {
  324. aot_set_last_error("allocate memory failed");
  325. return NULL;
  326. }
  327. bh_memcpy_s(compressed_str, compressed_str_len, Result.c_str(),
  328. compressed_str_len);
  329. *p_size = compressed_str_len;
  330. return compressed_str;
  331. }