aot_llvm.c 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "aot_llvm.h"
  6. #include "aot_compiler.h"
  7. #include "aot_emit_exception.h"
  8. #include "../aot/aot_runtime.h"
  9. #include "../aot/aot_intrinsic.h"
  10. #if WASM_ENABLE_DEBUG_AOT != 0
  11. #include "debug/dwarf_extractor.h"
  12. #endif
  13. LLVMTypeRef
  14. wasm_type_to_llvm_type(AOTLLVMTypes *llvm_types, uint8 wasm_type)
  15. {
  16. switch (wasm_type) {
  17. case VALUE_TYPE_I32:
  18. case VALUE_TYPE_FUNCREF:
  19. case VALUE_TYPE_EXTERNREF:
  20. return llvm_types->int32_type;
  21. case VALUE_TYPE_I64:
  22. return llvm_types->int64_type;
  23. case VALUE_TYPE_F32:
  24. return llvm_types->float32_type;
  25. case VALUE_TYPE_F64:
  26. return llvm_types->float64_type;
  27. case VALUE_TYPE_V128:
  28. return llvm_types->i64x2_vec_type;
  29. case VALUE_TYPE_VOID:
  30. return llvm_types->void_type;
  31. default:
  32. break;
  33. }
  34. return NULL;
  35. }
  36. /**
  37. * Add LLVM function
  38. */
  39. static LLVMValueRef
  40. aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module,
  41. AOTFuncType *aot_func_type, uint32 func_index,
  42. LLVMTypeRef *p_func_type)
  43. {
  44. LLVMValueRef func = NULL;
  45. LLVMTypeRef *param_types, ret_type, func_type;
  46. LLVMValueRef local_value;
  47. char func_name[32];
  48. uint64 size;
  49. uint32 i, j = 0, param_count = (uint64)aot_func_type->param_count;
  50. /* exec env as first parameter */
  51. param_count++;
  52. /* Extra wasm function results(except the first one)'s address are
  53. * appended to aot function parameters. */
  54. if (aot_func_type->result_count > 1)
  55. param_count += aot_func_type->result_count - 1;
  56. /* Initialize parameter types of the LLVM function */
  57. size = sizeof(LLVMTypeRef) * ((uint64)param_count);
  58. if (size >= UINT32_MAX
  59. || !(param_types = wasm_runtime_malloc((uint32)size))) {
  60. aot_set_last_error("allocate memory failed.");
  61. return NULL;
  62. }
  63. /* exec env as first parameter */
  64. param_types[j++] = comp_ctx->exec_env_type;
  65. for (i = 0; i < aot_func_type->param_count; i++)
  66. param_types[j++] = TO_LLVM_TYPE(aot_func_type->types[i]);
  67. /* Extra results' address */
  68. for (i = 1; i < aot_func_type->result_count; i++, j++) {
  69. param_types[j] =
  70. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count + i]);
  71. if (!(param_types[j] = LLVMPointerType(param_types[j], 0))) {
  72. aot_set_last_error("llvm get pointer type failed.");
  73. goto fail;
  74. }
  75. }
  76. /* Resolve return type of the LLVM function */
  77. if (aot_func_type->result_count)
  78. ret_type =
  79. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count]);
  80. else
  81. ret_type = VOID_TYPE;
  82. /* Resolve function prototype */
  83. if (!(func_type =
  84. LLVMFunctionType(ret_type, param_types, param_count, false))) {
  85. aot_set_last_error("create LLVM function type failed.");
  86. goto fail;
  87. }
  88. /* Add LLVM function */
  89. snprintf(func_name, sizeof(func_name), "%s%d", AOT_FUNC_PREFIX, func_index);
  90. if (!(func = LLVMAddFunction(module, func_name, func_type))) {
  91. aot_set_last_error("add LLVM function failed.");
  92. goto fail;
  93. }
  94. j = 0;
  95. local_value = LLVMGetParam(func, j++);
  96. LLVMSetValueName(local_value, "exec_env");
  97. /* Set parameter names */
  98. for (i = 0; i < aot_func_type->param_count; i++) {
  99. local_value = LLVMGetParam(func, j++);
  100. LLVMSetValueName(local_value, "");
  101. }
  102. if (p_func_type)
  103. *p_func_type = func_type;
  104. fail:
  105. wasm_runtime_free(param_types);
  106. return func;
  107. }
  108. static void
  109. free_block_memory(AOTBlock *block)
  110. {
  111. if (block->param_types)
  112. wasm_runtime_free(block->param_types);
  113. if (block->result_types)
  114. wasm_runtime_free(block->result_types);
  115. wasm_runtime_free(block);
  116. }
  117. /**
  118. * Create first AOTBlock, or function block for the function
  119. */
  120. static AOTBlock *
  121. aot_create_func_block(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  122. AOTFunc *func, AOTFuncType *aot_func_type)
  123. {
  124. AOTBlock *aot_block;
  125. uint32 param_count = aot_func_type->param_count,
  126. result_count = aot_func_type->result_count;
  127. /* Allocate memory */
  128. if (!(aot_block = wasm_runtime_malloc(sizeof(AOTBlock)))) {
  129. aot_set_last_error("allocate memory failed.");
  130. return NULL;
  131. }
  132. memset(aot_block, 0, sizeof(AOTBlock));
  133. if (param_count
  134. && !(aot_block->param_types = wasm_runtime_malloc(param_count))) {
  135. aot_set_last_error("allocate memory failed.");
  136. goto fail;
  137. }
  138. if (result_count) {
  139. if (!(aot_block->result_types = wasm_runtime_malloc(result_count))) {
  140. aot_set_last_error("allocate memory failed.");
  141. goto fail;
  142. }
  143. }
  144. /* Set block data */
  145. aot_block->label_type = LABEL_TYPE_FUNCTION;
  146. aot_block->param_count = param_count;
  147. if (param_count) {
  148. bh_memcpy_s(aot_block->param_types, param_count, aot_func_type->types,
  149. param_count);
  150. }
  151. aot_block->result_count = result_count;
  152. if (result_count) {
  153. bh_memcpy_s(aot_block->result_types, result_count,
  154. aot_func_type->types + param_count, result_count);
  155. }
  156. aot_block->wasm_code_end = func->code + func->code_size;
  157. /* Add function entry block */
  158. if (!(aot_block->llvm_entry_block = LLVMAppendBasicBlockInContext(
  159. comp_ctx->context, func_ctx->func, "func_begin"))) {
  160. aot_set_last_error("add LLVM basic block failed.");
  161. goto fail;
  162. }
  163. return aot_block;
  164. fail:
  165. free_block_memory(aot_block);
  166. return NULL;
  167. }
  168. static bool
  169. create_memory_info(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  170. LLVMTypeRef int8_ptr_type, uint32 func_index)
  171. {
  172. LLVMValueRef offset, mem_info_base;
  173. uint32 memory_count;
  174. WASMModule *module = comp_ctx->comp_data->wasm_module;
  175. WASMFunction *func = module->functions[func_index];
  176. LLVMTypeRef bound_check_type;
  177. bool mem_space_unchanged =
  178. (!func->has_op_memory_grow && !func->has_op_func_call)
  179. || (!module->possible_memory_grow);
  180. #if WASM_ENABLE_SHARED_MEMORY != 0
  181. bool is_shared_memory;
  182. #endif
  183. func_ctx->mem_space_unchanged = mem_space_unchanged;
  184. memory_count = module->memory_count + module->import_memory_count;
  185. /* If the module dosen't have memory, reserve
  186. one mem_info space with empty content */
  187. if (memory_count == 0)
  188. memory_count = 1;
  189. if (!(func_ctx->mem_info =
  190. wasm_runtime_malloc(sizeof(AOTMemInfo) * memory_count))) {
  191. return false;
  192. }
  193. memset(func_ctx->mem_info, 0, sizeof(AOTMemInfo));
  194. /* Currently we only create memory info for memory 0 */
  195. /* Load memory base address */
  196. #if WASM_ENABLE_SHARED_MEMORY != 0
  197. is_shared_memory =
  198. comp_ctx->comp_data->memories[0].memory_flags & 0x02 ? true : false;
  199. if (is_shared_memory) {
  200. LLVMValueRef shared_mem_addr;
  201. offset = I32_CONST(offsetof(AOTModuleInstance, memories));
  202. if (!offset) {
  203. aot_set_last_error("create llvm const failed.");
  204. return false;
  205. }
  206. /* aot_inst->memories */
  207. if (!(shared_mem_addr =
  208. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  209. &offset, 1, "shared_mem_addr_offset"))) {
  210. aot_set_last_error("llvm build in bounds gep failed");
  211. return false;
  212. }
  213. if (!(shared_mem_addr =
  214. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  215. int8_ptr_type, "shared_mem_addr_ptr"))) {
  216. aot_set_last_error("llvm build bit cast failed");
  217. return false;
  218. }
  219. /* aot_inst->memories[0] */
  220. if (!(shared_mem_addr = LLVMBuildLoad(
  221. comp_ctx->builder, shared_mem_addr, "shared_mem_addr"))) {
  222. aot_set_last_error("llvm build load failed");
  223. return false;
  224. }
  225. if (!(shared_mem_addr =
  226. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  227. int8_ptr_type, "shared_mem_addr_ptr"))) {
  228. aot_set_last_error("llvm build bit cast failed");
  229. return false;
  230. }
  231. if (!(shared_mem_addr = LLVMBuildLoad(
  232. comp_ctx->builder, shared_mem_addr, "shared_mem_addr"))) {
  233. aot_set_last_error("llvm build load failed");
  234. return false;
  235. }
  236. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data.ptr));
  237. if (!(func_ctx->mem_info[0].mem_base_addr =
  238. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  239. &offset, 1, "mem_base_addr_offset"))) {
  240. aot_set_last_error("llvm build in bounds gep failed");
  241. return false;
  242. }
  243. offset = I32_CONST(offsetof(AOTMemoryInstance, cur_page_count));
  244. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  245. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  246. &offset, 1, "mem_cur_page_offset"))) {
  247. aot_set_last_error("llvm build in bounds gep failed");
  248. return false;
  249. }
  250. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data_size));
  251. if (!(func_ctx->mem_info[0].mem_data_size_addr =
  252. LLVMBuildInBoundsGEP(comp_ctx->builder, shared_mem_addr,
  253. &offset, 1, "mem_data_size_offset"))) {
  254. aot_set_last_error("llvm build in bounds gep failed");
  255. return false;
  256. }
  257. }
  258. else
  259. #endif
  260. {
  261. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  262. + offsetof(AOTMemoryInstance, memory_data.ptr));
  263. if (!(func_ctx->mem_info[0].mem_base_addr =
  264. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  265. &offset, 1, "mem_base_addr_offset"))) {
  266. aot_set_last_error("llvm build in bounds gep failed");
  267. return false;
  268. }
  269. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  270. + offsetof(AOTMemoryInstance, cur_page_count));
  271. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  272. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  273. &offset, 1, "mem_cur_page_offset"))) {
  274. aot_set_last_error("llvm build in bounds gep failed");
  275. return false;
  276. }
  277. offset = I32_CONST(offsetof(AOTModuleInstance, global_table_data)
  278. + offsetof(AOTMemoryInstance, memory_data_size));
  279. if (!(func_ctx->mem_info[0].mem_data_size_addr =
  280. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst,
  281. &offset, 1, "mem_data_size_offset"))) {
  282. aot_set_last_error("llvm build in bounds gep failed");
  283. return false;
  284. }
  285. }
  286. /* Store mem info base address before cast */
  287. mem_info_base = func_ctx->mem_info[0].mem_base_addr;
  288. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildBitCast(
  289. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  290. int8_ptr_type, "mem_base_addr_ptr"))) {
  291. aot_set_last_error("llvm build bit cast failed");
  292. return false;
  293. }
  294. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr = LLVMBuildBitCast(
  295. comp_ctx->builder, func_ctx->mem_info[0].mem_cur_page_count_addr,
  296. INT32_PTR_TYPE, "mem_cur_page_ptr"))) {
  297. aot_set_last_error("llvm build bit cast failed");
  298. return false;
  299. }
  300. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildBitCast(
  301. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  302. INT32_PTR_TYPE, "mem_data_size_ptr"))) {
  303. aot_set_last_error("llvm build bit cast failed");
  304. return false;
  305. }
  306. if (mem_space_unchanged) {
  307. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad(
  308. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  309. "mem_base_addr"))) {
  310. aot_set_last_error("llvm build load failed");
  311. return false;
  312. }
  313. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  314. LLVMBuildLoad(comp_ctx->builder,
  315. func_ctx->mem_info[0].mem_cur_page_count_addr,
  316. "mem_cur_page_count"))) {
  317. aot_set_last_error("llvm build load failed");
  318. return false;
  319. }
  320. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildLoad(
  321. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  322. "mem_data_size"))) {
  323. aot_set_last_error("llvm build load failed");
  324. return false;
  325. }
  326. }
  327. #if WASM_ENABLE_SHARED_MEMORY != 0
  328. else if (is_shared_memory) {
  329. /* The base address for shared memory will never changed,
  330. we can load the value here */
  331. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad(
  332. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  333. "mem_base_addr"))) {
  334. aot_set_last_error("llvm build load failed");
  335. return false;
  336. }
  337. }
  338. #endif
  339. bound_check_type = (comp_ctx->pointer_size == sizeof(uint64))
  340. ? INT64_PTR_TYPE
  341. : INT32_PTR_TYPE;
  342. /* Load memory bound check constants */
  343. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_1byte)
  344. - offsetof(AOTMemoryInstance, memory_data.ptr));
  345. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  346. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  347. "bound_check_1byte_offset"))) {
  348. aot_set_last_error("llvm build in bounds gep failed");
  349. return false;
  350. }
  351. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildBitCast(
  352. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_1byte,
  353. bound_check_type, "bound_check_1byte_ptr"))) {
  354. aot_set_last_error("llvm build bit cast failed");
  355. return false;
  356. }
  357. if (mem_space_unchanged) {
  358. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  359. LLVMBuildLoad(comp_ctx->builder,
  360. func_ctx->mem_info[0].mem_bound_check_1byte,
  361. "bound_check_1byte"))) {
  362. aot_set_last_error("llvm build load failed");
  363. return false;
  364. }
  365. }
  366. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_2bytes)
  367. - offsetof(AOTMemoryInstance, memory_data.ptr));
  368. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  369. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  370. "bound_check_2bytes_offset"))) {
  371. aot_set_last_error("llvm build in bounds gep failed");
  372. return false;
  373. }
  374. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildBitCast(
  375. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_2bytes,
  376. bound_check_type, "bound_check_2bytes_ptr"))) {
  377. aot_set_last_error("llvm build bit cast failed");
  378. return false;
  379. }
  380. if (mem_space_unchanged) {
  381. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  382. LLVMBuildLoad(comp_ctx->builder,
  383. func_ctx->mem_info[0].mem_bound_check_2bytes,
  384. "bound_check_2bytes"))) {
  385. aot_set_last_error("llvm build load failed");
  386. return false;
  387. }
  388. }
  389. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_4bytes)
  390. - offsetof(AOTMemoryInstance, memory_data.ptr));
  391. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  392. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  393. "bound_check_4bytes_offset"))) {
  394. aot_set_last_error("llvm build in bounds gep failed");
  395. return false;
  396. }
  397. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildBitCast(
  398. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_4bytes,
  399. bound_check_type, "bound_check_4bytes_ptr"))) {
  400. aot_set_last_error("llvm build bit cast failed");
  401. return false;
  402. }
  403. if (mem_space_unchanged) {
  404. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  405. LLVMBuildLoad(comp_ctx->builder,
  406. func_ctx->mem_info[0].mem_bound_check_4bytes,
  407. "bound_check_4bytes"))) {
  408. aot_set_last_error("llvm build load failed");
  409. return false;
  410. }
  411. }
  412. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_8bytes)
  413. - offsetof(AOTMemoryInstance, memory_data.ptr));
  414. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  415. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  416. "bound_check_8bytes_offset"))) {
  417. aot_set_last_error("llvm build in bounds gep failed");
  418. return false;
  419. }
  420. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildBitCast(
  421. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_8bytes,
  422. bound_check_type, "bound_check_8bytes_ptr"))) {
  423. aot_set_last_error("llvm build bit cast failed");
  424. return false;
  425. }
  426. if (mem_space_unchanged) {
  427. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  428. LLVMBuildLoad(comp_ctx->builder,
  429. func_ctx->mem_info[0].mem_bound_check_8bytes,
  430. "bound_check_8bytes"))) {
  431. aot_set_last_error("llvm build load failed");
  432. return false;
  433. }
  434. }
  435. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_16bytes)
  436. - offsetof(AOTMemoryInstance, memory_data.ptr));
  437. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes =
  438. LLVMBuildInBoundsGEP(comp_ctx->builder, mem_info_base, &offset, 1,
  439. "bound_check_16bytes_offset"))) {
  440. aot_set_last_error("llvm build in bounds gep failed");
  441. return false;
  442. }
  443. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildBitCast(
  444. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_16bytes,
  445. bound_check_type, "bound_check_16bytes_ptr"))) {
  446. aot_set_last_error("llvm build bit cast failed");
  447. return false;
  448. }
  449. if (mem_space_unchanged) {
  450. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes =
  451. LLVMBuildLoad(comp_ctx->builder,
  452. func_ctx->mem_info[0].mem_bound_check_16bytes,
  453. "bound_check_16bytes"))) {
  454. aot_set_last_error("llvm build load failed");
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. static bool
  461. create_cur_exception(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  462. {
  463. LLVMValueRef offset;
  464. offset = I32_CONST(offsetof(AOTModuleInstance, cur_exception));
  465. func_ctx->cur_exception = LLVMBuildInBoundsGEP(
  466. comp_ctx->builder, func_ctx->aot_inst, &offset, 1, "cur_exception");
  467. if (!func_ctx->cur_exception) {
  468. aot_set_last_error("llvm build in bounds gep failed.");
  469. return false;
  470. }
  471. return true;
  472. }
  473. static bool
  474. create_func_type_indexes(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  475. {
  476. LLVMValueRef offset, func_type_indexes_ptr;
  477. LLVMTypeRef int32_ptr_type;
  478. offset = I32_CONST(offsetof(AOTModuleInstance, func_type_indexes.ptr));
  479. func_type_indexes_ptr =
  480. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->aot_inst, &offset, 1,
  481. "func_type_indexes_ptr");
  482. if (!func_type_indexes_ptr) {
  483. aot_set_last_error("llvm build add failed.");
  484. return false;
  485. }
  486. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  487. aot_set_last_error("llvm get pointer type failed.");
  488. return false;
  489. }
  490. func_ctx->func_type_indexes =
  491. LLVMBuildBitCast(comp_ctx->builder, func_type_indexes_ptr,
  492. int32_ptr_type, "func_type_indexes_tmp");
  493. if (!func_ctx->func_type_indexes) {
  494. aot_set_last_error("llvm build bit cast failed.");
  495. return false;
  496. }
  497. func_ctx->func_type_indexes = LLVMBuildLoad(
  498. comp_ctx->builder, func_ctx->func_type_indexes, "func_type_indexes");
  499. if (!func_ctx->func_type_indexes) {
  500. aot_set_last_error("llvm build load failed.");
  501. return false;
  502. }
  503. return true;
  504. }
  505. static bool
  506. create_func_ptrs(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  507. {
  508. LLVMValueRef offset;
  509. offset = I32_CONST(offsetof(AOTModuleInstance, func_ptrs));
  510. func_ctx->func_ptrs = LLVMBuildInBoundsGEP(
  511. comp_ctx->builder, func_ctx->aot_inst, &offset, 1, "func_ptrs_offset");
  512. if (!func_ctx->func_ptrs) {
  513. aot_set_last_error("llvm build in bounds gep failed.");
  514. return false;
  515. }
  516. func_ctx->func_ptrs =
  517. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  518. comp_ctx->exec_env_type, "func_ptrs_tmp");
  519. if (!func_ctx->func_ptrs) {
  520. aot_set_last_error("llvm build bit cast failed.");
  521. return false;
  522. }
  523. func_ctx->func_ptrs =
  524. LLVMBuildLoad(comp_ctx->builder, func_ctx->func_ptrs, "func_ptrs_ptr");
  525. if (!func_ctx->func_ptrs) {
  526. aot_set_last_error("llvm build load failed.");
  527. return false;
  528. }
  529. func_ctx->func_ptrs =
  530. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  531. comp_ctx->exec_env_type, "func_ptrs");
  532. if (!func_ctx->func_ptrs) {
  533. aot_set_last_error("llvm build bit cast failed.");
  534. return false;
  535. }
  536. return true;
  537. }
  538. /**
  539. * Create function compiler context
  540. */
  541. static AOTFuncContext *
  542. aot_create_func_context(AOTCompData *comp_data, AOTCompContext *comp_ctx,
  543. AOTFunc *func, uint32 func_index)
  544. {
  545. AOTFuncContext *func_ctx;
  546. AOTFuncType *aot_func_type = comp_data->func_types[func->func_type_index];
  547. AOTBlock *aot_block;
  548. LLVMTypeRef int8_ptr_type, int32_ptr_type;
  549. LLVMValueRef aot_inst_offset = I32_TWO, aot_inst_addr;
  550. LLVMValueRef argv_buf_offset = I32_THREE, argv_buf_addr;
  551. LLVMValueRef stack_bound_offset = I32_FOUR, stack_bound_addr;
  552. LLVMValueRef aux_stack_bound_offset = I32_SIX, aux_stack_bound_addr;
  553. LLVMValueRef aux_stack_bottom_offset = I32_SEVEN, aux_stack_bottom_addr;
  554. LLVMValueRef native_symbol_offset = I32_EIGHT, native_symbol_addr;
  555. char local_name[32];
  556. uint64 size;
  557. uint32 i, j = 0;
  558. /* Allocate memory for the function context */
  559. size = offsetof(AOTFuncContext, locals)
  560. + sizeof(LLVMValueRef)
  561. * ((uint64)aot_func_type->param_count + func->local_count);
  562. if (size >= UINT32_MAX || !(func_ctx = wasm_runtime_malloc((uint32)size))) {
  563. aot_set_last_error("allocate memory failed.");
  564. return NULL;
  565. }
  566. memset(func_ctx, 0, (uint32)size);
  567. func_ctx->aot_func = func;
  568. #if WASM_ENABLE_LAZY_JIT == 0
  569. func_ctx->module = comp_ctx->module;
  570. #else
  571. func_ctx->module = comp_ctx->modules[func_index];
  572. #endif
  573. /* Add LLVM function */
  574. if (!(func_ctx->func =
  575. aot_add_llvm_func(comp_ctx, func_ctx->module, aot_func_type,
  576. func_index, &func_ctx->func_type)))
  577. goto fail;
  578. /* Create function's first AOTBlock */
  579. if (!(aot_block =
  580. aot_create_func_block(comp_ctx, func_ctx, func, aot_func_type)))
  581. goto fail;
  582. #if WASM_ENABLE_DEBUG_AOT != 0
  583. func_ctx->debug_func = dwarf_gen_func_info(comp_ctx, func_ctx);
  584. #endif
  585. aot_block_stack_push(&func_ctx->block_stack, aot_block);
  586. /* Add local variables */
  587. LLVMPositionBuilderAtEnd(comp_ctx->builder, aot_block->llvm_entry_block);
  588. /* Save the pameters for fast access */
  589. func_ctx->exec_env = LLVMGetParam(func_ctx->func, j++);
  590. /* Get aot inst address, the layout of exec_env is:
  591. exec_env->next, exec_env->prev, exec_env->module_inst, and argv_buf */
  592. if (!(aot_inst_addr =
  593. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->exec_env,
  594. &aot_inst_offset, 1, "aot_inst_addr"))) {
  595. aot_set_last_error("llvm build in bounds gep failed");
  596. goto fail;
  597. }
  598. /* Load aot inst */
  599. if (!(func_ctx->aot_inst =
  600. LLVMBuildLoad(comp_ctx->builder, aot_inst_addr, "aot_inst"))) {
  601. aot_set_last_error("llvm build load failed");
  602. goto fail;
  603. }
  604. /* Get argv buffer address */
  605. if (!(argv_buf_addr =
  606. LLVMBuildInBoundsGEP(comp_ctx->builder, func_ctx->exec_env,
  607. &argv_buf_offset, 1, "argv_buf_addr"))) {
  608. aot_set_last_error("llvm build in bounds gep failed");
  609. goto fail;
  610. }
  611. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  612. aot_set_last_error("llvm add pointer type failed");
  613. goto fail;
  614. }
  615. /* Convert to int32 pointer type */
  616. if (!(argv_buf_addr = LLVMBuildBitCast(comp_ctx->builder, argv_buf_addr,
  617. int32_ptr_type, "argv_buf_ptr"))) {
  618. aot_set_last_error("llvm build load failed");
  619. goto fail;
  620. }
  621. if (!(func_ctx->argv_buf =
  622. LLVMBuildLoad(comp_ctx->builder, argv_buf_addr, "argv_buf"))) {
  623. aot_set_last_error("llvm build load failed");
  624. goto fail;
  625. }
  626. /* Get native stack boundary address */
  627. if (!(stack_bound_addr = LLVMBuildInBoundsGEP(
  628. comp_ctx->builder, func_ctx->exec_env, &stack_bound_offset, 1,
  629. "stack_bound_addr"))) {
  630. aot_set_last_error("llvm build in bounds gep failed");
  631. goto fail;
  632. }
  633. if (!(func_ctx->native_stack_bound = LLVMBuildLoad(
  634. comp_ctx->builder, stack_bound_addr, "native_stack_bound"))) {
  635. aot_set_last_error("llvm build load failed");
  636. goto fail;
  637. }
  638. /* Get aux stack boundary address */
  639. if (!(aux_stack_bound_addr = LLVMBuildInBoundsGEP(
  640. comp_ctx->builder, func_ctx->exec_env, &aux_stack_bound_offset, 1,
  641. "aux_stack_bound_addr"))) {
  642. aot_set_last_error("llvm build in bounds gep failed");
  643. goto fail;
  644. }
  645. if (!(aux_stack_bound_addr =
  646. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bound_addr,
  647. INT32_PTR_TYPE, "aux_stack_bound_ptr"))) {
  648. aot_set_last_error("llvm build bit cast failed");
  649. goto fail;
  650. }
  651. if (!(func_ctx->aux_stack_bound = LLVMBuildLoad(
  652. comp_ctx->builder, aux_stack_bound_addr, "aux_stack_bound"))) {
  653. aot_set_last_error("llvm build load failed");
  654. goto fail;
  655. }
  656. /* Get aux stack bottom address */
  657. if (!(aux_stack_bottom_addr = LLVMBuildInBoundsGEP(
  658. comp_ctx->builder, func_ctx->exec_env, &aux_stack_bottom_offset,
  659. 1, "aux_stack_bottom_addr"))) {
  660. aot_set_last_error("llvm build in bounds gep failed");
  661. goto fail;
  662. }
  663. if (!(aux_stack_bottom_addr =
  664. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bottom_addr,
  665. INT32_PTR_TYPE, "aux_stack_bottom_ptr"))) {
  666. aot_set_last_error("llvm build bit cast failed");
  667. goto fail;
  668. }
  669. if (!(func_ctx->aux_stack_bottom = LLVMBuildLoad(
  670. comp_ctx->builder, aux_stack_bottom_addr, "aux_stack_bottom"))) {
  671. aot_set_last_error("llvm build load failed");
  672. goto fail;
  673. }
  674. if (!(native_symbol_addr = LLVMBuildInBoundsGEP(
  675. comp_ctx->builder, func_ctx->exec_env, &native_symbol_offset, 1,
  676. "native_symbol_addr"))) {
  677. aot_set_last_error("llvm build in bounds gep failed");
  678. goto fail;
  679. }
  680. if (!(func_ctx->native_symbol = LLVMBuildLoad(
  681. comp_ctx->builder, native_symbol_addr, "native_symbol_tmp"))) {
  682. aot_set_last_error("llvm build bit cast failed");
  683. goto fail;
  684. }
  685. if (!(func_ctx->native_symbol =
  686. LLVMBuildBitCast(comp_ctx->builder, func_ctx->native_symbol,
  687. comp_ctx->exec_env_type, "native_symbol"))) {
  688. aot_set_last_error("llvm build bit cast failed");
  689. goto fail;
  690. }
  691. for (i = 0; i < aot_func_type->param_count; i++, j++) {
  692. snprintf(local_name, sizeof(local_name), "l%d", i);
  693. func_ctx->locals[i] =
  694. LLVMBuildAlloca(comp_ctx->builder,
  695. TO_LLVM_TYPE(aot_func_type->types[i]), local_name);
  696. if (!func_ctx->locals[i]) {
  697. aot_set_last_error("llvm build alloca failed.");
  698. goto fail;
  699. }
  700. if (!LLVMBuildStore(comp_ctx->builder, LLVMGetParam(func_ctx->func, j),
  701. func_ctx->locals[i])) {
  702. aot_set_last_error("llvm build store failed.");
  703. goto fail;
  704. }
  705. }
  706. for (i = 0; i < func->local_count; i++) {
  707. LLVMTypeRef local_type;
  708. LLVMValueRef local_value = NULL;
  709. snprintf(local_name, sizeof(local_name), "l%d",
  710. aot_func_type->param_count + i);
  711. local_type = TO_LLVM_TYPE(func->local_types[i]);
  712. func_ctx->locals[aot_func_type->param_count + i] =
  713. LLVMBuildAlloca(comp_ctx->builder, local_type, local_name);
  714. if (!func_ctx->locals[aot_func_type->param_count + i]) {
  715. aot_set_last_error("llvm build alloca failed.");
  716. goto fail;
  717. }
  718. switch (func->local_types[i]) {
  719. case VALUE_TYPE_I32:
  720. local_value = I32_ZERO;
  721. break;
  722. case VALUE_TYPE_I64:
  723. local_value = I64_ZERO;
  724. break;
  725. case VALUE_TYPE_F32:
  726. local_value = F32_ZERO;
  727. break;
  728. case VALUE_TYPE_F64:
  729. local_value = F64_ZERO;
  730. break;
  731. case VALUE_TYPE_V128:
  732. local_value = V128_i64x2_ZERO;
  733. break;
  734. case VALUE_TYPE_FUNCREF:
  735. case VALUE_TYPE_EXTERNREF:
  736. local_value = REF_NULL;
  737. break;
  738. default:
  739. bh_assert(0);
  740. break;
  741. }
  742. if (!LLVMBuildStore(comp_ctx->builder, local_value,
  743. func_ctx->locals[aot_func_type->param_count + i])) {
  744. aot_set_last_error("llvm build store failed.");
  745. goto fail;
  746. }
  747. }
  748. if (aot_func_type->param_count + func->local_count > 0) {
  749. func_ctx->last_alloca =
  750. func_ctx
  751. ->locals[aot_func_type->param_count + func->local_count - 1];
  752. if (!(func_ctx->last_alloca =
  753. LLVMBuildBitCast(comp_ctx->builder, func_ctx->last_alloca,
  754. INT8_PTR_TYPE, "stack_ptr"))) {
  755. aot_set_last_error("llvm build bit cast failed.");
  756. goto fail;
  757. }
  758. }
  759. else {
  760. if (!(func_ctx->last_alloca =
  761. LLVMBuildAlloca(comp_ctx->builder, INT8_TYPE, "stack_ptr"))) {
  762. aot_set_last_error("llvm build alloca failed.");
  763. goto fail;
  764. }
  765. }
  766. if (!(int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0))) {
  767. aot_set_last_error("llvm add pointer type failed.");
  768. goto fail;
  769. }
  770. /* Create base addr, end addr, data size of mem, heap */
  771. if (!create_memory_info(comp_ctx, func_ctx, int8_ptr_type, func_index))
  772. goto fail;
  773. /* Load current exception */
  774. if (!create_cur_exception(comp_ctx, func_ctx))
  775. goto fail;
  776. /* Load function type indexes */
  777. if (!create_func_type_indexes(comp_ctx, func_ctx))
  778. goto fail;
  779. /* Load function pointers */
  780. if (!create_func_ptrs(comp_ctx, func_ctx))
  781. goto fail;
  782. return func_ctx;
  783. fail:
  784. if (func_ctx->mem_info)
  785. wasm_runtime_free(func_ctx->mem_info);
  786. aot_block_stack_destroy(&func_ctx->block_stack);
  787. wasm_runtime_free(func_ctx);
  788. return NULL;
  789. }
  790. static void
  791. aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count)
  792. {
  793. uint32 i;
  794. for (i = 0; i < count; i++)
  795. if (func_ctxes[i]) {
  796. if (func_ctxes[i]->mem_info)
  797. wasm_runtime_free(func_ctxes[i]->mem_info);
  798. aot_block_stack_destroy(&func_ctxes[i]->block_stack);
  799. aot_checked_addr_list_destroy(func_ctxes[i]);
  800. wasm_runtime_free(func_ctxes[i]);
  801. }
  802. wasm_runtime_free(func_ctxes);
  803. }
  804. /**
  805. * Create function compiler contexts
  806. */
  807. static AOTFuncContext **
  808. aot_create_func_contexts(AOTCompData *comp_data, AOTCompContext *comp_ctx)
  809. {
  810. AOTFuncContext **func_ctxes;
  811. uint64 size;
  812. uint32 i;
  813. /* Allocate memory */
  814. size = sizeof(AOTFuncContext *) * (uint64)comp_data->func_count;
  815. if (size >= UINT32_MAX
  816. || !(func_ctxes = wasm_runtime_malloc((uint32)size))) {
  817. aot_set_last_error("allocate memory failed.");
  818. return NULL;
  819. }
  820. memset(func_ctxes, 0, size);
  821. /* Create each function context */
  822. for (i = 0; i < comp_data->func_count; i++) {
  823. AOTFunc *func = comp_data->funcs[i];
  824. if (!(func_ctxes[i] =
  825. aot_create_func_context(comp_data, comp_ctx, func, i))) {
  826. aot_destroy_func_contexts(func_ctxes, comp_data->func_count);
  827. return NULL;
  828. }
  829. }
  830. return func_ctxes;
  831. }
  832. static bool
  833. aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context)
  834. {
  835. basic_types->int1_type = LLVMInt1TypeInContext(context);
  836. basic_types->int8_type = LLVMInt8TypeInContext(context);
  837. basic_types->int16_type = LLVMInt16TypeInContext(context);
  838. basic_types->int32_type = LLVMInt32TypeInContext(context);
  839. basic_types->int64_type = LLVMInt64TypeInContext(context);
  840. basic_types->float32_type = LLVMFloatTypeInContext(context);
  841. basic_types->float64_type = LLVMDoubleTypeInContext(context);
  842. basic_types->void_type = LLVMVoidTypeInContext(context);
  843. basic_types->meta_data_type = LLVMMetadataTypeInContext(context);
  844. basic_types->int8_ptr_type = LLVMPointerType(basic_types->int8_type, 0);
  845. if (basic_types->int8_ptr_type) {
  846. basic_types->int8_pptr_type =
  847. LLVMPointerType(basic_types->int8_ptr_type, 0);
  848. }
  849. basic_types->int16_ptr_type = LLVMPointerType(basic_types->int16_type, 0);
  850. basic_types->int32_ptr_type = LLVMPointerType(basic_types->int32_type, 0);
  851. basic_types->int64_ptr_type = LLVMPointerType(basic_types->int64_type, 0);
  852. basic_types->float32_ptr_type =
  853. LLVMPointerType(basic_types->float32_type, 0);
  854. basic_types->float64_ptr_type =
  855. LLVMPointerType(basic_types->float64_type, 0);
  856. basic_types->i8x16_vec_type = LLVMVectorType(basic_types->int8_type, 16);
  857. basic_types->i16x8_vec_type = LLVMVectorType(basic_types->int16_type, 8);
  858. basic_types->i32x4_vec_type = LLVMVectorType(basic_types->int32_type, 4);
  859. basic_types->i64x2_vec_type = LLVMVectorType(basic_types->int64_type, 2);
  860. basic_types->f32x4_vec_type = LLVMVectorType(basic_types->float32_type, 4);
  861. basic_types->f64x2_vec_type = LLVMVectorType(basic_types->float64_type, 2);
  862. basic_types->v128_type = basic_types->i64x2_vec_type;
  863. basic_types->v128_ptr_type = LLVMPointerType(basic_types->v128_type, 0);
  864. basic_types->i1x2_vec_type = LLVMVectorType(basic_types->int1_type, 2);
  865. basic_types->funcref_type = LLVMInt32TypeInContext(context);
  866. basic_types->externref_type = LLVMInt32TypeInContext(context);
  867. return (basic_types->int8_ptr_type && basic_types->int8_pptr_type
  868. && basic_types->int16_ptr_type && basic_types->int32_ptr_type
  869. && basic_types->int64_ptr_type && basic_types->float32_ptr_type
  870. && basic_types->float64_ptr_type && basic_types->i8x16_vec_type
  871. && basic_types->i16x8_vec_type && basic_types->i32x4_vec_type
  872. && basic_types->i64x2_vec_type && basic_types->f32x4_vec_type
  873. && basic_types->f64x2_vec_type && basic_types->i1x2_vec_type
  874. && basic_types->meta_data_type && basic_types->funcref_type
  875. && basic_types->externref_type)
  876. ? true
  877. : false;
  878. }
  879. static bool
  880. aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx)
  881. {
  882. #define CREATE_I1_CONST(name, value) \
  883. if (!(consts->i1_##name = \
  884. LLVMConstInt(comp_ctx->basic_types.int1_type, value, true))) \
  885. return false;
  886. CREATE_I1_CONST(zero, 0)
  887. CREATE_I1_CONST(one, 1)
  888. #undef CREATE_I1_CONST
  889. if (!(consts->i8_zero = I8_CONST(0)))
  890. return false;
  891. if (!(consts->f32_zero = F32_CONST(0)))
  892. return false;
  893. if (!(consts->f64_zero = F64_CONST(0)))
  894. return false;
  895. #define CREATE_I32_CONST(name, value) \
  896. if (!(consts->i32_##name = LLVMConstInt(I32_TYPE, value, true))) \
  897. return false;
  898. CREATE_I32_CONST(min, (uint32)INT32_MIN)
  899. CREATE_I32_CONST(neg_one, (uint32)-1)
  900. CREATE_I32_CONST(zero, 0)
  901. CREATE_I32_CONST(one, 1)
  902. CREATE_I32_CONST(two, 2)
  903. CREATE_I32_CONST(three, 3)
  904. CREATE_I32_CONST(four, 4)
  905. CREATE_I32_CONST(five, 5)
  906. CREATE_I32_CONST(six, 6)
  907. CREATE_I32_CONST(seven, 7)
  908. CREATE_I32_CONST(eight, 8)
  909. CREATE_I32_CONST(nine, 9)
  910. CREATE_I32_CONST(ten, 10)
  911. CREATE_I32_CONST(eleven, 11)
  912. CREATE_I32_CONST(twelve, 12)
  913. CREATE_I32_CONST(thirteen, 13)
  914. CREATE_I32_CONST(fourteen, 14)
  915. CREATE_I32_CONST(fifteen, 15)
  916. CREATE_I32_CONST(31, 31)
  917. CREATE_I32_CONST(32, 32)
  918. #undef CREATE_I32_CONST
  919. #define CREATE_I64_CONST(name, value) \
  920. if (!(consts->i64_##name = LLVMConstInt(I64_TYPE, value, true))) \
  921. return false;
  922. CREATE_I64_CONST(min, (uint64)INT64_MIN)
  923. CREATE_I64_CONST(neg_one, (uint64)-1)
  924. CREATE_I64_CONST(zero, 0)
  925. CREATE_I64_CONST(63, 63)
  926. CREATE_I64_CONST(64, 64)
  927. #undef CREATE_I64_CONST
  928. #define CREATE_V128_CONST(name, type) \
  929. if (!(consts->name##_vec_zero = LLVMConstNull(type))) \
  930. return false; \
  931. if (!(consts->name##_undef = LLVMGetUndef(type))) \
  932. return false;
  933. CREATE_V128_CONST(i8x16, V128_i8x16_TYPE)
  934. CREATE_V128_CONST(i16x8, V128_i16x8_TYPE)
  935. CREATE_V128_CONST(i32x4, V128_i32x4_TYPE)
  936. CREATE_V128_CONST(i64x2, V128_i64x2_TYPE)
  937. CREATE_V128_CONST(f32x4, V128_f32x4_TYPE)
  938. CREATE_V128_CONST(f64x2, V128_f64x2_TYPE)
  939. #undef CREATE_V128_CONST
  940. #define CREATE_VEC_ZERO_MASK(slot) \
  941. { \
  942. LLVMTypeRef type = LLVMVectorType(I32_TYPE, slot); \
  943. if (!type || !(consts->i32x##slot##_zero = LLVMConstNull(type))) \
  944. return false; \
  945. }
  946. CREATE_VEC_ZERO_MASK(16)
  947. CREATE_VEC_ZERO_MASK(8)
  948. CREATE_VEC_ZERO_MASK(4)
  949. CREATE_VEC_ZERO_MASK(2)
  950. #undef CREATE_VEC_ZERO_MASK
  951. return true;
  952. }
  953. typedef struct ArchItem {
  954. char *arch;
  955. bool support_eb;
  956. } ArchItem;
  957. /* clang-format off */
  958. static ArchItem valid_archs[] = {
  959. { "x86_64", false },
  960. { "i386", false },
  961. { "xtensa", false },
  962. { "mips", true },
  963. { "mipsel", false },
  964. { "aarch64v8", false },
  965. { "aarch64v8.1", false },
  966. { "aarch64v8.2", false },
  967. { "aarch64v8.3", false },
  968. { "aarch64v8.4", false },
  969. { "aarch64v8.5", false },
  970. { "aarch64_bev8", false }, /* big endian */
  971. { "aarch64_bev8.1", false },
  972. { "aarch64_bev8.2", false },
  973. { "aarch64_bev8.3", false },
  974. { "aarch64_bev8.4", false },
  975. { "aarch64_bev8.5", false },
  976. { "armv4", true },
  977. { "armv4t", true },
  978. { "armv5t", true },
  979. { "armv5te", true },
  980. { "armv5tej", true },
  981. { "armv6", true },
  982. { "armv6kz", true },
  983. { "armv6t2", true },
  984. { "armv6k", true },
  985. { "armv7", true },
  986. { "armv6m", true },
  987. { "armv6sm", true },
  988. { "armv7em", true },
  989. { "armv8a", true },
  990. { "armv8r", true },
  991. { "armv8m.base", true },
  992. { "armv8m.main", true },
  993. { "armv8.1m.main", true },
  994. { "thumbv4", true },
  995. { "thumbv4t", true },
  996. { "thumbv5t", true },
  997. { "thumbv5te", true },
  998. { "thumbv5tej", true },
  999. { "thumbv6", true },
  1000. { "thumbv6kz", true },
  1001. { "thumbv6t2", true },
  1002. { "thumbv6k", true },
  1003. { "thumbv7", true },
  1004. { "thumbv6m", true },
  1005. { "thumbv6sm", true },
  1006. { "thumbv7em", true },
  1007. { "thumbv8a", true },
  1008. { "thumbv8r", true },
  1009. { "thumbv8m.base", true },
  1010. { "thumbv8m.main", true },
  1011. { "thumbv8.1m.main", true },
  1012. { "riscv32", true },
  1013. { "riscv64", true },
  1014. { "arc", true }
  1015. };
  1016. static const char *valid_abis[] = {
  1017. "gnu",
  1018. "eabi",
  1019. "gnueabihf",
  1020. "msvc",
  1021. "ilp32",
  1022. "ilp32f",
  1023. "ilp32d",
  1024. "lp64",
  1025. "lp64f",
  1026. "lp64d"
  1027. };
  1028. /* clang-format on */
  1029. static void
  1030. print_supported_targets()
  1031. {
  1032. uint32 i;
  1033. os_printf("Supported targets:\n");
  1034. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1035. os_printf("%s ", valid_archs[i].arch);
  1036. if (valid_archs[i].support_eb)
  1037. os_printf("%seb ", valid_archs[i].arch);
  1038. }
  1039. os_printf("\n");
  1040. }
  1041. static void
  1042. print_supported_abis()
  1043. {
  1044. uint32 i;
  1045. os_printf("Supported ABI: ");
  1046. for (i = 0; i < sizeof(valid_abis) / sizeof(const char *); i++)
  1047. os_printf("%s ", valid_abis[i]);
  1048. os_printf("\n");
  1049. }
  1050. static bool
  1051. check_target_arch(const char *target_arch)
  1052. {
  1053. uint32 i;
  1054. char *arch;
  1055. bool support_eb;
  1056. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1057. arch = valid_archs[i].arch;
  1058. support_eb = valid_archs[i].support_eb;
  1059. if (!strncmp(target_arch, arch, strlen(arch))
  1060. && ((support_eb
  1061. && (!strcmp(target_arch + strlen(arch), "eb")
  1062. || !strcmp(target_arch + strlen(arch), "")))
  1063. || (!support_eb && !strcmp(target_arch + strlen(arch), "")))) {
  1064. return true;
  1065. }
  1066. }
  1067. return false;
  1068. }
  1069. static bool
  1070. check_target_abi(const char *target_abi)
  1071. {
  1072. uint32 i;
  1073. for (i = 0; i < sizeof(valid_abis) / sizeof(char *); i++) {
  1074. if (!strcmp(target_abi, valid_abis[i]))
  1075. return true;
  1076. }
  1077. return false;
  1078. }
  1079. static void
  1080. get_target_arch_from_triple(const char *triple, char *arch_buf, uint32 buf_size)
  1081. {
  1082. uint32 i = 0;
  1083. while (*triple != '-' && *triple != '\0' && i < buf_size - 1)
  1084. arch_buf[i++] = *triple++;
  1085. /* Make sure buffer is long enough */
  1086. bh_assert(*triple == '-' || *triple == '\0');
  1087. }
  1088. LLVMBool
  1089. WAMRCreateMCJITCompilerForModule(LLVMExecutionEngineRef *OutJIT,
  1090. LLVMModuleRef M,
  1091. struct LLVMMCJITCompilerOptions *Options,
  1092. size_t SizeOfOptions, char **OutError);
  1093. void
  1094. LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM);
  1095. #if WASM_ENABLE_LAZY_JIT != 0
  1096. void
  1097. aot_handle_llvm_errmsg(const char *string, LLVMErrorRef err)
  1098. {
  1099. char *err_msg = LLVMGetErrorMessage(err);
  1100. aot_set_last_error_v("%s: %s", string, err_msg);
  1101. LLVMDisposeErrorMessage(err_msg);
  1102. }
  1103. static bool
  1104. orc_lazyjit_create(AOTCompContext *comp_ctx, uint32 func_count)
  1105. {
  1106. uint32 i;
  1107. char *err_msg = NULL;
  1108. char *cpu = NULL;
  1109. char *features = NULL;
  1110. char *llvm_triple = NULL;
  1111. char func_name[32] = { 0 };
  1112. LLVMErrorRef err;
  1113. LLVMTargetRef llvm_targetref = NULL;
  1114. LLVMTargetMachineRef target_machine_for_orcjit = NULL;
  1115. LLVMOrcLLJITRef orc_lazyjit = NULL;
  1116. LLVMOrcJITTargetMachineBuilderRef target_machine_builder = NULL;
  1117. LLVMOrcLLJITBuilderRef orc_lazyjit_builder = NULL;
  1118. LLVMOrcMaterializationUnitRef orc_material_unit = NULL;
  1119. LLVMOrcExecutionSessionRef orc_execution_session = NULL;
  1120. LLVMOrcLazyCallThroughManagerRef orc_call_through_mgr = NULL;
  1121. LLVMOrcIndirectStubsManagerRef orc_indirect_stub_mgr = NULL;
  1122. LLVMOrcCSymbolAliasMapPair *orc_symbol_map_pairs = NULL;
  1123. llvm_triple = LLVMGetDefaultTargetTriple();
  1124. if (llvm_triple == NULL) {
  1125. aot_set_last_error("failed to get default target triple.");
  1126. goto fail;
  1127. }
  1128. if (LLVMGetTargetFromTriple(llvm_triple, &llvm_targetref, &err_msg) != 0) {
  1129. aot_set_last_error_v("failed to get llvm target from triple %s.",
  1130. err_msg);
  1131. LLVMDisposeMessage(err_msg);
  1132. goto fail;
  1133. }
  1134. if (!LLVMTargetHasJIT(llvm_targetref)) {
  1135. aot_set_last_error("unspported JIT on this platform.");
  1136. goto fail;
  1137. }
  1138. cpu = LLVMGetHostCPUName();
  1139. if (cpu == NULL) {
  1140. aot_set_last_error("failed to get host cpu information.");
  1141. goto fail;
  1142. }
  1143. features = LLVMGetHostCPUFeatures();
  1144. if (features == NULL) {
  1145. aot_set_last_error("failed to get host cpu features.");
  1146. goto fail;
  1147. }
  1148. LOG_VERBOSE("LLVM ORCJIT detected CPU \"%s\", with features \"%s\"\n", cpu,
  1149. features);
  1150. comp_ctx->target_machine = LLVMCreateTargetMachine(
  1151. llvm_targetref, llvm_triple, cpu, features, LLVMCodeGenLevelDefault,
  1152. LLVMRelocDefault, LLVMCodeModelJITDefault);
  1153. if (!comp_ctx->target_machine) {
  1154. aot_set_last_error("failed to create target machine.");
  1155. goto fail;
  1156. }
  1157. target_machine_for_orcjit = LLVMCreateTargetMachine(
  1158. llvm_targetref, llvm_triple, cpu, features, LLVMCodeGenLevelDefault,
  1159. LLVMRelocDefault, LLVMCodeModelJITDefault);
  1160. if (!target_machine_for_orcjit) {
  1161. aot_set_last_error("failed to create target machine.");
  1162. goto fail;
  1163. }
  1164. target_machine_builder =
  1165. LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(
  1166. target_machine_for_orcjit);
  1167. if (!target_machine_builder) {
  1168. aot_set_last_error("failed to create target machine builder.");
  1169. goto fail;
  1170. }
  1171. /* The target_machine_for_orcjit has been disposed before
  1172. LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine() returns */
  1173. target_machine_for_orcjit = NULL;
  1174. orc_lazyjit_builder = LLVMOrcCreateLLJITBuilder();
  1175. if (!orc_lazyjit_builder) {
  1176. aot_set_last_error("failed to create lazy jit builder.");
  1177. goto fail;
  1178. }
  1179. LLVMOrcLLJITBuilderSetNumCompileThreads(orc_lazyjit_builder,
  1180. WASM_LAZY_JIT_COMPILE_THREAD_NUM);
  1181. LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(orc_lazyjit_builder,
  1182. target_machine_builder);
  1183. /* Should not dispose of the JITTargetMachineBuilder after calling
  1184. LLVMOrcLLJITBuilderSetJITTargetMachineBuilder() */
  1185. target_machine_builder = NULL;
  1186. err = LLVMOrcCreateLLJIT(&orc_lazyjit, orc_lazyjit_builder);
  1187. if (err) {
  1188. aot_handle_llvm_errmsg("failed to create llvm lazy orcjit instance",
  1189. err);
  1190. goto fail;
  1191. }
  1192. /* The orc_lazyjit_builder is managed by orc_lazyjit after calling
  1193. LLVMOrcCreateLLJIT(), here we should not dispose it again */
  1194. orc_lazyjit_builder = NULL;
  1195. if (func_count > 0) {
  1196. orc_execution_session = LLVMOrcLLJITGetExecutionSession(orc_lazyjit);
  1197. if (!orc_execution_session) {
  1198. aot_set_last_error("failed to get orc execution session");
  1199. goto fail;
  1200. }
  1201. err = LLVMOrcCreateLocalLazyCallThroughManager(
  1202. llvm_triple, orc_execution_session, 0, &orc_call_through_mgr);
  1203. if (err) {
  1204. aot_handle_llvm_errmsg("failed to create orc call through manager",
  1205. err);
  1206. goto fail;
  1207. }
  1208. orc_indirect_stub_mgr =
  1209. LLVMOrcCreateLocalIndirectStubsManager(llvm_triple);
  1210. if (!orc_indirect_stub_mgr) {
  1211. aot_set_last_error("failed to create orc indirect stub manager");
  1212. goto fail;
  1213. }
  1214. if (!(orc_symbol_map_pairs = wasm_runtime_malloc(
  1215. sizeof(LLVMOrcCSymbolAliasMapPair) * func_count))) {
  1216. aot_set_last_error("failed to allocate memory");
  1217. goto fail;
  1218. }
  1219. memset(orc_symbol_map_pairs, 0,
  1220. sizeof(LLVMOrcCSymbolAliasMapPair) * func_count);
  1221. for (i = 0; i < func_count; i++) {
  1222. snprintf(func_name, sizeof(func_name), "orcjit_%s%d",
  1223. AOT_FUNC_PREFIX, i);
  1224. orc_symbol_map_pairs[i].Name =
  1225. LLVMOrcExecutionSessionIntern(orc_execution_session, func_name);
  1226. snprintf(func_name, sizeof(func_name), "%s%d", AOT_FUNC_PREFIX, i);
  1227. orc_symbol_map_pairs[i].Entry.Name =
  1228. LLVMOrcExecutionSessionIntern(orc_execution_session, func_name);
  1229. orc_symbol_map_pairs[i].Entry.Flags.GenericFlags =
  1230. LLVMJITSymbolGenericFlagsExported
  1231. | LLVMJITSymbolGenericFlagsCallable;
  1232. orc_symbol_map_pairs[i].Entry.Flags.TargetFlags =
  1233. LLVMJITSymbolGenericFlagsExported
  1234. | LLVMJITSymbolGenericFlagsCallable;
  1235. if (!orc_symbol_map_pairs[i].Name
  1236. || !orc_symbol_map_pairs[i].Entry.Name) {
  1237. aot_set_last_error("failed to allocate memory");
  1238. goto fail;
  1239. }
  1240. }
  1241. orc_material_unit =
  1242. LLVMOrcLazyReexports(orc_call_through_mgr, orc_indirect_stub_mgr,
  1243. LLVMOrcLLJITGetMainJITDylib(orc_lazyjit),
  1244. orc_symbol_map_pairs, func_count);
  1245. if (!orc_material_unit) {
  1246. aot_set_last_error("failed to orc re-exports");
  1247. goto fail;
  1248. }
  1249. }
  1250. comp_ctx->orc_lazyjit = orc_lazyjit;
  1251. comp_ctx->orc_material_unit = orc_material_unit;
  1252. comp_ctx->orc_symbol_map_pairs = orc_symbol_map_pairs;
  1253. comp_ctx->orc_call_through_mgr = orc_call_through_mgr;
  1254. comp_ctx->orc_indirect_stub_mgr = orc_indirect_stub_mgr;
  1255. LLVMDisposeMessage(llvm_triple);
  1256. LLVMDisposeMessage(cpu);
  1257. LLVMDisposeMessage(features);
  1258. return true;
  1259. fail:
  1260. if (orc_symbol_map_pairs)
  1261. wasm_runtime_free(orc_symbol_map_pairs);
  1262. if (orc_call_through_mgr)
  1263. LLVMOrcDisposeLazyCallThroughManager(orc_call_through_mgr);
  1264. if (orc_indirect_stub_mgr)
  1265. LLVMOrcDisposeIndirectStubsManager(orc_indirect_stub_mgr);
  1266. if (orc_lazyjit)
  1267. LLVMOrcDisposeLLJIT(orc_lazyjit);
  1268. if (target_machine_builder)
  1269. LLVMOrcDisposeJITTargetMachineBuilder(target_machine_builder);
  1270. if (orc_lazyjit_builder)
  1271. LLVMOrcDisposeLLJITBuilder(orc_lazyjit_builder);
  1272. if (target_machine_for_orcjit)
  1273. LLVMDisposeTargetMachine(target_machine_for_orcjit);
  1274. if (features)
  1275. LLVMDisposeMessage(features);
  1276. if (cpu)
  1277. LLVMDisposeMessage(cpu);
  1278. if (llvm_triple)
  1279. LLVMDisposeMessage(llvm_triple);
  1280. return false;
  1281. }
  1282. #endif /* WASM_ENABLE_LAZY_JIT != 0 */
  1283. AOTCompContext *
  1284. aot_create_comp_context(AOTCompData *comp_data, aot_comp_option_t option)
  1285. {
  1286. AOTCompContext *comp_ctx, *ret = NULL;
  1287. #if WASM_ENABLE_LAZY_JIT == 0
  1288. struct LLVMMCJITCompilerOptions jit_options;
  1289. #endif
  1290. LLVMTargetRef target;
  1291. char *triple = NULL, *triple_norm, *arch, *abi;
  1292. char *cpu = NULL, *features, buf[128];
  1293. char *triple_norm_new = NULL, *cpu_new = NULL;
  1294. char *err = NULL, *fp_round = "round.tonearest",
  1295. *fp_exce = "fpexcept.strict";
  1296. char triple_buf[32] = { 0 }, features_buf[128] = { 0 };
  1297. uint32 opt_level, size_level, i;
  1298. LLVMCodeModel code_model;
  1299. LLVMTargetDataRef target_data_ref;
  1300. /* Initialize LLVM environment */
  1301. #if WASM_ENABLE_LAZY_JIT != 0
  1302. LLVMInitializeCore(LLVMGetGlobalPassRegistry());
  1303. LLVMInitializeNativeTarget();
  1304. LLVMInitializeNativeAsmPrinter();
  1305. LLVMInitializeNativeAsmParser();
  1306. #else
  1307. LLVMInitializeAllTargetInfos();
  1308. LLVMInitializeAllTargets();
  1309. LLVMInitializeAllTargetMCs();
  1310. LLVMInitializeAllAsmPrinters();
  1311. LLVMLinkInMCJIT();
  1312. #endif
  1313. /* Allocate memory */
  1314. if (!(comp_ctx = wasm_runtime_malloc(sizeof(AOTCompContext)))) {
  1315. aot_set_last_error("allocate memory failed.");
  1316. return NULL;
  1317. }
  1318. memset(comp_ctx, 0, sizeof(AOTCompContext));
  1319. comp_ctx->comp_data = comp_data;
  1320. /* Create LLVM context, module and builder */
  1321. #if WASM_ENABLE_LAZY_JIT != 0
  1322. comp_ctx->orc_thread_safe_context = LLVMOrcCreateNewThreadSafeContext();
  1323. if (!comp_ctx->orc_thread_safe_context) {
  1324. aot_set_last_error("create LLVM ThreadSafeContext failed.");
  1325. goto fail;
  1326. }
  1327. /* Get a reference to the underlying LLVMContext, note:
  1328. different from non LAZY JIT mode, no need to dispose this context,
  1329. if will be disposed when the thread safe context is disposed */
  1330. if (!(comp_ctx->context = LLVMOrcThreadSafeContextGetContext(
  1331. comp_ctx->orc_thread_safe_context))) {
  1332. aot_set_last_error("get context from LLVM ThreadSafeContext failed.");
  1333. goto fail;
  1334. }
  1335. #else
  1336. if (!(comp_ctx->context = LLVMContextCreate())) {
  1337. aot_set_last_error("create LLVM context failed.");
  1338. goto fail;
  1339. }
  1340. #endif
  1341. if (!(comp_ctx->builder = LLVMCreateBuilderInContext(comp_ctx->context))) {
  1342. aot_set_last_error("create LLVM builder failed.");
  1343. goto fail;
  1344. }
  1345. #if WASM_ENABLE_LAZY_JIT == 0
  1346. if (!(comp_ctx->module = LLVMModuleCreateWithNameInContext(
  1347. "WASM Module", comp_ctx->context))) {
  1348. aot_set_last_error("create LLVM module failed.");
  1349. goto fail;
  1350. }
  1351. #else
  1352. if (comp_data->func_count > 0) {
  1353. if (!(comp_ctx->modules = wasm_runtime_malloc(
  1354. sizeof(LLVMModuleRef) * comp_data->func_count))) {
  1355. aot_set_last_error("allocate memory failed.");
  1356. goto fail;
  1357. }
  1358. memset(comp_ctx->modules, 0,
  1359. sizeof(LLVMModuleRef) * comp_data->func_count);
  1360. for (i = 0; i < comp_data->func_count; i++) {
  1361. char module_name[32];
  1362. snprintf(module_name, sizeof(module_name), "WASM Module %d", i);
  1363. /* Create individual modules for each aot function, note:
  1364. different from non LAZY JIT mode, no need to dispose them,
  1365. they will be disposed when the thread safe context is disposed */
  1366. if (!(comp_ctx->modules[i] = LLVMModuleCreateWithNameInContext(
  1367. module_name, comp_ctx->context))) {
  1368. aot_set_last_error("create LLVM module failed.");
  1369. goto fail;
  1370. }
  1371. }
  1372. }
  1373. #endif
  1374. if (BH_LIST_ERROR == bh_list_init(&comp_ctx->native_symbols)) {
  1375. goto fail;
  1376. }
  1377. #if WASM_ENABLE_DEBUG_AOT != 0 && WASM_ENABLE_LAZY_JIT == 0
  1378. if (!(comp_ctx->debug_builder = LLVMCreateDIBuilder(comp_ctx->module))) {
  1379. aot_set_last_error("create LLVM Debug Infor builder failed.");
  1380. goto fail;
  1381. }
  1382. LLVMAddModuleFlag(
  1383. comp_ctx->module, LLVMModuleFlagBehaviorWarning, "Debug Info Version",
  1384. strlen("Debug Info Version"),
  1385. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32Type(), 3, false)));
  1386. comp_ctx->debug_file = dwarf_gen_file_info(comp_ctx);
  1387. if (!comp_ctx->debug_file) {
  1388. aot_set_last_error("dwarf generate file info failed");
  1389. goto fail;
  1390. }
  1391. comp_ctx->debug_comp_unit = dwarf_gen_comp_unit_info(comp_ctx);
  1392. if (!comp_ctx->debug_comp_unit) {
  1393. aot_set_last_error("dwarf generate compile unit info failed");
  1394. goto fail;
  1395. }
  1396. #endif
  1397. if (option->enable_bulk_memory)
  1398. comp_ctx->enable_bulk_memory = true;
  1399. if (option->enable_thread_mgr)
  1400. comp_ctx->enable_thread_mgr = true;
  1401. if (option->enable_tail_call)
  1402. comp_ctx->enable_tail_call = true;
  1403. if (option->enable_ref_types)
  1404. comp_ctx->enable_ref_types = true;
  1405. if (option->enable_aux_stack_frame)
  1406. comp_ctx->enable_aux_stack_frame = true;
  1407. if (option->enable_aux_stack_check)
  1408. comp_ctx->enable_aux_stack_check = true;
  1409. if (option->is_indirect_mode)
  1410. comp_ctx->is_indirect_mode = true;
  1411. if (option->disable_llvm_intrinsics)
  1412. comp_ctx->disable_llvm_intrinsics = true;
  1413. if (option->disable_llvm_lto)
  1414. comp_ctx->disable_llvm_lto = true;
  1415. comp_ctx->opt_level = option->opt_level;
  1416. comp_ctx->size_level = option->size_level;
  1417. if (option->is_jit_mode) {
  1418. char *triple_jit = NULL;
  1419. comp_ctx->is_jit_mode = true;
  1420. #if WASM_ENABLE_LAZY_JIT != 0
  1421. /* Create LLJIT Instance */
  1422. if (!orc_lazyjit_create(comp_ctx, comp_data->func_count)) {
  1423. goto fail;
  1424. }
  1425. #else
  1426. /* Create LLVM execution engine */
  1427. LLVMInitializeMCJITCompilerOptions(&jit_options, sizeof(jit_options));
  1428. jit_options.OptLevel = LLVMCodeGenLevelAggressive;
  1429. jit_options.EnableFastISel = true;
  1430. /*jit_options.CodeModel = LLVMCodeModelSmall;*/
  1431. if (WAMRCreateMCJITCompilerForModule(&comp_ctx->exec_engine,
  1432. comp_ctx->module, &jit_options,
  1433. sizeof(jit_options), &err)
  1434. != 0) {
  1435. if (err) {
  1436. LLVMDisposeMessage(err);
  1437. err = NULL;
  1438. }
  1439. aot_set_last_error("create LLVM JIT compiler failed.");
  1440. goto fail;
  1441. }
  1442. comp_ctx->target_machine =
  1443. LLVMGetExecutionEngineTargetMachine(comp_ctx->exec_engine);
  1444. #endif
  1445. #ifndef OS_ENABLE_HW_BOUND_CHECK
  1446. comp_ctx->enable_bound_check = true;
  1447. #else
  1448. comp_ctx->enable_bound_check = false;
  1449. #endif
  1450. #if WASM_ENABLE_LAZY_JIT != 0
  1451. if (!(triple_jit =
  1452. (char *)LLVMOrcLLJITGetTripleString(comp_ctx->orc_lazyjit))) {
  1453. aot_set_last_error("can not get triple from the target machine");
  1454. goto fail;
  1455. }
  1456. /* Save target arch */
  1457. get_target_arch_from_triple(triple_jit, comp_ctx->target_arch,
  1458. sizeof(comp_ctx->target_arch));
  1459. #else
  1460. if (!(triple_jit =
  1461. LLVMGetTargetMachineTriple(comp_ctx->target_machine))) {
  1462. aot_set_last_error("can not get triple from the target machine");
  1463. goto fail;
  1464. }
  1465. /* Save target arch */
  1466. get_target_arch_from_triple(triple_jit, comp_ctx->target_arch,
  1467. sizeof(comp_ctx->target_arch));
  1468. LLVMDisposeMessage(triple_jit);
  1469. #endif
  1470. }
  1471. else {
  1472. /* Create LLVM target machine */
  1473. arch = option->target_arch;
  1474. abi = option->target_abi;
  1475. cpu = option->target_cpu;
  1476. features = option->cpu_features;
  1477. opt_level = option->opt_level;
  1478. size_level = option->size_level;
  1479. if (arch) {
  1480. /* Add default sub-arch if not specified */
  1481. if (!strcmp(arch, "arm"))
  1482. arch = "armv4";
  1483. else if (!strcmp(arch, "armeb"))
  1484. arch = "armv4eb";
  1485. else if (!strcmp(arch, "thumb"))
  1486. arch = "thumbv4t";
  1487. else if (!strcmp(arch, "thumbeb"))
  1488. arch = "thumbv4teb";
  1489. else if (!strcmp(arch, "aarch64"))
  1490. arch = "aarch64v8";
  1491. else if (!strcmp(arch, "aarch64_be"))
  1492. arch = "aarch64_bev8";
  1493. }
  1494. /* Check target arch */
  1495. if (arch && !check_target_arch(arch)) {
  1496. if (!strcmp(arch, "help"))
  1497. print_supported_targets();
  1498. else
  1499. aot_set_last_error(
  1500. "Invalid target. "
  1501. "Use --target=help to list all supported targets");
  1502. goto fail;
  1503. }
  1504. /* Check target ABI */
  1505. if (abi && !check_target_abi(abi)) {
  1506. if (!strcmp(abi, "help"))
  1507. print_supported_abis();
  1508. else
  1509. aot_set_last_error(
  1510. "Invalid target ABI. "
  1511. "Use --target-abi=help to list all supported ABI");
  1512. goto fail;
  1513. }
  1514. /* Set default abi for riscv target */
  1515. if (arch && !strncmp(arch, "riscv", 5) && !abi) {
  1516. if (!strcmp(arch, "riscv64"))
  1517. abi = "lp64d";
  1518. else
  1519. abi = "ilp32d";
  1520. }
  1521. #if defined(__APPLE__) || defined(__MACH__)
  1522. if (!abi) {
  1523. /* On MacOS platform, set abi to "gnu" to avoid generating
  1524. object file of Mach-O binary format which is unsupported */
  1525. abi = "gnu";
  1526. if (!arch && !cpu && !features) {
  1527. /* Get CPU name of the host machine to avoid checking
  1528. SIMD capability failed */
  1529. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  1530. aot_set_last_error("llvm get host cpu name failed.");
  1531. goto fail;
  1532. }
  1533. }
  1534. }
  1535. #endif
  1536. if (abi) {
  1537. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  1538. const char *vendor_sys;
  1539. char *arch1 = arch, default_arch[32] = { 0 };
  1540. if (!arch1) {
  1541. char *default_triple = LLVMGetDefaultTargetTriple();
  1542. if (!default_triple) {
  1543. aot_set_last_error(
  1544. "llvm get default target triple failed.");
  1545. goto fail;
  1546. }
  1547. vendor_sys = strstr(default_triple, "-");
  1548. bh_assert(vendor_sys);
  1549. bh_memcpy_s(default_arch, sizeof(default_arch), default_triple,
  1550. (uint32)(vendor_sys - default_triple));
  1551. arch1 = default_arch;
  1552. LLVMDisposeMessage(default_triple);
  1553. }
  1554. /**
  1555. * Set <vendor>-<sys> according to abi to generate the object file
  1556. * with the correct file format which might be different from the
  1557. * default object file format of the host, e.g., generating AOT file
  1558. * for Windows/MacOS under Linux host, or generating AOT file for
  1559. * Linux/MacOS under Windows host.
  1560. */
  1561. if (!strcmp(abi, "msvc")) {
  1562. if (!strcmp(arch1, "i386"))
  1563. vendor_sys = "-pc-win32-";
  1564. else
  1565. vendor_sys = "-pc-windows-";
  1566. }
  1567. else {
  1568. vendor_sys = "-pc-linux-";
  1569. }
  1570. bh_assert(strlen(arch1) + strlen(vendor_sys) + strlen(abi)
  1571. < sizeof(triple_buf));
  1572. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch1,
  1573. (uint32)strlen(arch1));
  1574. bh_memcpy_s(triple_buf + strlen(arch1),
  1575. (uint32)(sizeof(triple_buf) - strlen(arch1)),
  1576. vendor_sys, (uint32)strlen(vendor_sys));
  1577. bh_memcpy_s(triple_buf + strlen(arch1) + strlen(vendor_sys),
  1578. (uint32)(sizeof(triple_buf) - strlen(arch1)
  1579. - strlen(vendor_sys)),
  1580. abi, (uint32)strlen(abi));
  1581. triple = triple_buf;
  1582. }
  1583. else if (arch) {
  1584. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  1585. const char *vendor_sys;
  1586. char *default_triple = LLVMGetDefaultTargetTriple();
  1587. if (!default_triple) {
  1588. aot_set_last_error("llvm get default target triple failed.");
  1589. goto fail;
  1590. }
  1591. if (strstr(default_triple, "windows")) {
  1592. vendor_sys = "-pc-windows-";
  1593. if (!abi)
  1594. abi = "msvc";
  1595. }
  1596. else if (strstr(default_triple, "win32")) {
  1597. vendor_sys = "-pc-win32-";
  1598. if (!abi)
  1599. abi = "msvc";
  1600. }
  1601. else {
  1602. vendor_sys = "-pc-linux-";
  1603. if (!abi)
  1604. abi = "gnu";
  1605. }
  1606. LLVMDisposeMessage(default_triple);
  1607. bh_assert(strlen(arch) + strlen(vendor_sys) + strlen(abi)
  1608. < sizeof(triple_buf));
  1609. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch,
  1610. (uint32)strlen(arch));
  1611. bh_memcpy_s(triple_buf + strlen(arch),
  1612. (uint32)(sizeof(triple_buf) - strlen(arch)), vendor_sys,
  1613. (uint32)strlen(vendor_sys));
  1614. bh_memcpy_s(triple_buf + strlen(arch) + strlen(vendor_sys),
  1615. (uint32)(sizeof(triple_buf) - strlen(arch)
  1616. - strlen(vendor_sys)),
  1617. abi, (uint32)strlen(abi));
  1618. triple = triple_buf;
  1619. }
  1620. if (!cpu && features) {
  1621. aot_set_last_error("cpu isn't specified for cpu features.");
  1622. goto fail;
  1623. }
  1624. if (!triple && !cpu) {
  1625. /* Get a triple for the host machine */
  1626. if (!(triple_norm = triple_norm_new =
  1627. LLVMGetDefaultTargetTriple())) {
  1628. aot_set_last_error("llvm get default target triple failed.");
  1629. goto fail;
  1630. }
  1631. /* Get CPU name of the host machine */
  1632. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  1633. aot_set_last_error("llvm get host cpu name failed.");
  1634. goto fail;
  1635. }
  1636. }
  1637. else if (triple) {
  1638. /* Normalize a target triple */
  1639. if (!(triple_norm = triple_norm_new =
  1640. LLVMNormalizeTargetTriple(triple))) {
  1641. snprintf(buf, sizeof(buf),
  1642. "llvm normlalize target triple (%s) failed.", triple);
  1643. aot_set_last_error(buf);
  1644. goto fail;
  1645. }
  1646. if (!cpu)
  1647. cpu = "";
  1648. }
  1649. else {
  1650. /* triple is NULL, cpu isn't NULL */
  1651. snprintf(buf, sizeof(buf), "target isn't specified for cpu %s.",
  1652. cpu);
  1653. aot_set_last_error(buf);
  1654. goto fail;
  1655. }
  1656. /* Add module flag and cpu feature for riscv target */
  1657. if (arch && !strncmp(arch, "riscv", 5)) {
  1658. LLVMMetadataRef meta_target_abi;
  1659. if (!(meta_target_abi = LLVMMDStringInContext2(comp_ctx->context,
  1660. abi, strlen(abi)))) {
  1661. aot_set_last_error("create metadata string failed.");
  1662. goto fail;
  1663. }
  1664. #if WASM_ENABLE_LAZY_JIT == 0
  1665. LLVMAddModuleFlag(comp_ctx->module, LLVMModuleFlagBehaviorError,
  1666. "target-abi", strlen("target-abi"),
  1667. meta_target_abi);
  1668. #else
  1669. for (i = 0; i < comp_data->func_count; i++) {
  1670. LLVMAddModuleFlag(comp_ctx->modules[i],
  1671. LLVMModuleFlagBehaviorError, "target-abi",
  1672. strlen("target-abi"), meta_target_abi);
  1673. }
  1674. #endif
  1675. if (!strcmp(abi, "lp64d") || !strcmp(abi, "ilp32d")) {
  1676. if (features) {
  1677. snprintf(features_buf, sizeof(features_buf), "%s%s",
  1678. features, ",+d");
  1679. features = features_buf;
  1680. }
  1681. else
  1682. features = "+d";
  1683. }
  1684. }
  1685. if (!features)
  1686. features = "";
  1687. /* Get target with triple, note that LLVMGetTargetFromTriple()
  1688. return 0 when success, but not true. */
  1689. if (LLVMGetTargetFromTriple(triple_norm, &target, &err) != 0) {
  1690. if (err) {
  1691. LLVMDisposeMessage(err);
  1692. err = NULL;
  1693. }
  1694. snprintf(buf, sizeof(buf),
  1695. "llvm get target from triple (%s) failed", triple_norm);
  1696. aot_set_last_error(buf);
  1697. goto fail;
  1698. }
  1699. /* Save target arch */
  1700. get_target_arch_from_triple(triple_norm, comp_ctx->target_arch,
  1701. sizeof(comp_ctx->target_arch));
  1702. if (option->bounds_checks == 1 || option->bounds_checks == 0) {
  1703. /* Set by user */
  1704. comp_ctx->enable_bound_check =
  1705. (option->bounds_checks == 1) ? true : false;
  1706. }
  1707. else {
  1708. /* Unset by user, use default value */
  1709. if (strstr(comp_ctx->target_arch, "64")
  1710. && !option->is_sgx_platform) {
  1711. comp_ctx->enable_bound_check = false;
  1712. }
  1713. else {
  1714. comp_ctx->enable_bound_check = true;
  1715. }
  1716. }
  1717. os_printf("Create AoT compiler with:\n");
  1718. os_printf(" target: %s\n", comp_ctx->target_arch);
  1719. os_printf(" target cpu: %s\n", cpu);
  1720. os_printf(" cpu features: %s\n", features);
  1721. os_printf(" opt level: %d\n", opt_level);
  1722. os_printf(" size level: %d\n", size_level);
  1723. switch (option->output_format) {
  1724. case AOT_LLVMIR_UNOPT_FILE:
  1725. os_printf(" output format: unoptimized LLVM IR\n");
  1726. break;
  1727. case AOT_LLVMIR_OPT_FILE:
  1728. os_printf(" output format: optimized LLVM IR\n");
  1729. break;
  1730. case AOT_FORMAT_FILE:
  1731. os_printf(" output format: AoT file\n");
  1732. break;
  1733. case AOT_OBJECT_FILE:
  1734. os_printf(" output format: native object file\n");
  1735. break;
  1736. }
  1737. if (!LLVMTargetHasTargetMachine(target)) {
  1738. snprintf(buf, sizeof(buf),
  1739. "no target machine for this target (%s).", triple_norm);
  1740. aot_set_last_error(buf);
  1741. goto fail;
  1742. }
  1743. /* Report error if target isn't arc and hasn't asm backend.
  1744. For arc target, as it cannot emit to memory buffer of elf file
  1745. currently, we let it emit to assembly file instead, and then call
  1746. arc-gcc to compile
  1747. asm file to elf file, and read elf file to memory buffer. */
  1748. if (strncmp(comp_ctx->target_arch, "arc", 3)
  1749. && !LLVMTargetHasAsmBackend(target)) {
  1750. snprintf(buf, sizeof(buf), "no asm backend for this target (%s).",
  1751. LLVMGetTargetName(target));
  1752. aot_set_last_error(buf);
  1753. goto fail;
  1754. }
  1755. /* Set code model */
  1756. if (size_level == 0)
  1757. code_model = LLVMCodeModelLarge;
  1758. else if (size_level == 1)
  1759. code_model = LLVMCodeModelMedium;
  1760. else if (size_level == 2)
  1761. code_model = LLVMCodeModelKernel;
  1762. else
  1763. code_model = LLVMCodeModelSmall;
  1764. /* Create the target machine */
  1765. if (!(comp_ctx->target_machine = LLVMCreateTargetMachine(
  1766. target, triple_norm, cpu, features, opt_level,
  1767. LLVMRelocStatic, code_model))) {
  1768. aot_set_last_error("create LLVM target machine failed.");
  1769. goto fail;
  1770. }
  1771. #if WASM_ENABLE_LAZY_JIT == 0
  1772. LLVMSetTarget(comp_ctx->module, triple_norm);
  1773. #endif
  1774. }
  1775. if (option->enable_simd && strcmp(comp_ctx->target_arch, "x86_64") != 0
  1776. && strncmp(comp_ctx->target_arch, "aarch64", 7) != 0) {
  1777. /* Disable simd if it isn't supported by target arch */
  1778. option->enable_simd = false;
  1779. }
  1780. if (option->enable_simd) {
  1781. char *tmp;
  1782. bool check_simd_ret;
  1783. comp_ctx->enable_simd = true;
  1784. if (!(tmp = LLVMGetTargetMachineCPU(comp_ctx->target_machine))) {
  1785. aot_set_last_error("get CPU from Target Machine fail");
  1786. goto fail;
  1787. }
  1788. check_simd_ret =
  1789. aot_check_simd_compatibility(comp_ctx->target_arch, tmp);
  1790. LLVMDisposeMessage(tmp);
  1791. if (!check_simd_ret) {
  1792. aot_set_last_error("SIMD compatibility check failed, "
  1793. "try adding --cpu=<cpu> to specify a cpu "
  1794. "or adding --disable-simd to disable SIMD");
  1795. goto fail;
  1796. }
  1797. }
  1798. if (!(target_data_ref =
  1799. LLVMCreateTargetDataLayout(comp_ctx->target_machine))) {
  1800. aot_set_last_error("create LLVM target data layout failed.");
  1801. goto fail;
  1802. }
  1803. comp_ctx->pointer_size = LLVMPointerSize(target_data_ref);
  1804. LLVMDisposeTargetData(target_data_ref);
  1805. comp_ctx->optimize = true;
  1806. if (option->output_format == AOT_LLVMIR_UNOPT_FILE)
  1807. comp_ctx->optimize = false;
  1808. /* Create metadata for llvm float experimental constrained intrinsics */
  1809. if (!(comp_ctx->fp_rounding_mode = LLVMMDStringInContext(
  1810. comp_ctx->context, fp_round, (uint32)strlen(fp_round)))
  1811. || !(comp_ctx->fp_exception_behavior = LLVMMDStringInContext(
  1812. comp_ctx->context, fp_exce, (uint32)strlen(fp_exce)))) {
  1813. aot_set_last_error("create float llvm metadata failed.");
  1814. goto fail;
  1815. }
  1816. if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context)) {
  1817. aot_set_last_error("create LLVM basic types failed.");
  1818. goto fail;
  1819. }
  1820. if (!aot_create_llvm_consts(&comp_ctx->llvm_consts, comp_ctx)) {
  1821. aot_set_last_error("create LLVM const values failed.");
  1822. goto fail;
  1823. }
  1824. /* set exec_env data type to int8** */
  1825. comp_ctx->exec_env_type = comp_ctx->basic_types.int8_pptr_type;
  1826. /* set aot_inst data type to int8* */
  1827. comp_ctx->aot_inst_type = INT8_PTR_TYPE;
  1828. /* Create function context for each function */
  1829. comp_ctx->func_ctx_count = comp_data->func_count;
  1830. if (comp_data->func_count > 0
  1831. && !(comp_ctx->func_ctxes =
  1832. aot_create_func_contexts(comp_data, comp_ctx)))
  1833. goto fail;
  1834. if (cpu) {
  1835. uint32 len = (uint32)strlen(cpu) + 1;
  1836. if (!(comp_ctx->target_cpu = wasm_runtime_malloc(len))) {
  1837. aot_set_last_error("allocate memory failed");
  1838. goto fail;
  1839. }
  1840. bh_memcpy_s(comp_ctx->target_cpu, len, cpu, len);
  1841. }
  1842. if (comp_ctx->disable_llvm_intrinsics)
  1843. aot_intrinsic_fill_capability_flags(comp_ctx);
  1844. ret = comp_ctx;
  1845. fail:
  1846. if (triple_norm_new)
  1847. LLVMDisposeMessage(triple_norm_new);
  1848. if (cpu_new)
  1849. LLVMDisposeMessage(cpu_new);
  1850. if (!ret)
  1851. aot_destroy_comp_context(comp_ctx);
  1852. (void)i;
  1853. return ret;
  1854. }
  1855. void
  1856. aot_destroy_comp_context(AOTCompContext *comp_ctx)
  1857. {
  1858. if (!comp_ctx)
  1859. return;
  1860. #if WASM_ENABLE_LAZY_JIT != 0
  1861. if (comp_ctx->orc_symbol_map_pairs)
  1862. wasm_runtime_free(comp_ctx->orc_symbol_map_pairs);
  1863. if (comp_ctx->orc_call_through_mgr)
  1864. LLVMOrcDisposeLazyCallThroughManager(comp_ctx->orc_call_through_mgr);
  1865. if (comp_ctx->orc_indirect_stub_mgr)
  1866. LLVMOrcDisposeIndirectStubsManager(comp_ctx->orc_indirect_stub_mgr);
  1867. if (comp_ctx->orc_material_unit)
  1868. LLVMOrcDisposeMaterializationUnit(comp_ctx->orc_material_unit);
  1869. if (comp_ctx->target_machine)
  1870. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  1871. if (comp_ctx->builder)
  1872. LLVMDisposeBuilder(comp_ctx->builder);
  1873. if (comp_ctx->orc_lazyjit)
  1874. LLVMOrcDisposeLLJIT(comp_ctx->orc_lazyjit);
  1875. if (comp_ctx->orc_thread_safe_context)
  1876. LLVMOrcDisposeThreadSafeContext(comp_ctx->orc_thread_safe_context);
  1877. if (comp_ctx->modules)
  1878. wasm_runtime_free(comp_ctx->modules);
  1879. /* Note: don't dispose comp_ctx->context and comp_ctx->modules[i] as
  1880. they are disposed when disposing the thread safe context */
  1881. LLVMShutdown();
  1882. #else
  1883. if (comp_ctx->target_machine && !comp_ctx->is_jit_mode)
  1884. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  1885. if (comp_ctx->builder)
  1886. LLVMDisposeBuilder(comp_ctx->builder);
  1887. if (comp_ctx->exec_engine) {
  1888. LLVMDisposeExecutionEngine(comp_ctx->exec_engine);
  1889. /* The LLVM module is freed when disposing execution engine,
  1890. no need to dispose it again. */
  1891. }
  1892. else if (comp_ctx->module)
  1893. LLVMDisposeModule(comp_ctx->module);
  1894. if (comp_ctx->context)
  1895. LLVMContextDispose(comp_ctx->context);
  1896. #endif
  1897. if (comp_ctx->func_ctxes)
  1898. aot_destroy_func_contexts(comp_ctx->func_ctxes,
  1899. comp_ctx->func_ctx_count);
  1900. if (bh_list_length(&comp_ctx->native_symbols) > 0) {
  1901. AOTNativeSymbol *sym = bh_list_first_elem(&comp_ctx->native_symbols);
  1902. while (sym) {
  1903. AOTNativeSymbol *t = bh_list_elem_next(sym);
  1904. bh_list_remove(&comp_ctx->native_symbols, sym);
  1905. wasm_runtime_free(sym);
  1906. sym = t;
  1907. }
  1908. }
  1909. if (comp_ctx->target_cpu) {
  1910. wasm_runtime_free(comp_ctx->target_cpu);
  1911. }
  1912. wasm_runtime_free(comp_ctx);
  1913. }
  1914. static bool
  1915. insert_native_symbol(AOTCompContext *comp_ctx, const char *symbol, int32 idx)
  1916. {
  1917. AOTNativeSymbol *sym = wasm_runtime_malloc(sizeof(AOTNativeSymbol));
  1918. if (!sym) {
  1919. aot_set_last_error("alloc native symbol failed.");
  1920. return false;
  1921. }
  1922. memset(sym, 0, sizeof(AOTNativeSymbol));
  1923. bh_assert(strlen(symbol) <= sizeof(sym->symbol));
  1924. snprintf(sym->symbol, sizeof(sym->symbol), "%s", symbol);
  1925. sym->index = idx;
  1926. if (BH_LIST_ERROR == bh_list_insert(&comp_ctx->native_symbols, sym)) {
  1927. wasm_runtime_free(sym);
  1928. aot_set_last_error("insert native symbol to list failed.");
  1929. return false;
  1930. }
  1931. return true;
  1932. }
  1933. int32
  1934. aot_get_native_symbol_index(AOTCompContext *comp_ctx, const char *symbol)
  1935. {
  1936. int32 idx = -1;
  1937. AOTNativeSymbol *sym = NULL;
  1938. sym = bh_list_first_elem(&comp_ctx->native_symbols);
  1939. /* Lookup an existing symobl record */
  1940. while (sym) {
  1941. if (strcmp(sym->symbol, symbol) == 0) {
  1942. idx = sym->index;
  1943. break;
  1944. }
  1945. sym = bh_list_elem_next(sym);
  1946. }
  1947. /* Given symbol is not exist in list, then we alloc a new index for it */
  1948. if (idx < 0) {
  1949. if (comp_ctx->pointer_size == sizeof(uint32)
  1950. && !strncmp(symbol, "f64#", 4)) {
  1951. idx = bh_list_length(&comp_ctx->native_symbols);
  1952. /* Add 4 bytes padding on 32-bit target to make sure that
  1953. the f64 const is stored on 8-byte aligned address */
  1954. if ((idx & 1) && !strncmp(comp_ctx->target_arch, "i386", 4)) {
  1955. if (!insert_native_symbol(comp_ctx, "__ignore", idx)) {
  1956. return -1;
  1957. }
  1958. }
  1959. }
  1960. idx = bh_list_length(&comp_ctx->native_symbols);
  1961. if (!insert_native_symbol(comp_ctx, symbol, idx)) {
  1962. return -1;
  1963. }
  1964. if (comp_ctx->pointer_size == sizeof(uint32)
  1965. && !strncmp(symbol, "f64#", 4)) {
  1966. /* f64 const occupies 2 pointer slots on 32-bit target */
  1967. if (!insert_native_symbol(comp_ctx, "__ignore", idx + 1)) {
  1968. return -1;
  1969. }
  1970. }
  1971. }
  1972. return idx;
  1973. }
  1974. void
  1975. aot_value_stack_push(AOTValueStack *stack, AOTValue *value)
  1976. {
  1977. if (!stack->value_list_head)
  1978. stack->value_list_head = stack->value_list_end = value;
  1979. else {
  1980. stack->value_list_end->next = value;
  1981. value->prev = stack->value_list_end;
  1982. stack->value_list_end = value;
  1983. }
  1984. }
  1985. AOTValue *
  1986. aot_value_stack_pop(AOTValueStack *stack)
  1987. {
  1988. AOTValue *value = stack->value_list_end;
  1989. bh_assert(stack->value_list_end);
  1990. if (stack->value_list_head == stack->value_list_end)
  1991. stack->value_list_head = stack->value_list_end = NULL;
  1992. else {
  1993. stack->value_list_end = stack->value_list_end->prev;
  1994. stack->value_list_end->next = NULL;
  1995. value->prev = NULL;
  1996. }
  1997. return value;
  1998. }
  1999. void
  2000. aot_value_stack_destroy(AOTValueStack *stack)
  2001. {
  2002. AOTValue *value = stack->value_list_head, *p;
  2003. while (value) {
  2004. p = value->next;
  2005. wasm_runtime_free(value);
  2006. value = p;
  2007. }
  2008. stack->value_list_head = NULL;
  2009. stack->value_list_end = NULL;
  2010. }
  2011. void
  2012. aot_block_stack_push(AOTBlockStack *stack, AOTBlock *block)
  2013. {
  2014. if (!stack->block_list_head)
  2015. stack->block_list_head = stack->block_list_end = block;
  2016. else {
  2017. stack->block_list_end->next = block;
  2018. block->prev = stack->block_list_end;
  2019. stack->block_list_end = block;
  2020. }
  2021. }
  2022. AOTBlock *
  2023. aot_block_stack_pop(AOTBlockStack *stack)
  2024. {
  2025. AOTBlock *block = stack->block_list_end;
  2026. bh_assert(stack->block_list_end);
  2027. if (stack->block_list_head == stack->block_list_end)
  2028. stack->block_list_head = stack->block_list_end = NULL;
  2029. else {
  2030. stack->block_list_end = stack->block_list_end->prev;
  2031. stack->block_list_end->next = NULL;
  2032. block->prev = NULL;
  2033. }
  2034. return block;
  2035. }
  2036. void
  2037. aot_block_stack_destroy(AOTBlockStack *stack)
  2038. {
  2039. AOTBlock *block = stack->block_list_head, *p;
  2040. while (block) {
  2041. p = block->next;
  2042. aot_value_stack_destroy(&block->value_stack);
  2043. aot_block_destroy(block);
  2044. block = p;
  2045. }
  2046. stack->block_list_head = NULL;
  2047. stack->block_list_end = NULL;
  2048. }
  2049. void
  2050. aot_block_destroy(AOTBlock *block)
  2051. {
  2052. aot_value_stack_destroy(&block->value_stack);
  2053. if (block->param_types)
  2054. wasm_runtime_free(block->param_types);
  2055. if (block->param_phis)
  2056. wasm_runtime_free(block->param_phis);
  2057. if (block->else_param_phis)
  2058. wasm_runtime_free(block->else_param_phis);
  2059. if (block->result_types)
  2060. wasm_runtime_free(block->result_types);
  2061. if (block->result_phis)
  2062. wasm_runtime_free(block->result_phis);
  2063. wasm_runtime_free(block);
  2064. }
  2065. bool
  2066. aot_checked_addr_list_add(AOTFuncContext *func_ctx, uint32 local_idx,
  2067. uint32 offset, uint32 bytes)
  2068. {
  2069. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2070. if (!(node = wasm_runtime_malloc(sizeof(AOTCheckedAddr)))) {
  2071. aot_set_last_error("allocate memory failed.");
  2072. return false;
  2073. }
  2074. node->local_idx = local_idx;
  2075. node->offset = offset;
  2076. node->bytes = bytes;
  2077. node->next = func_ctx->checked_addr_list;
  2078. func_ctx->checked_addr_list = node;
  2079. return true;
  2080. }
  2081. void
  2082. aot_checked_addr_list_del(AOTFuncContext *func_ctx, uint32 local_idx)
  2083. {
  2084. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2085. AOTCheckedAddr *node_prev = NULL, *node_next;
  2086. while (node) {
  2087. node_next = node->next;
  2088. if (node->local_idx == local_idx) {
  2089. if (!node_prev)
  2090. func_ctx->checked_addr_list = node_next;
  2091. else
  2092. node_prev->next = node_next;
  2093. wasm_runtime_free(node);
  2094. }
  2095. else {
  2096. node_prev = node;
  2097. }
  2098. node = node_next;
  2099. }
  2100. }
  2101. bool
  2102. aot_checked_addr_list_find(AOTFuncContext *func_ctx, uint32 local_idx,
  2103. uint32 offset, uint32 bytes)
  2104. {
  2105. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2106. while (node) {
  2107. if (node->local_idx == local_idx && node->offset == offset
  2108. && node->bytes >= bytes) {
  2109. return true;
  2110. }
  2111. node = node->next;
  2112. }
  2113. return false;
  2114. }
  2115. void
  2116. aot_checked_addr_list_destroy(AOTFuncContext *func_ctx)
  2117. {
  2118. AOTCheckedAddr *node = func_ctx->checked_addr_list, *node_next;
  2119. while (node) {
  2120. node_next = node->next;
  2121. wasm_runtime_free(node);
  2122. node = node_next;
  2123. }
  2124. func_ctx->checked_addr_list = NULL;
  2125. }
  2126. bool
  2127. aot_build_zero_function_ret(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  2128. AOTFuncType *func_type)
  2129. {
  2130. LLVMValueRef ret = NULL;
  2131. if (func_type->result_count) {
  2132. switch (func_type->types[func_type->param_count]) {
  2133. case VALUE_TYPE_I32:
  2134. ret = LLVMBuildRet(comp_ctx->builder, I32_ZERO);
  2135. break;
  2136. case VALUE_TYPE_I64:
  2137. ret = LLVMBuildRet(comp_ctx->builder, I64_ZERO);
  2138. break;
  2139. case VALUE_TYPE_F32:
  2140. ret = LLVMBuildRet(comp_ctx->builder, F32_ZERO);
  2141. break;
  2142. case VALUE_TYPE_F64:
  2143. ret = LLVMBuildRet(comp_ctx->builder, F64_ZERO);
  2144. break;
  2145. case VALUE_TYPE_V128:
  2146. ret =
  2147. LLVMBuildRet(comp_ctx->builder, LLVM_CONST(i64x2_vec_zero));
  2148. break;
  2149. case VALUE_TYPE_FUNCREF:
  2150. case VALUE_TYPE_EXTERNREF:
  2151. ret = LLVMBuildRet(comp_ctx->builder, REF_NULL);
  2152. break;
  2153. default:
  2154. bh_assert(0);
  2155. }
  2156. }
  2157. else {
  2158. ret = LLVMBuildRetVoid(comp_ctx->builder);
  2159. }
  2160. if (!ret) {
  2161. aot_set_last_error("llvm build ret failed.");
  2162. return false;
  2163. }
  2164. #if WASM_ENABLE_DEBUG_AOT != 0
  2165. LLVMMetadataRef return_location =
  2166. dwarf_gen_func_ret_location(comp_ctx, func_ctx);
  2167. LLVMInstructionSetDebugLoc(ret, return_location);
  2168. #endif
  2169. return true;
  2170. }
  2171. static LLVMValueRef
  2172. __call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2173. const AOTFuncContext *func_ctx, const char *name,
  2174. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2175. int param_count, LLVMValueRef *param_values)
  2176. {
  2177. LLVMValueRef func, ret;
  2178. LLVMTypeRef func_type;
  2179. const char *symname;
  2180. int32 func_idx;
  2181. if (comp_ctx->disable_llvm_intrinsics
  2182. && aot_intrinsic_check_capability(comp_ctx, name)) {
  2183. if (func_ctx == NULL) {
  2184. aot_set_last_error_v("invalid func_ctx for intrinsic: %s", name);
  2185. return NULL;
  2186. }
  2187. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2188. (uint32)param_count, false))) {
  2189. aot_set_last_error("create LLVM intrinsic function type failed.");
  2190. return NULL;
  2191. }
  2192. if (!(func_type = LLVMPointerType(func_type, 0))) {
  2193. aot_set_last_error(
  2194. "create LLVM intrinsic function pointer type failed.");
  2195. return NULL;
  2196. }
  2197. if (!(symname = aot_intrinsic_get_symbol(name))) {
  2198. aot_set_last_error_v("runtime intrinsic not implemented: %s\n",
  2199. name);
  2200. return NULL;
  2201. }
  2202. func_idx =
  2203. aot_get_native_symbol_index((AOTCompContext *)comp_ctx, symname);
  2204. if (func_idx < 0) {
  2205. aot_set_last_error_v("get runtime intrinsc index failed: %s\n",
  2206. name);
  2207. return NULL;
  2208. }
  2209. if (!(func = aot_get_func_from_table(comp_ctx, func_ctx->native_symbol,
  2210. func_type, func_idx))) {
  2211. aot_set_last_error_v("get runtime intrinsc failed: %s\n", name);
  2212. return NULL;
  2213. }
  2214. }
  2215. else {
  2216. /* Declare llvm intrinsic function if necessary */
  2217. if (!(func = LLVMGetNamedFunction(func_ctx->module, name))) {
  2218. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2219. (uint32)param_count, false))) {
  2220. aot_set_last_error(
  2221. "create LLVM intrinsic function type failed.");
  2222. return NULL;
  2223. }
  2224. if (!(func = LLVMAddFunction(func_ctx->module, name, func_type))) {
  2225. aot_set_last_error("add LLVM intrinsic function failed.");
  2226. return NULL;
  2227. }
  2228. }
  2229. }
  2230. /* Call the LLVM intrinsic function */
  2231. if (!(ret = LLVMBuildCall(comp_ctx->builder, func, param_values,
  2232. (uint32)param_count, "call"))) {
  2233. aot_set_last_error("llvm build intrinsic call failed.");
  2234. return NULL;
  2235. }
  2236. return ret;
  2237. }
  2238. LLVMValueRef
  2239. aot_call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2240. const AOTFuncContext *func_ctx, const char *intrinsic,
  2241. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2242. int param_count, ...)
  2243. {
  2244. LLVMValueRef *param_values, ret;
  2245. va_list argptr;
  2246. uint64 total_size;
  2247. int i = 0;
  2248. /* Create param values */
  2249. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2250. if (total_size >= UINT32_MAX
  2251. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2252. aot_set_last_error("allocate memory for param values failed.");
  2253. return false;
  2254. }
  2255. /* Load each param value */
  2256. va_start(argptr, param_count);
  2257. while (i < param_count)
  2258. param_values[i++] = va_arg(argptr, LLVMValueRef);
  2259. va_end(argptr);
  2260. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2261. param_types, param_count, param_values);
  2262. wasm_runtime_free(param_values);
  2263. return ret;
  2264. }
  2265. LLVMValueRef
  2266. aot_call_llvm_intrinsic_v(const AOTCompContext *comp_ctx,
  2267. const AOTFuncContext *func_ctx, const char *intrinsic,
  2268. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2269. int param_count, va_list param_value_list)
  2270. {
  2271. LLVMValueRef *param_values, ret;
  2272. uint64 total_size;
  2273. int i = 0;
  2274. /* Create param values */
  2275. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2276. if (total_size >= UINT32_MAX
  2277. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2278. aot_set_last_error("allocate memory for param values failed.");
  2279. return false;
  2280. }
  2281. /* Load each param value */
  2282. while (i < param_count)
  2283. param_values[i++] = va_arg(param_value_list, LLVMValueRef);
  2284. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2285. param_types, param_count, param_values);
  2286. wasm_runtime_free(param_values);
  2287. return ret;
  2288. }
  2289. LLVMValueRef
  2290. aot_get_func_from_table(const AOTCompContext *comp_ctx, LLVMValueRef base,
  2291. LLVMTypeRef func_type, int32 index)
  2292. {
  2293. LLVMValueRef func;
  2294. LLVMValueRef func_addr;
  2295. if (!(func_addr = I32_CONST(index))) {
  2296. aot_set_last_error("construct function index failed.");
  2297. goto fail;
  2298. }
  2299. if (!(func_addr = LLVMBuildInBoundsGEP(comp_ctx->builder, base, &func_addr,
  2300. 1, "func_addr"))) {
  2301. aot_set_last_error("get function addr by index failed.");
  2302. goto fail;
  2303. }
  2304. func = LLVMBuildLoad(comp_ctx->builder, func_addr, "func_tmp");
  2305. if (func == NULL) {
  2306. aot_set_last_error("get function pointer failed.");
  2307. goto fail;
  2308. }
  2309. if (!(func =
  2310. LLVMBuildBitCast(comp_ctx->builder, func, func_type, "func"))) {
  2311. aot_set_last_error("cast function fialed.");
  2312. goto fail;
  2313. }
  2314. return func;
  2315. fail:
  2316. return NULL;
  2317. }
  2318. LLVMValueRef
  2319. aot_load_const_from_table(AOTCompContext *comp_ctx, LLVMValueRef base,
  2320. const WASMValue *value, uint8 value_type)
  2321. {
  2322. LLVMValueRef const_index, const_addr, const_value;
  2323. LLVMTypeRef const_ptr_type;
  2324. char buf[128] = { 0 };
  2325. int32 index;
  2326. switch (value_type) {
  2327. case VALUE_TYPE_F32:
  2328. /* Store the raw int bits of f32 const as a hex string */
  2329. snprintf(buf, sizeof(buf), "f32#%08" PRIX32, value->i32);
  2330. const_ptr_type = F32_PTR_TYPE;
  2331. break;
  2332. case VALUE_TYPE_F64:
  2333. /* Store the raw int bits of f64 const as a hex string */
  2334. snprintf(buf, sizeof(buf), "f64#%016" PRIX64, value->i64);
  2335. const_ptr_type = F64_PTR_TYPE;
  2336. break;
  2337. default:
  2338. bh_assert(0);
  2339. return NULL;
  2340. }
  2341. /* Load f32/f64 const from exec_env->native_symbol[index] */
  2342. index = aot_get_native_symbol_index(comp_ctx, buf);
  2343. if (index < 0) {
  2344. return NULL;
  2345. }
  2346. if (!(const_index = I32_CONST(index))) {
  2347. aot_set_last_error("construct const index failed.");
  2348. return NULL;
  2349. }
  2350. if (!(const_addr = LLVMBuildInBoundsGEP(
  2351. comp_ctx->builder, base, &const_index, 1, "const_addr_tmp"))) {
  2352. aot_set_last_error("get const addr by index failed.");
  2353. return NULL;
  2354. }
  2355. if (!(const_addr = LLVMBuildBitCast(comp_ctx->builder, const_addr,
  2356. const_ptr_type, "const_addr"))) {
  2357. aot_set_last_error("cast const fialed.");
  2358. return NULL;
  2359. }
  2360. if (!(const_value =
  2361. LLVMBuildLoad(comp_ctx->builder, const_addr, "const_value"))) {
  2362. aot_set_last_error("load const failed.");
  2363. return NULL;
  2364. }
  2365. return const_value;
  2366. }