aot_llvm.c 92 KB

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