aot_llvm.c 92 KB

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