aot_llvm.c 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "aot_llvm.h"
  6. #include "aot_llvm_extra2.h"
  7. #include "aot_compiler.h"
  8. #include "aot_emit_exception.h"
  9. #include "aot_emit_table.h"
  10. #include "../aot/aot_runtime.h"
  11. #include "../aot/aot_intrinsic.h"
  12. #if WASM_ENABLE_DEBUG_AOT != 0
  13. #include "debug/dwarf_extractor.h"
  14. #endif
  15. static bool
  16. create_native_symbol(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx);
  17. static bool
  18. create_native_stack_bound(const AOTCompContext *comp_ctx,
  19. AOTFuncContext *func_ctx);
  20. static bool
  21. create_native_stack_top_min(const AOTCompContext *comp_ctx,
  22. AOTFuncContext *func_ctx);
  23. LLVMTypeRef
  24. wasm_type_to_llvm_type(const AOTLLVMTypes *llvm_types, uint8 wasm_type)
  25. {
  26. switch (wasm_type) {
  27. case VALUE_TYPE_I32:
  28. case VALUE_TYPE_FUNCREF:
  29. case VALUE_TYPE_EXTERNREF:
  30. return llvm_types->int32_type;
  31. case VALUE_TYPE_I64:
  32. return llvm_types->int64_type;
  33. case VALUE_TYPE_F32:
  34. return llvm_types->float32_type;
  35. case VALUE_TYPE_F64:
  36. return llvm_types->float64_type;
  37. case VALUE_TYPE_V128:
  38. return llvm_types->i64x2_vec_type;
  39. case VALUE_TYPE_VOID:
  40. return llvm_types->void_type;
  41. default:
  42. break;
  43. }
  44. return NULL;
  45. }
  46. static LLVMValueRef
  47. aot_add_llvm_func1(const AOTCompContext *comp_ctx, LLVMModuleRef module,
  48. uint32 func_index, uint32 param_count, LLVMTypeRef func_type,
  49. const char *prefix)
  50. {
  51. char func_name[48];
  52. LLVMValueRef func;
  53. LLVMValueRef local_value;
  54. uint32 i, j;
  55. /* Add LLVM function */
  56. snprintf(func_name, sizeof(func_name), "%s%d", prefix, func_index);
  57. if (!(func = LLVMAddFunction(module, func_name, func_type))) {
  58. aot_set_last_error("add LLVM function failed.");
  59. return NULL;
  60. }
  61. j = 0;
  62. local_value = LLVMGetParam(func, j++);
  63. LLVMSetValueName(local_value, "exec_env");
  64. /* Set parameter names */
  65. for (i = 0; i < param_count; i++) {
  66. local_value = LLVMGetParam(func, j++);
  67. LLVMSetValueName(local_value, "");
  68. }
  69. return func;
  70. }
  71. /*
  72. * create a basic func_ctx enough to call aot_emit_exception.
  73. *
  74. * that is:
  75. * - exec_env
  76. * - aot_inst
  77. * - native_symbol (if is_indirect_mode)
  78. */
  79. static bool
  80. create_basic_func_context(const AOTCompContext *comp_ctx,
  81. AOTFuncContext *func_ctx)
  82. {
  83. LLVMValueRef aot_inst_offset = I32_TWO, aot_inst_addr;
  84. /* Save the pameters for fast access */
  85. func_ctx->exec_env = LLVMGetParam(func_ctx->func, 0);
  86. /* Get aot inst address, the layout of exec_env is:
  87. exec_env->next, exec_env->prev, exec_env->module_inst, and argv_buf */
  88. if (!(aot_inst_addr = LLVMBuildInBoundsGEP2(
  89. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  90. &aot_inst_offset, 1, "aot_inst_addr"))) {
  91. aot_set_last_error("llvm build in bounds gep failed");
  92. goto fail;
  93. }
  94. /* Load aot inst */
  95. if (!(func_ctx->aot_inst = LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  96. aot_inst_addr, "aot_inst"))) {
  97. aot_set_last_error("llvm build load failed");
  98. goto fail;
  99. }
  100. if (comp_ctx->is_indirect_mode
  101. && !create_native_symbol(comp_ctx, func_ctx)) {
  102. goto fail;
  103. }
  104. return true;
  105. fail:
  106. return false;
  107. }
  108. /*
  109. * return if the "precheck" wrapper function can use tail call optimization
  110. */
  111. bool
  112. aot_target_precheck_can_use_musttail(const AOTCompContext *comp_ctx)
  113. {
  114. if (!strcmp(comp_ctx->target_arch, "xtensa")) {
  115. /*
  116. * xtensa windowed ABI doesn't have tail call optimization.
  117. *
  118. * Note: as of writing this, the xtensa version of LLVM
  119. * simply ignores the musttail attribute.
  120. * https://github.com/espressif/llvm-project/pull/73
  121. */
  122. return false;
  123. }
  124. if (!strcmp(comp_ctx->target_arch, "riscv32")
  125. || !strcmp(comp_ctx->target_arch, "riscv64")) {
  126. /*
  127. * REVISIT: actually, riscv can use tail call optimization
  128. * in some cases. I (yamamoto) don't know the exact conditions
  129. * though.
  130. */
  131. return false;
  132. }
  133. /*
  134. * x86-64/i386: true
  135. *
  136. * others: assume true for now
  137. */
  138. return true;
  139. }
  140. unsigned int
  141. aot_estimate_stack_usage_for_function_call(const AOTCompContext *comp_ctx,
  142. const AOTFuncType *callee_func_type)
  143. {
  144. /*
  145. * Estimate how much stack is necessary to make a function call.
  146. * This does not include the stack consumption of the callee function.
  147. *
  148. * For precise estimation, ideally this function needs to be
  149. * target-specific.
  150. * However, this implementation aims to be target-independent,
  151. * allowing a small overstimation, which is probably ok for our purpose.
  152. * (overflow detection and memory profiling)
  153. * On the other hand, an underestimation should be avoided as it
  154. * can cause more serious problems like silent data corruptions.
  155. *
  156. * Assumptions:
  157. *
  158. * - the first result is returned via a register.
  159. *
  160. * - all parameters, including exec_env and pointers to non-first
  161. * results, are passed via stack.
  162. * (this is a bit pessimistic than many of real calling conventions,
  163. * where some of parameters are passed via register.)
  164. *
  165. * - N-byte value needs N-byte alignment on stack.
  166. *
  167. * - a value smaller than a pointer is extended.
  168. * (eg. 4 byte values are extended to 8 byte on x86-64.)
  169. */
  170. const unsigned int param_count = callee_func_type->param_count;
  171. const unsigned int result_count = callee_func_type->result_count;
  172. unsigned int size = 0;
  173. unsigned int i;
  174. unsigned int nb;
  175. if (!strcmp(comp_ctx->target_arch, "xtensa")) {
  176. /*
  177. * In the xtensa windowed ABI, outgoing arguments are already
  178. * included in the callee's stack frame size, which equals to
  179. * the operand of the ENTRY instruction and what LLVM
  180. * MFI->getStackSize returns.
  181. */
  182. return 0;
  183. }
  184. /* exec_env */
  185. size = comp_ctx->pointer_size;
  186. /* parameters */
  187. for (i = 0; i < param_count; i++) {
  188. nb = wasm_value_type_cell_num(callee_func_type->types[i]) * 4;
  189. if (nb < comp_ctx->pointer_size) {
  190. nb = comp_ctx->pointer_size;
  191. }
  192. size = align_uint(size, nb) + nb;
  193. }
  194. /* pointers to results */
  195. nb = comp_ctx->pointer_size;
  196. for (i = 1; i < result_count; i++) {
  197. size = align_uint(size, nb) + nb;
  198. }
  199. /* return address */
  200. nb = comp_ctx->pointer_size;
  201. size = align_uint(size, nb) + nb;
  202. /*
  203. * some extra for possible arch-dependent things like
  204. * 16-byte alignment for x86_64.
  205. */
  206. size += 16;
  207. return size;
  208. }
  209. static uint32
  210. get_inst_extra_offset(AOTCompContext *comp_ctx)
  211. {
  212. const AOTCompData *comp_data = comp_ctx->comp_data;
  213. uint32 table_count = comp_data->import_table_count + comp_data->table_count;
  214. uint64 offset = get_tbl_inst_offset(comp_ctx, NULL, table_count);
  215. bh_assert(offset <= UINT_MAX);
  216. offset = align_uint(offset, 8);
  217. return offset;
  218. }
  219. /*
  220. * a "precheck" function performs a few things before calling wrapped_func.
  221. *
  222. * - update native_stack_top_min if necessary
  223. * - stack overflow check (if it does, trap)
  224. */
  225. static LLVMValueRef
  226. aot_add_precheck_function(AOTCompContext *comp_ctx, LLVMModuleRef module,
  227. uint32 func_index, uint32 orig_param_count,
  228. LLVMTypeRef func_type, LLVMValueRef wrapped_func)
  229. {
  230. LLVMValueRef precheck_func;
  231. LLVMBasicBlockRef begin = NULL;
  232. LLVMBasicBlockRef check_top_block = NULL;
  233. LLVMBasicBlockRef update_top_block = NULL;
  234. LLVMBasicBlockRef stack_bound_check_block = NULL;
  235. LLVMBasicBlockRef call_wrapped_func_block = NULL;
  236. LLVMValueRef *params = NULL;
  237. precheck_func =
  238. aot_add_llvm_func1(comp_ctx, module, func_index, orig_param_count,
  239. func_type, AOT_FUNC_PREFIX);
  240. if (!precheck_func) {
  241. goto fail;
  242. }
  243. begin = LLVMAppendBasicBlockInContext(comp_ctx->context, precheck_func,
  244. "begin");
  245. check_top_block = LLVMAppendBasicBlockInContext(
  246. comp_ctx->context, precheck_func, "check_top_block");
  247. if (comp_ctx->enable_stack_estimation) {
  248. update_top_block = LLVMAppendBasicBlockInContext(
  249. comp_ctx->context, precheck_func, "update_top_block");
  250. if (!update_top_block) {
  251. goto fail;
  252. }
  253. }
  254. stack_bound_check_block = LLVMAppendBasicBlockInContext(
  255. comp_ctx->context, precheck_func, "stack_bound_check_block");
  256. call_wrapped_func_block = LLVMAppendBasicBlockInContext(
  257. comp_ctx->context, precheck_func, "call_wrapped_func");
  258. if (!begin || !check_top_block || !stack_bound_check_block
  259. || !call_wrapped_func_block) {
  260. goto fail;
  261. }
  262. LLVMBuilderRef b = comp_ctx->builder;
  263. LLVMPositionBuilderAtEnd(b, begin);
  264. /* create a temporary minimum func_ctx */
  265. AOTFuncContext tmp;
  266. AOTFuncContext *func_ctx = &tmp;
  267. memset(func_ctx, 0, sizeof(*func_ctx));
  268. func_ctx->func = precheck_func;
  269. func_ctx->module = module;
  270. func_ctx->aot_func = comp_ctx->comp_data->funcs[func_index];
  271. #if WASM_ENABLE_DEBUG_AOT != 0
  272. func_ctx->debug_func = NULL;
  273. #endif
  274. if (!create_basic_func_context(comp_ctx, func_ctx))
  275. goto fail;
  276. if (comp_ctx->enable_stack_bound_check
  277. && !create_native_stack_bound(comp_ctx, func_ctx))
  278. goto fail;
  279. if (comp_ctx->enable_stack_estimation
  280. && !create_native_stack_top_min(comp_ctx, func_ctx)) {
  281. goto fail;
  282. }
  283. unsigned int param_count = LLVMCountParams(precheck_func);
  284. uint64 sz = param_count * sizeof(LLVMValueRef);
  285. params = wasm_runtime_malloc(sz);
  286. if (params == NULL) {
  287. goto fail;
  288. }
  289. LLVMGetParams(precheck_func, params);
  290. const bool is_64bit = comp_ctx->pointer_size == sizeof(uint64);
  291. LLVMTypeRef uintptr_type;
  292. if (is_64bit)
  293. uintptr_type = I64_TYPE;
  294. else
  295. uintptr_type = I32_TYPE;
  296. /*
  297. * load the stack pointer
  298. */
  299. LLVMValueRef sp_ptr = LLVMBuildAlloca(b, I32_TYPE, "sp_ptr");
  300. if (!sp_ptr) {
  301. goto fail;
  302. }
  303. LLVMValueRef sp = LLVMBuildPtrToInt(b, sp_ptr, uintptr_type, "sp");
  304. if (!sp) {
  305. goto fail;
  306. }
  307. /*
  308. * load the value for this wrapped function from the stack_sizes array
  309. */
  310. LLVMValueRef stack_sizes;
  311. if (comp_ctx->is_indirect_mode) {
  312. uint32 offset_u32;
  313. LLVMValueRef offset;
  314. LLVMValueRef stack_sizes_p;
  315. offset_u32 = get_inst_extra_offset(comp_ctx);
  316. offset_u32 += offsetof(AOTModuleInstanceExtra, stack_sizes);
  317. offset = I32_CONST(offset_u32);
  318. if (!offset) {
  319. goto fail;
  320. }
  321. stack_sizes_p =
  322. LLVMBuildInBoundsGEP2(b, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  323. "aot_inst_stack_sizes_p");
  324. if (!stack_sizes_p) {
  325. goto fail;
  326. }
  327. stack_sizes =
  328. LLVMBuildLoad2(b, INT32_PTR_TYPE, stack_sizes_p, "stack_sizes");
  329. if (!stack_sizes) {
  330. goto fail;
  331. }
  332. }
  333. else {
  334. stack_sizes = comp_ctx->stack_sizes;
  335. }
  336. LLVMValueRef func_index_const = I32_CONST(func_index);
  337. LLVMValueRef sizes =
  338. LLVMBuildBitCast(b, stack_sizes, INT32_PTR_TYPE, "sizes");
  339. if (!sizes) {
  340. goto fail;
  341. }
  342. LLVMValueRef sizep = LLVMBuildInBoundsGEP2(b, I32_TYPE, sizes,
  343. &func_index_const, 1, "sizep");
  344. if (!sizep) {
  345. goto fail;
  346. }
  347. LLVMValueRef size32 = LLVMBuildLoad2(b, I32_TYPE, sizep, "size32");
  348. if (!size32) {
  349. goto fail;
  350. }
  351. LLVMValueRef size;
  352. if (is_64bit) {
  353. size = LLVMBuildZExt(b, size32, uintptr_type, "size");
  354. if (!size) {
  355. goto fail;
  356. }
  357. }
  358. else {
  359. size = size32;
  360. }
  361. /*
  362. * calculate new sp
  363. */
  364. LLVMValueRef underflow =
  365. LLVMBuildICmp(b, LLVMIntULT, sp, size, "underflow");
  366. if (!underflow) {
  367. goto fail;
  368. }
  369. LLVMValueRef new_sp = LLVMBuildSub(b, sp, size, "new_sp");
  370. if (!new_sp) {
  371. goto fail;
  372. }
  373. if (!LLVMBuildBr(b, check_top_block)) {
  374. goto fail;
  375. }
  376. LLVMPositionBuilderAtEnd(b, check_top_block);
  377. if (comp_ctx->enable_stack_estimation) {
  378. /*
  379. * load native_stack_top_min from the exec_env
  380. */
  381. LLVMValueRef top_min =
  382. LLVMBuildLoad2(b, OPQ_PTR_TYPE, func_ctx->native_stack_top_min_addr,
  383. "native_stack_top_min");
  384. if (!top_min) {
  385. goto fail;
  386. }
  387. LLVMValueRef top_min_int = LLVMBuildPtrToInt(
  388. b, top_min, uintptr_type, "native_stack_top_min_int");
  389. if (!top_min_int) {
  390. goto fail;
  391. }
  392. bh_assert(update_top_block);
  393. /*
  394. * update native_stack_top_min if
  395. * new_sp = sp - size < native_stack_top_min
  396. *
  397. * Note: unless the stack has already overflown in this exec_env,
  398. * native_stack_bound <= native_stack_top_min
  399. */
  400. LLVMValueRef cmp_top =
  401. LLVMBuildICmp(b, LLVMIntULT, new_sp, top_min_int, "cmp_top");
  402. if (!cmp_top) {
  403. goto fail;
  404. }
  405. cmp_top = LLVMBuildOr(b, underflow, cmp_top, "cmp_top2");
  406. if (!cmp_top) {
  407. goto fail;
  408. }
  409. if (!LLVMBuildCondBr(b, cmp_top, update_top_block,
  410. call_wrapped_func_block)) {
  411. aot_set_last_error("llvm build cond br failed.");
  412. goto fail;
  413. }
  414. /*
  415. * update native_stack_top_min
  416. */
  417. LLVMPositionBuilderAtEnd(b, update_top_block);
  418. LLVMValueRef new_sp_ptr =
  419. LLVMBuildIntToPtr(b, new_sp, INT8_PTR_TYPE, "new_sp_ptr");
  420. if (!new_sp_ptr) {
  421. goto fail;
  422. }
  423. if (!LLVMBuildStore(b, new_sp_ptr,
  424. func_ctx->native_stack_top_min_addr)) {
  425. goto fail;
  426. }
  427. if (!LLVMBuildBr(b, stack_bound_check_block)) {
  428. goto fail;
  429. }
  430. }
  431. else {
  432. if (!LLVMBuildBr(b, stack_bound_check_block)) {
  433. goto fail;
  434. }
  435. }
  436. LLVMPositionBuilderAtEnd(b, stack_bound_check_block);
  437. if (comp_ctx->enable_stack_bound_check) {
  438. /*
  439. * trap if new_sp < native_stack_bound
  440. */
  441. LLVMValueRef bound_int = LLVMBuildPtrToInt(
  442. b, func_ctx->native_stack_bound, uintptr_type, "bound_base_int");
  443. if (!bound_int) {
  444. goto fail;
  445. }
  446. LLVMValueRef cmp =
  447. LLVMBuildICmp(b, LLVMIntULT, new_sp, bound_int, "cmp");
  448. if (!cmp) {
  449. goto fail;
  450. }
  451. cmp = LLVMBuildOr(b, underflow, cmp, "cmp2");
  452. if (!cmp) {
  453. goto fail;
  454. }
  455. /* todo: @llvm.expect.i1(i1 %cmp, i1 0) */
  456. if (!aot_emit_exception(comp_ctx, func_ctx, EXCE_NATIVE_STACK_OVERFLOW,
  457. true, cmp, call_wrapped_func_block))
  458. goto fail;
  459. }
  460. else {
  461. if (!LLVMBuildBr(b, call_wrapped_func_block)) {
  462. goto fail;
  463. }
  464. }
  465. /*
  466. * call the wrapped function
  467. * use a tail-call if possible
  468. */
  469. LLVMPositionBuilderAtEnd(b, call_wrapped_func_block);
  470. const char *name = "tail_call";
  471. LLVMTypeRef ret_type = LLVMGetReturnType(func_type);
  472. if (ret_type == VOID_TYPE) {
  473. name = "";
  474. }
  475. LLVMValueRef retval =
  476. LLVMBuildCall2(b, func_type, wrapped_func, params, param_count, name);
  477. if (!retval) {
  478. goto fail;
  479. }
  480. wasm_runtime_free(params);
  481. params = NULL;
  482. if (aot_target_precheck_can_use_musttail(comp_ctx)) {
  483. LLVMSetTailCallKind(retval, LLVMTailCallKindMustTail);
  484. }
  485. else {
  486. LLVMSetTailCallKind(retval, LLVMTailCallKindTail);
  487. }
  488. if (ret_type == VOID_TYPE) {
  489. if (!LLVMBuildRetVoid(b)) {
  490. goto fail;
  491. }
  492. }
  493. else {
  494. if (!LLVMBuildRet(b, retval)) {
  495. goto fail;
  496. }
  497. }
  498. return precheck_func;
  499. fail:
  500. if (params != NULL) {
  501. wasm_runtime_free(params);
  502. }
  503. aot_set_last_error("failed to build precheck wrapper function.");
  504. return NULL;
  505. }
  506. /**
  507. * Add LLVM function
  508. */
  509. static LLVMValueRef
  510. aot_add_llvm_func(AOTCompContext *comp_ctx, LLVMModuleRef module,
  511. const AOTFuncType *aot_func_type, uint32 func_index,
  512. LLVMTypeRef *p_func_type, LLVMValueRef *p_precheck_func)
  513. {
  514. LLVMValueRef func = NULL;
  515. LLVMTypeRef *param_types, ret_type, func_type;
  516. LLVMTypeRef func_type_wrapper;
  517. LLVMValueRef func_wrapper;
  518. LLVMBasicBlockRef func_begin;
  519. char func_name[48];
  520. uint64 size;
  521. uint32 i, j = 0, param_count = (uint64)aot_func_type->param_count;
  522. uint32 backend_thread_num, compile_thread_num;
  523. /* exec env as first parameter */
  524. param_count++;
  525. /* Extra wasm function results(except the first one)'s address are
  526. * appended to aot function parameters. */
  527. if (aot_func_type->result_count > 1)
  528. param_count += aot_func_type->result_count - 1;
  529. /* Initialize parameter types of the LLVM function */
  530. size = sizeof(LLVMTypeRef) * ((uint64)param_count);
  531. if (size >= UINT32_MAX
  532. || !(param_types = wasm_runtime_malloc((uint32)size))) {
  533. aot_set_last_error("allocate memory failed.");
  534. return NULL;
  535. }
  536. /* exec env as first parameter */
  537. param_types[j++] = comp_ctx->exec_env_type;
  538. for (i = 0; i < aot_func_type->param_count; i++)
  539. param_types[j++] = TO_LLVM_TYPE(aot_func_type->types[i]);
  540. /* Extra results' address */
  541. for (i = 1; i < aot_func_type->result_count; i++, j++) {
  542. param_types[j] =
  543. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count + i]);
  544. if (!(param_types[j] = LLVMPointerType(param_types[j], 0))) {
  545. aot_set_last_error("llvm get pointer type failed.");
  546. goto fail;
  547. }
  548. }
  549. /* Resolve return type of the LLVM function */
  550. if (aot_func_type->result_count)
  551. ret_type =
  552. TO_LLVM_TYPE(aot_func_type->types[aot_func_type->param_count]);
  553. else
  554. ret_type = VOID_TYPE;
  555. /* Resolve function prototype */
  556. if (!(func_type =
  557. LLVMFunctionType(ret_type, param_types, param_count, false))) {
  558. aot_set_last_error("create LLVM function type failed.");
  559. goto fail;
  560. }
  561. bh_assert(func_index < comp_ctx->func_ctx_count);
  562. bh_assert(LLVMGetReturnType(func_type) == ret_type);
  563. const char *prefix = AOT_FUNC_PREFIX;
  564. const bool need_precheck =
  565. comp_ctx->enable_stack_bound_check || comp_ctx->enable_stack_estimation;
  566. if (need_precheck) {
  567. /*
  568. * REVISIT: probably this breaks windows hw bound check
  569. * (the RtlAddFunctionTable stuff)
  570. */
  571. prefix = AOT_FUNC_INTERNAL_PREFIX;
  572. }
  573. if (!(func = aot_add_llvm_func1(comp_ctx, module, func_index,
  574. aot_func_type->param_count, func_type,
  575. prefix)))
  576. goto fail;
  577. if (comp_ctx->is_indirect_mode) {
  578. /* avoid LUT relocations ("switch-table") */
  579. LLVMAttributeRef attr_no_jump_tables = LLVMCreateStringAttribute(
  580. comp_ctx->context, "no-jump-tables", strlen("no-jump-tables"),
  581. "true", strlen("true"));
  582. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex,
  583. attr_no_jump_tables);
  584. }
  585. if (need_precheck) {
  586. if (!comp_ctx->is_jit_mode)
  587. LLVMSetLinkage(func, LLVMInternalLinkage);
  588. unsigned int kind =
  589. LLVMGetEnumAttributeKindForName("noinline", strlen("noinline"));
  590. LLVMAttributeRef attr_noinline =
  591. LLVMCreateEnumAttribute(comp_ctx->context, kind, 0);
  592. LLVMAddAttributeAtIndex(func, LLVMAttributeFunctionIndex,
  593. attr_noinline);
  594. LLVMValueRef precheck_func = aot_add_precheck_function(
  595. comp_ctx, module, func_index, aot_func_type->param_count, func_type,
  596. func);
  597. if (!precheck_func)
  598. goto fail;
  599. LLVMAddAttributeAtIndex(precheck_func, LLVMAttributeFunctionIndex,
  600. attr_noinline);
  601. *p_precheck_func = precheck_func;
  602. }
  603. else {
  604. *p_precheck_func = func;
  605. }
  606. if (p_func_type)
  607. *p_func_type = func_type;
  608. backend_thread_num = WASM_ORC_JIT_BACKEND_THREAD_NUM;
  609. compile_thread_num = WASM_ORC_JIT_COMPILE_THREAD_NUM;
  610. /* Add the jit wrapper function with simple prototype, so that we
  611. can easily call it to trigger its compilation and let LLVM JIT
  612. compile the actual jit functions by adding them into the function
  613. list in the PartitionFunction callback */
  614. if (comp_ctx->is_jit_mode
  615. && (func_index % (backend_thread_num * compile_thread_num)
  616. < backend_thread_num)) {
  617. func_type_wrapper = LLVMFunctionType(VOID_TYPE, NULL, 0, false);
  618. if (!func_type_wrapper) {
  619. aot_set_last_error("create LLVM function type failed.");
  620. goto fail;
  621. }
  622. snprintf(func_name, sizeof(func_name), "%s%d%s", AOT_FUNC_PREFIX,
  623. func_index, "_wrapper");
  624. if (!(func_wrapper =
  625. LLVMAddFunction(module, func_name, func_type_wrapper))) {
  626. aot_set_last_error("add LLVM function failed.");
  627. goto fail;
  628. }
  629. if (!(func_begin = LLVMAppendBasicBlockInContext(
  630. comp_ctx->context, func_wrapper, "func_begin"))) {
  631. aot_set_last_error("add LLVM basic block failed.");
  632. goto fail;
  633. }
  634. LLVMPositionBuilderAtEnd(comp_ctx->builder, func_begin);
  635. if (!LLVMBuildRetVoid(comp_ctx->builder)) {
  636. aot_set_last_error("llvm build ret failed.");
  637. goto fail;
  638. }
  639. }
  640. fail:
  641. wasm_runtime_free(param_types);
  642. return func;
  643. }
  644. static void
  645. free_block_memory(AOTBlock *block)
  646. {
  647. if (block->param_types)
  648. wasm_runtime_free(block->param_types);
  649. if (block->result_types)
  650. wasm_runtime_free(block->result_types);
  651. wasm_runtime_free(block);
  652. }
  653. /**
  654. * Create first AOTBlock, or function block for the function
  655. */
  656. static AOTBlock *
  657. aot_create_func_block(const AOTCompContext *comp_ctx,
  658. const AOTFuncContext *func_ctx, const AOTFunc *func,
  659. const AOTFuncType *aot_func_type)
  660. {
  661. AOTBlock *aot_block;
  662. uint32 param_count = aot_func_type->param_count,
  663. result_count = aot_func_type->result_count;
  664. /* Allocate memory */
  665. if (!(aot_block = wasm_runtime_malloc(sizeof(AOTBlock)))) {
  666. aot_set_last_error("allocate memory failed.");
  667. return NULL;
  668. }
  669. memset(aot_block, 0, sizeof(AOTBlock));
  670. if (param_count
  671. && !(aot_block->param_types = wasm_runtime_malloc(param_count))) {
  672. aot_set_last_error("allocate memory failed.");
  673. goto fail;
  674. }
  675. if (result_count) {
  676. if (!(aot_block->result_types = wasm_runtime_malloc(result_count))) {
  677. aot_set_last_error("allocate memory failed.");
  678. goto fail;
  679. }
  680. }
  681. /* Set block data */
  682. aot_block->label_type = LABEL_TYPE_FUNCTION;
  683. aot_block->param_count = param_count;
  684. if (param_count) {
  685. bh_memcpy_s(aot_block->param_types, param_count, aot_func_type->types,
  686. param_count);
  687. }
  688. aot_block->result_count = result_count;
  689. if (result_count) {
  690. bh_memcpy_s(aot_block->result_types, result_count,
  691. aot_func_type->types + param_count, result_count);
  692. }
  693. aot_block->wasm_code_end = func->code + func->code_size;
  694. /* Add function entry block */
  695. if (!(aot_block->llvm_entry_block = LLVMAppendBasicBlockInContext(
  696. comp_ctx->context, func_ctx->func, "func_begin"))) {
  697. aot_set_last_error("add LLVM basic block failed.");
  698. goto fail;
  699. }
  700. return aot_block;
  701. fail:
  702. free_block_memory(aot_block);
  703. return NULL;
  704. }
  705. static bool
  706. create_argv_buf(AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  707. {
  708. LLVMValueRef argv_buf_offset = I32_THREE, argv_buf_addr;
  709. LLVMTypeRef int32_ptr_type;
  710. /* Get argv buffer address */
  711. if (!(argv_buf_addr = LLVMBuildInBoundsGEP2(
  712. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  713. &argv_buf_offset, 1, "argv_buf_addr"))) {
  714. aot_set_last_error("llvm build in bounds gep failed");
  715. return false;
  716. }
  717. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  718. aot_set_last_error("llvm add pointer type failed");
  719. return false;
  720. }
  721. /* Convert to int32 pointer type */
  722. if (!(argv_buf_addr = LLVMBuildBitCast(comp_ctx->builder, argv_buf_addr,
  723. int32_ptr_type, "argv_buf_ptr"))) {
  724. aot_set_last_error("llvm build load failed");
  725. return false;
  726. }
  727. if (!(func_ctx->argv_buf = LLVMBuildLoad2(comp_ctx->builder, INT32_PTR_TYPE,
  728. argv_buf_addr, "argv_buf"))) {
  729. aot_set_last_error("llvm build load failed");
  730. return false;
  731. }
  732. return true;
  733. }
  734. static bool
  735. create_native_stack_bound(const AOTCompContext *comp_ctx,
  736. AOTFuncContext *func_ctx)
  737. {
  738. LLVMValueRef stack_bound_offset = I32_FOUR, stack_bound_addr;
  739. if (!(stack_bound_addr = LLVMBuildInBoundsGEP2(
  740. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  741. &stack_bound_offset, 1, "stack_bound_addr"))) {
  742. aot_set_last_error("llvm build in bounds gep failed");
  743. return false;
  744. }
  745. if (!(func_ctx->native_stack_bound =
  746. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, stack_bound_addr,
  747. "native_stack_bound"))) {
  748. aot_set_last_error("llvm build load failed");
  749. return false;
  750. }
  751. return true;
  752. }
  753. static bool
  754. create_native_stack_top_min(const AOTCompContext *comp_ctx,
  755. AOTFuncContext *func_ctx)
  756. {
  757. LLVMValueRef offset = I32_NINE;
  758. if (!(func_ctx->native_stack_top_min_addr = LLVMBuildInBoundsGEP2(
  759. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env, &offset, 1,
  760. "native_stack_top_min_addr"))) {
  761. aot_set_last_error("llvm build in bounds gep failed");
  762. return false;
  763. }
  764. return true;
  765. }
  766. static bool
  767. create_aux_stack_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  768. {
  769. LLVMValueRef aux_stack_bound_offset = I32_SIX, aux_stack_bound_addr;
  770. LLVMValueRef aux_stack_bottom_offset = I32_SEVEN, aux_stack_bottom_addr;
  771. /* Get aux stack boundary address */
  772. if (!(aux_stack_bound_addr = LLVMBuildInBoundsGEP2(
  773. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  774. &aux_stack_bound_offset, 1, "aux_stack_bound_addr"))) {
  775. aot_set_last_error("llvm build in bounds gep failed");
  776. return false;
  777. }
  778. if (!(aux_stack_bound_addr =
  779. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bound_addr,
  780. INT32_PTR_TYPE, "aux_stack_bound_ptr"))) {
  781. aot_set_last_error("llvm build bit cast failed");
  782. return false;
  783. }
  784. if (!(func_ctx->aux_stack_bound =
  785. LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, aux_stack_bound_addr,
  786. "aux_stack_bound"))) {
  787. aot_set_last_error("llvm build load failed");
  788. return false;
  789. }
  790. /* Get aux stack bottom address */
  791. if (!(aux_stack_bottom_addr = LLVMBuildInBoundsGEP2(
  792. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  793. &aux_stack_bottom_offset, 1, "aux_stack_bottom_addr"))) {
  794. aot_set_last_error("llvm build in bounds gep failed");
  795. return false;
  796. }
  797. if (!(aux_stack_bottom_addr =
  798. LLVMBuildBitCast(comp_ctx->builder, aux_stack_bottom_addr,
  799. INT32_PTR_TYPE, "aux_stack_bottom_ptr"))) {
  800. aot_set_last_error("llvm build bit cast failed");
  801. return false;
  802. }
  803. if (!(func_ctx->aux_stack_bottom =
  804. LLVMBuildLoad2(comp_ctx->builder, I32_TYPE, aux_stack_bottom_addr,
  805. "aux_stack_bottom"))) {
  806. aot_set_last_error("llvm build load failed");
  807. return false;
  808. }
  809. return true;
  810. }
  811. static bool
  812. create_native_symbol(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  813. {
  814. LLVMValueRef native_symbol_offset = I32_EIGHT, native_symbol_addr;
  815. if (!(native_symbol_addr = LLVMBuildInBoundsGEP2(
  816. comp_ctx->builder, OPQ_PTR_TYPE, func_ctx->exec_env,
  817. &native_symbol_offset, 1, "native_symbol_addr"))) {
  818. aot_set_last_error("llvm build in bounds gep failed");
  819. return false;
  820. }
  821. if (!(func_ctx->native_symbol =
  822. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  823. native_symbol_addr, "native_symbol_tmp"))) {
  824. aot_set_last_error("llvm build bit cast failed");
  825. return false;
  826. }
  827. if (!(func_ctx->native_symbol =
  828. LLVMBuildBitCast(comp_ctx->builder, func_ctx->native_symbol,
  829. comp_ctx->exec_env_type, "native_symbol"))) {
  830. aot_set_last_error("llvm build bit cast failed");
  831. return false;
  832. }
  833. return true;
  834. }
  835. static bool
  836. create_local_variables(const AOTCompData *comp_data,
  837. const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  838. const AOTFunc *func)
  839. {
  840. AOTFuncType *aot_func_type =
  841. (AOTFuncType *)comp_data->types[func->func_type_index];
  842. char local_name[32];
  843. uint32 i, j = 1;
  844. for (i = 0; i < aot_func_type->param_count; i++, j++) {
  845. snprintf(local_name, sizeof(local_name), "l%d", i);
  846. func_ctx->locals[i] =
  847. LLVMBuildAlloca(comp_ctx->builder,
  848. TO_LLVM_TYPE(aot_func_type->types[i]), local_name);
  849. if (!func_ctx->locals[i]) {
  850. aot_set_last_error("llvm build alloca failed.");
  851. return false;
  852. }
  853. if (!LLVMBuildStore(comp_ctx->builder, LLVMGetParam(func_ctx->func, j),
  854. func_ctx->locals[i])) {
  855. aot_set_last_error("llvm build store failed.");
  856. return false;
  857. }
  858. }
  859. for (i = 0; i < func->local_count; i++) {
  860. LLVMTypeRef local_type;
  861. LLVMValueRef local_value = NULL;
  862. snprintf(local_name, sizeof(local_name), "l%d",
  863. aot_func_type->param_count + i);
  864. local_type = TO_LLVM_TYPE(func->local_types[i]);
  865. func_ctx->locals[aot_func_type->param_count + i] =
  866. LLVMBuildAlloca(comp_ctx->builder, local_type, local_name);
  867. if (!func_ctx->locals[aot_func_type->param_count + i]) {
  868. aot_set_last_error("llvm build alloca failed.");
  869. return false;
  870. }
  871. switch (func->local_types[i]) {
  872. case VALUE_TYPE_I32:
  873. local_value = I32_ZERO;
  874. break;
  875. case VALUE_TYPE_I64:
  876. local_value = I64_ZERO;
  877. break;
  878. case VALUE_TYPE_F32:
  879. local_value = F32_ZERO;
  880. break;
  881. case VALUE_TYPE_F64:
  882. local_value = F64_ZERO;
  883. break;
  884. case VALUE_TYPE_V128:
  885. local_value = V128_i64x2_ZERO;
  886. break;
  887. case VALUE_TYPE_FUNCREF:
  888. case VALUE_TYPE_EXTERNREF:
  889. local_value = REF_NULL;
  890. break;
  891. default:
  892. bh_assert(0);
  893. break;
  894. }
  895. if (!LLVMBuildStore(comp_ctx->builder, local_value,
  896. func_ctx->locals[aot_func_type->param_count + i])) {
  897. aot_set_last_error("llvm build store failed.");
  898. return false;
  899. }
  900. }
  901. return true;
  902. }
  903. static bool
  904. create_memory_info(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx,
  905. LLVMTypeRef int8_ptr_type, uint32 func_index)
  906. {
  907. LLVMValueRef offset, mem_info_base;
  908. uint32 memory_count;
  909. WASMModule *module = comp_ctx->comp_data->wasm_module;
  910. WASMFunction *func = module->functions[func_index];
  911. LLVMTypeRef bound_check_type;
  912. bool mem_space_unchanged =
  913. (!func->has_op_memory_grow && !func->has_op_func_call)
  914. || (!module->possible_memory_grow);
  915. #if WASM_ENABLE_SHARED_MEMORY != 0
  916. bool is_shared_memory;
  917. #endif
  918. func_ctx->mem_space_unchanged = mem_space_unchanged;
  919. memory_count = module->memory_count + module->import_memory_count;
  920. /* If the module dosen't have memory, reserve
  921. one mem_info space with empty content */
  922. if (memory_count == 0)
  923. memory_count = 1;
  924. if (!(func_ctx->mem_info =
  925. wasm_runtime_malloc(sizeof(AOTMemInfo) * memory_count))) {
  926. return false;
  927. }
  928. memset(func_ctx->mem_info, 0, sizeof(AOTMemInfo));
  929. /* Currently we only create memory info for memory 0 */
  930. /* Load memory base address */
  931. #if WASM_ENABLE_SHARED_MEMORY != 0
  932. is_shared_memory =
  933. comp_ctx->comp_data->memories[0].memory_flags & 0x02 ? true : false;
  934. if (is_shared_memory) {
  935. LLVMValueRef shared_mem_addr;
  936. offset = I32_CONST(offsetof(AOTModuleInstance, memories));
  937. if (!offset) {
  938. aot_set_last_error("create llvm const failed.");
  939. return false;
  940. }
  941. /* aot_inst->memories */
  942. if (!(shared_mem_addr = LLVMBuildInBoundsGEP2(
  943. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  944. "shared_mem_addr_offset"))) {
  945. aot_set_last_error("llvm build in bounds gep failed");
  946. return false;
  947. }
  948. if (!(shared_mem_addr =
  949. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  950. int8_ptr_type, "shared_mem_addr_ptr"))) {
  951. aot_set_last_error("llvm build bit cast failed");
  952. return false;
  953. }
  954. /* aot_inst->memories[0] */
  955. if (!(shared_mem_addr =
  956. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  957. shared_mem_addr, "shared_mem_addr"))) {
  958. aot_set_last_error("llvm build load failed");
  959. return false;
  960. }
  961. if (!(shared_mem_addr =
  962. LLVMBuildBitCast(comp_ctx->builder, shared_mem_addr,
  963. int8_ptr_type, "shared_mem_addr_ptr"))) {
  964. aot_set_last_error("llvm build bit cast failed");
  965. return false;
  966. }
  967. if (!(shared_mem_addr =
  968. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  969. shared_mem_addr, "shared_mem_addr"))) {
  970. aot_set_last_error("llvm build load failed");
  971. return false;
  972. }
  973. /* memories[0]->memory_data */
  974. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data));
  975. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildInBoundsGEP2(
  976. comp_ctx->builder, INT8_TYPE, shared_mem_addr, &offset, 1,
  977. "mem_base_addr_offset"))) {
  978. aot_set_last_error("llvm build in bounds gep failed");
  979. return false;
  980. }
  981. /* memories[0]->cur_page_count */
  982. offset = I32_CONST(offsetof(AOTMemoryInstance, cur_page_count));
  983. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  984. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE,
  985. shared_mem_addr, &offset, 1,
  986. "mem_cur_page_offset"))) {
  987. aot_set_last_error("llvm build in bounds gep failed");
  988. return false;
  989. }
  990. /* memories[0]->memory_data_size */
  991. offset = I32_CONST(offsetof(AOTMemoryInstance, memory_data_size));
  992. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildInBoundsGEP2(
  993. comp_ctx->builder, INT8_TYPE, shared_mem_addr, &offset, 1,
  994. "mem_data_size_offset"))) {
  995. aot_set_last_error("llvm build in bounds gep failed");
  996. return false;
  997. }
  998. }
  999. else
  1000. #endif
  1001. {
  1002. uint32 offset_of_global_table_data;
  1003. if (comp_ctx->is_jit_mode)
  1004. offset_of_global_table_data =
  1005. offsetof(WASMModuleInstance, global_table_data);
  1006. else
  1007. offset_of_global_table_data =
  1008. offsetof(AOTModuleInstance, global_table_data);
  1009. offset = I32_CONST(offset_of_global_table_data
  1010. + offsetof(AOTMemoryInstance, memory_data));
  1011. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildInBoundsGEP2(
  1012. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1013. "mem_base_addr_offset"))) {
  1014. aot_set_last_error("llvm build in bounds gep failed");
  1015. return false;
  1016. }
  1017. offset = I32_CONST(offset_of_global_table_data
  1018. + offsetof(AOTMemoryInstance, cur_page_count));
  1019. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  1020. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE,
  1021. func_ctx->aot_inst, &offset, 1,
  1022. "mem_cur_page_offset"))) {
  1023. aot_set_last_error("llvm build in bounds gep failed");
  1024. return false;
  1025. }
  1026. offset = I32_CONST(offset_of_global_table_data
  1027. + offsetof(AOTMemoryInstance, memory_data_size));
  1028. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildInBoundsGEP2(
  1029. comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst, &offset, 1,
  1030. "mem_data_size_offset"))) {
  1031. aot_set_last_error("llvm build in bounds gep failed");
  1032. return false;
  1033. }
  1034. }
  1035. /* Store mem info base address before cast */
  1036. mem_info_base = func_ctx->mem_info[0].mem_base_addr;
  1037. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildBitCast(
  1038. comp_ctx->builder, func_ctx->mem_info[0].mem_base_addr,
  1039. int8_ptr_type, "mem_base_addr_ptr"))) {
  1040. aot_set_last_error("llvm build bit cast failed");
  1041. return false;
  1042. }
  1043. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr = LLVMBuildBitCast(
  1044. comp_ctx->builder, func_ctx->mem_info[0].mem_cur_page_count_addr,
  1045. INT32_PTR_TYPE, "mem_cur_page_ptr"))) {
  1046. aot_set_last_error("llvm build bit cast failed");
  1047. return false;
  1048. }
  1049. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildBitCast(
  1050. comp_ctx->builder, func_ctx->mem_info[0].mem_data_size_addr,
  1051. INT32_PTR_TYPE, "mem_data_size_ptr"))) {
  1052. aot_set_last_error("llvm build bit cast failed");
  1053. return false;
  1054. }
  1055. if (mem_space_unchanged) {
  1056. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad2(
  1057. comp_ctx->builder, OPQ_PTR_TYPE,
  1058. func_ctx->mem_info[0].mem_base_addr, "mem_base_addr"))) {
  1059. aot_set_last_error("llvm build load failed");
  1060. return false;
  1061. }
  1062. if (!(func_ctx->mem_info[0].mem_cur_page_count_addr =
  1063. LLVMBuildLoad2(comp_ctx->builder, I32_TYPE,
  1064. func_ctx->mem_info[0].mem_cur_page_count_addr,
  1065. "mem_cur_page_count"))) {
  1066. aot_set_last_error("llvm build load failed");
  1067. return false;
  1068. }
  1069. if (!(func_ctx->mem_info[0].mem_data_size_addr = LLVMBuildLoad2(
  1070. comp_ctx->builder, I32_TYPE,
  1071. func_ctx->mem_info[0].mem_data_size_addr, "mem_data_size"))) {
  1072. aot_set_last_error("llvm build load failed");
  1073. return false;
  1074. }
  1075. }
  1076. #if WASM_ENABLE_SHARED_MEMORY != 0
  1077. else if (is_shared_memory) {
  1078. /* The base address for shared memory will never changed,
  1079. we can load the value here */
  1080. if (!(func_ctx->mem_info[0].mem_base_addr = LLVMBuildLoad2(
  1081. comp_ctx->builder, OPQ_PTR_TYPE,
  1082. func_ctx->mem_info[0].mem_base_addr, "mem_base_addr"))) {
  1083. aot_set_last_error("llvm build load failed");
  1084. return false;
  1085. }
  1086. }
  1087. #endif
  1088. bound_check_type = (comp_ctx->pointer_size == sizeof(uint64))
  1089. ? INT64_PTR_TYPE
  1090. : INT32_PTR_TYPE;
  1091. /* Load memory bound check constants */
  1092. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_1byte)
  1093. - offsetof(AOTMemoryInstance, memory_data));
  1094. if (!(func_ctx->mem_info[0].mem_bound_check_1byte =
  1095. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1096. &offset, 1, "bound_check_1byte_offset"))) {
  1097. aot_set_last_error("llvm build in bounds gep failed");
  1098. return false;
  1099. }
  1100. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildBitCast(
  1101. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_1byte,
  1102. bound_check_type, "bound_check_1byte_ptr"))) {
  1103. aot_set_last_error("llvm build bit cast failed");
  1104. return false;
  1105. }
  1106. if (mem_space_unchanged) {
  1107. if (!(func_ctx->mem_info[0].mem_bound_check_1byte = LLVMBuildLoad2(
  1108. comp_ctx->builder,
  1109. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1110. : I32_TYPE,
  1111. func_ctx->mem_info[0].mem_bound_check_1byte,
  1112. "bound_check_1byte"))) {
  1113. aot_set_last_error("llvm build load failed");
  1114. return false;
  1115. }
  1116. }
  1117. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_2bytes)
  1118. - offsetof(AOTMemoryInstance, memory_data));
  1119. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes =
  1120. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1121. &offset, 1, "bound_check_2bytes_offset"))) {
  1122. aot_set_last_error("llvm build in bounds gep failed");
  1123. return false;
  1124. }
  1125. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildBitCast(
  1126. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_2bytes,
  1127. bound_check_type, "bound_check_2bytes_ptr"))) {
  1128. aot_set_last_error("llvm build bit cast failed");
  1129. return false;
  1130. }
  1131. if (mem_space_unchanged) {
  1132. if (!(func_ctx->mem_info[0].mem_bound_check_2bytes = LLVMBuildLoad2(
  1133. comp_ctx->builder,
  1134. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1135. : I32_TYPE,
  1136. func_ctx->mem_info[0].mem_bound_check_2bytes,
  1137. "bound_check_2bytes"))) {
  1138. aot_set_last_error("llvm build load failed");
  1139. return false;
  1140. }
  1141. }
  1142. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_4bytes)
  1143. - offsetof(AOTMemoryInstance, memory_data));
  1144. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes =
  1145. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1146. &offset, 1, "bound_check_4bytes_offset"))) {
  1147. aot_set_last_error("llvm build in bounds gep failed");
  1148. return false;
  1149. }
  1150. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildBitCast(
  1151. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_4bytes,
  1152. bound_check_type, "bound_check_4bytes_ptr"))) {
  1153. aot_set_last_error("llvm build bit cast failed");
  1154. return false;
  1155. }
  1156. if (mem_space_unchanged) {
  1157. if (!(func_ctx->mem_info[0].mem_bound_check_4bytes = LLVMBuildLoad2(
  1158. comp_ctx->builder,
  1159. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1160. : I32_TYPE,
  1161. func_ctx->mem_info[0].mem_bound_check_4bytes,
  1162. "bound_check_4bytes"))) {
  1163. aot_set_last_error("llvm build load failed");
  1164. return false;
  1165. }
  1166. }
  1167. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_8bytes)
  1168. - offsetof(AOTMemoryInstance, memory_data));
  1169. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes =
  1170. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, mem_info_base,
  1171. &offset, 1, "bound_check_8bytes_offset"))) {
  1172. aot_set_last_error("llvm build in bounds gep failed");
  1173. return false;
  1174. }
  1175. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildBitCast(
  1176. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_8bytes,
  1177. bound_check_type, "bound_check_8bytes_ptr"))) {
  1178. aot_set_last_error("llvm build bit cast failed");
  1179. return false;
  1180. }
  1181. if (mem_space_unchanged) {
  1182. if (!(func_ctx->mem_info[0].mem_bound_check_8bytes = LLVMBuildLoad2(
  1183. comp_ctx->builder,
  1184. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1185. : I32_TYPE,
  1186. func_ctx->mem_info[0].mem_bound_check_8bytes,
  1187. "bound_check_8bytes"))) {
  1188. aot_set_last_error("llvm build load failed");
  1189. return false;
  1190. }
  1191. }
  1192. offset = I32_CONST(offsetof(AOTMemoryInstance, mem_bound_check_16bytes)
  1193. - offsetof(AOTMemoryInstance, memory_data));
  1194. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildInBoundsGEP2(
  1195. comp_ctx->builder, INT8_TYPE, mem_info_base, &offset, 1,
  1196. "bound_check_16bytes_offset"))) {
  1197. aot_set_last_error("llvm build in bounds gep failed");
  1198. return false;
  1199. }
  1200. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildBitCast(
  1201. comp_ctx->builder, func_ctx->mem_info[0].mem_bound_check_16bytes,
  1202. bound_check_type, "bound_check_16bytes_ptr"))) {
  1203. aot_set_last_error("llvm build bit cast failed");
  1204. return false;
  1205. }
  1206. if (mem_space_unchanged) {
  1207. if (!(func_ctx->mem_info[0].mem_bound_check_16bytes = LLVMBuildLoad2(
  1208. comp_ctx->builder,
  1209. (comp_ctx->pointer_size == sizeof(uint64)) ? I64_TYPE
  1210. : I32_TYPE,
  1211. func_ctx->mem_info[0].mem_bound_check_16bytes,
  1212. "bound_check_16bytes"))) {
  1213. aot_set_last_error("llvm build load failed");
  1214. return false;
  1215. }
  1216. }
  1217. return true;
  1218. }
  1219. static bool
  1220. create_cur_exception(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  1221. {
  1222. LLVMValueRef offset;
  1223. offset = I32_CONST(offsetof(AOTModuleInstance, cur_exception));
  1224. func_ctx->cur_exception =
  1225. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1226. &offset, 1, "cur_exception");
  1227. if (!func_ctx->cur_exception) {
  1228. aot_set_last_error("llvm build in bounds gep failed.");
  1229. return false;
  1230. }
  1231. return true;
  1232. }
  1233. static bool
  1234. create_func_type_indexes(const AOTCompContext *comp_ctx,
  1235. AOTFuncContext *func_ctx)
  1236. {
  1237. LLVMValueRef offset, func_type_indexes_ptr;
  1238. LLVMTypeRef int32_ptr_type;
  1239. offset = I32_CONST(offsetof(AOTModuleInstance, func_type_indexes));
  1240. func_type_indexes_ptr =
  1241. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1242. &offset, 1, "func_type_indexes_ptr");
  1243. if (!func_type_indexes_ptr) {
  1244. aot_set_last_error("llvm build add failed.");
  1245. return false;
  1246. }
  1247. if (!(int32_ptr_type = LLVMPointerType(INT32_PTR_TYPE, 0))) {
  1248. aot_set_last_error("llvm get pointer type failed.");
  1249. return false;
  1250. }
  1251. func_ctx->func_type_indexes =
  1252. LLVMBuildBitCast(comp_ctx->builder, func_type_indexes_ptr,
  1253. int32_ptr_type, "func_type_indexes_tmp");
  1254. if (!func_ctx->func_type_indexes) {
  1255. aot_set_last_error("llvm build bit cast failed.");
  1256. return false;
  1257. }
  1258. func_ctx->func_type_indexes =
  1259. LLVMBuildLoad2(comp_ctx->builder, INT32_PTR_TYPE,
  1260. func_ctx->func_type_indexes, "func_type_indexes");
  1261. if (!func_ctx->func_type_indexes) {
  1262. aot_set_last_error("llvm build load failed.");
  1263. return false;
  1264. }
  1265. return true;
  1266. }
  1267. static bool
  1268. create_func_ptrs(const AOTCompContext *comp_ctx, AOTFuncContext *func_ctx)
  1269. {
  1270. LLVMValueRef offset;
  1271. offset = I32_CONST(offsetof(AOTModuleInstance, func_ptrs));
  1272. func_ctx->func_ptrs =
  1273. LLVMBuildInBoundsGEP2(comp_ctx->builder, INT8_TYPE, func_ctx->aot_inst,
  1274. &offset, 1, "func_ptrs_offset");
  1275. if (!func_ctx->func_ptrs) {
  1276. aot_set_last_error("llvm build in bounds gep failed.");
  1277. return false;
  1278. }
  1279. func_ctx->func_ptrs =
  1280. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  1281. comp_ctx->exec_env_type, "func_ptrs_tmp");
  1282. if (!func_ctx->func_ptrs) {
  1283. aot_set_last_error("llvm build bit cast failed.");
  1284. return false;
  1285. }
  1286. func_ctx->func_ptrs = LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE,
  1287. func_ctx->func_ptrs, "func_ptrs_ptr");
  1288. if (!func_ctx->func_ptrs) {
  1289. aot_set_last_error("llvm build load failed.");
  1290. return false;
  1291. }
  1292. func_ctx->func_ptrs =
  1293. LLVMBuildBitCast(comp_ctx->builder, func_ctx->func_ptrs,
  1294. comp_ctx->exec_env_type, "func_ptrs");
  1295. if (!func_ctx->func_ptrs) {
  1296. aot_set_last_error("llvm build bit cast failed.");
  1297. return false;
  1298. }
  1299. return true;
  1300. }
  1301. const char *aot_stack_sizes_name = AOT_STACK_SIZES_NAME;
  1302. const char *aot_stack_sizes_alias_name = AOT_STACK_SIZES_ALIAS_NAME;
  1303. const char *aot_stack_sizes_section_name = AOT_STACK_SIZES_SECTION_NAME;
  1304. static bool
  1305. aot_create_stack_sizes(const AOTCompData *comp_data, AOTCompContext *comp_ctx)
  1306. {
  1307. LLVMValueRef stack_sizes, *values, array, alias;
  1308. LLVMTypeRef stack_sizes_type;
  1309. #if LLVM_VERSION_MAJOR <= 13
  1310. LLVMTypeRef alias_type;
  1311. #endif
  1312. uint64 size;
  1313. uint32 i;
  1314. stack_sizes_type = LLVMArrayType(I32_TYPE, comp_data->func_count);
  1315. if (!stack_sizes_type) {
  1316. aot_set_last_error("failed to create stack_sizes type.");
  1317. return false;
  1318. }
  1319. stack_sizes =
  1320. LLVMAddGlobal(comp_ctx->module, stack_sizes_type, aot_stack_sizes_name);
  1321. if (!stack_sizes) {
  1322. aot_set_last_error("failed to create stack_sizes global.");
  1323. return false;
  1324. }
  1325. size = sizeof(LLVMValueRef) * comp_data->func_count;
  1326. if (size >= UINT32_MAX || !(values = wasm_runtime_malloc((uint32)size))) {
  1327. aot_set_last_error("allocate memory failed.");
  1328. return false;
  1329. }
  1330. for (i = 0; i < comp_data->func_count; i++) {
  1331. /*
  1332. * This value is a placeholder, which will be replaced
  1333. * after the corresponding functions are compiled.
  1334. *
  1335. * Don't use zeros becasue LLVM can optimize them to
  1336. * zeroinitializer.
  1337. */
  1338. values[i] = I32_NEG_ONE;
  1339. }
  1340. array = LLVMConstArray(I32_TYPE, values, comp_data->func_count);
  1341. wasm_runtime_free(values);
  1342. if (!array) {
  1343. aot_set_last_error("failed to create stack_sizes initializer.");
  1344. return false;
  1345. }
  1346. LLVMSetInitializer(stack_sizes, array);
  1347. /*
  1348. * create an alias so that aot_resolve_stack_sizes can find it.
  1349. */
  1350. #if LLVM_VERSION_MAJOR > 13
  1351. alias = LLVMAddAlias2(comp_ctx->module, stack_sizes_type, 0, stack_sizes,
  1352. aot_stack_sizes_alias_name);
  1353. #else
  1354. alias_type = LLVMPointerType(stack_sizes_type, 0);
  1355. if (!alias_type) {
  1356. aot_set_last_error("failed to create alias type.");
  1357. return false;
  1358. }
  1359. alias = LLVMAddAlias(comp_ctx->module, alias_type, stack_sizes,
  1360. aot_stack_sizes_alias_name);
  1361. #endif
  1362. if (!alias) {
  1363. aot_set_last_error("failed to create stack_sizes alias.");
  1364. return false;
  1365. }
  1366. /*
  1367. * make the original symbol internal. we mainly use this version to
  1368. * avoid creating extra relocations in the precheck functions.
  1369. */
  1370. LLVMSetLinkage(stack_sizes, LLVMInternalLinkage);
  1371. LLVMSetSection(stack_sizes, aot_stack_sizes_section_name);
  1372. comp_ctx->stack_sizes_type = stack_sizes_type;
  1373. comp_ctx->stack_sizes = stack_sizes;
  1374. return true;
  1375. }
  1376. /**
  1377. * Create function compiler context
  1378. */
  1379. static AOTFuncContext *
  1380. aot_create_func_context(const AOTCompData *comp_data, AOTCompContext *comp_ctx,
  1381. AOTFunc *func, uint32 func_index)
  1382. {
  1383. AOTFuncContext *func_ctx;
  1384. AOTFuncType *aot_func_type =
  1385. (AOTFuncType *)comp_data->types[func->func_type_index];
  1386. WASMModule *module = comp_ctx->comp_data->wasm_module;
  1387. WASMFunction *wasm_func = module->functions[func_index];
  1388. AOTBlock *aot_block;
  1389. LLVMTypeRef int8_ptr_type;
  1390. uint64 size;
  1391. /* Allocate memory for the function context */
  1392. size = offsetof(AOTFuncContext, locals)
  1393. + sizeof(LLVMValueRef)
  1394. * ((uint64)aot_func_type->param_count + func->local_count);
  1395. if (size >= UINT32_MAX || !(func_ctx = wasm_runtime_malloc((uint32)size))) {
  1396. aot_set_last_error("allocate memory failed.");
  1397. return NULL;
  1398. }
  1399. memset(func_ctx, 0, (uint32)size);
  1400. func_ctx->aot_func = func;
  1401. func_ctx->module = comp_ctx->module;
  1402. /* Add LLVM function */
  1403. if (!(func_ctx->func = aot_add_llvm_func(
  1404. comp_ctx, func_ctx->module, aot_func_type, func_index,
  1405. &func_ctx->func_type, &func_ctx->precheck_func))) {
  1406. goto fail;
  1407. }
  1408. /* Create function's first AOTBlock */
  1409. if (!(aot_block =
  1410. aot_create_func_block(comp_ctx, func_ctx, func, aot_func_type))) {
  1411. goto fail;
  1412. }
  1413. #if WASM_ENABLE_DEBUG_AOT != 0
  1414. func_ctx->debug_func = dwarf_gen_func_info(comp_ctx, func_ctx);
  1415. #endif
  1416. aot_block_stack_push(&func_ctx->block_stack, aot_block);
  1417. /* Add local variables */
  1418. LLVMPositionBuilderAtEnd(comp_ctx->builder, aot_block->llvm_entry_block);
  1419. if (!create_basic_func_context(comp_ctx, func_ctx)) {
  1420. goto fail;
  1421. }
  1422. /* Get argv buffer address */
  1423. if (wasm_func->has_op_func_call && !create_argv_buf(comp_ctx, func_ctx)) {
  1424. goto fail;
  1425. }
  1426. /* Get auxiliary stack info */
  1427. if (wasm_func->has_op_set_global_aux_stack
  1428. && !create_aux_stack_info(comp_ctx, func_ctx)) {
  1429. goto fail;
  1430. }
  1431. /* Create local variables */
  1432. if (!create_local_variables(comp_data, comp_ctx, func_ctx, func)) {
  1433. goto fail;
  1434. }
  1435. if (!(int8_ptr_type = LLVMPointerType(INT8_PTR_TYPE, 0))) {
  1436. aot_set_last_error("llvm add pointer type failed.");
  1437. goto fail;
  1438. }
  1439. /* Create base addr, end addr, data size of mem, heap */
  1440. if (wasm_func->has_memory_operations
  1441. && !create_memory_info(comp_ctx, func_ctx, int8_ptr_type, func_index)) {
  1442. goto fail;
  1443. }
  1444. /* Load current exception */
  1445. if (!create_cur_exception(comp_ctx, func_ctx)) {
  1446. goto fail;
  1447. }
  1448. /* Load function type indexes */
  1449. if (wasm_func->has_op_call_indirect
  1450. && !create_func_type_indexes(comp_ctx, func_ctx)) {
  1451. goto fail;
  1452. }
  1453. /* Load function pointers */
  1454. if (!create_func_ptrs(comp_ctx, func_ctx)) {
  1455. goto fail;
  1456. }
  1457. return func_ctx;
  1458. fail:
  1459. if (func_ctx->mem_info)
  1460. wasm_runtime_free(func_ctx->mem_info);
  1461. aot_block_stack_destroy(&func_ctx->block_stack);
  1462. wasm_runtime_free(func_ctx);
  1463. return NULL;
  1464. }
  1465. static void
  1466. aot_destroy_func_contexts(AOTFuncContext **func_ctxes, uint32 count)
  1467. {
  1468. uint32 i;
  1469. for (i = 0; i < count; i++)
  1470. if (func_ctxes[i]) {
  1471. if (func_ctxes[i]->mem_info)
  1472. wasm_runtime_free(func_ctxes[i]->mem_info);
  1473. aot_block_stack_destroy(&func_ctxes[i]->block_stack);
  1474. aot_checked_addr_list_destroy(func_ctxes[i]);
  1475. wasm_runtime_free(func_ctxes[i]);
  1476. }
  1477. wasm_runtime_free(func_ctxes);
  1478. }
  1479. /**
  1480. * Create function compiler contexts
  1481. */
  1482. static AOTFuncContext **
  1483. aot_create_func_contexts(const AOTCompData *comp_data, AOTCompContext *comp_ctx)
  1484. {
  1485. AOTFuncContext **func_ctxes;
  1486. uint64 size;
  1487. uint32 i;
  1488. if ((comp_ctx->enable_stack_bound_check
  1489. || comp_ctx->enable_stack_estimation)
  1490. && !aot_create_stack_sizes(comp_data, comp_ctx))
  1491. return NULL;
  1492. /* Allocate memory */
  1493. size = sizeof(AOTFuncContext *) * (uint64)comp_data->func_count;
  1494. if (size >= UINT32_MAX
  1495. || !(func_ctxes = wasm_runtime_malloc((uint32)size))) {
  1496. aot_set_last_error("allocate memory failed.");
  1497. return NULL;
  1498. }
  1499. memset(func_ctxes, 0, size);
  1500. /* Create each function context */
  1501. for (i = 0; i < comp_data->func_count; i++) {
  1502. AOTFunc *func = comp_data->funcs[i];
  1503. if (!(func_ctxes[i] =
  1504. aot_create_func_context(comp_data, comp_ctx, func, i))) {
  1505. aot_destroy_func_contexts(func_ctxes, comp_data->func_count);
  1506. return NULL;
  1507. }
  1508. }
  1509. return func_ctxes;
  1510. }
  1511. static bool
  1512. aot_set_llvm_basic_types(AOTLLVMTypes *basic_types, LLVMContextRef context,
  1513. int pointer_size)
  1514. {
  1515. basic_types->int1_type = LLVMInt1TypeInContext(context);
  1516. basic_types->int8_type = LLVMInt8TypeInContext(context);
  1517. basic_types->int16_type = LLVMInt16TypeInContext(context);
  1518. basic_types->int32_type = LLVMInt32TypeInContext(context);
  1519. basic_types->int64_type = LLVMInt64TypeInContext(context);
  1520. basic_types->float32_type = LLVMFloatTypeInContext(context);
  1521. basic_types->float64_type = LLVMDoubleTypeInContext(context);
  1522. basic_types->void_type = LLVMVoidTypeInContext(context);
  1523. basic_types->meta_data_type = LLVMMetadataTypeInContext(context);
  1524. basic_types->int8_ptr_type = LLVMPointerType(basic_types->int8_type, 0);
  1525. if (basic_types->int8_ptr_type) {
  1526. basic_types->int8_pptr_type =
  1527. LLVMPointerType(basic_types->int8_ptr_type, 0);
  1528. }
  1529. basic_types->int16_ptr_type = LLVMPointerType(basic_types->int16_type, 0);
  1530. basic_types->int32_ptr_type = LLVMPointerType(basic_types->int32_type, 0);
  1531. basic_types->int64_ptr_type = LLVMPointerType(basic_types->int64_type, 0);
  1532. basic_types->float32_ptr_type =
  1533. LLVMPointerType(basic_types->float32_type, 0);
  1534. basic_types->float64_ptr_type =
  1535. LLVMPointerType(basic_types->float64_type, 0);
  1536. basic_types->i8x16_vec_type = LLVMVectorType(basic_types->int8_type, 16);
  1537. basic_types->i16x8_vec_type = LLVMVectorType(basic_types->int16_type, 8);
  1538. basic_types->i32x4_vec_type = LLVMVectorType(basic_types->int32_type, 4);
  1539. basic_types->i64x2_vec_type = LLVMVectorType(basic_types->int64_type, 2);
  1540. basic_types->f32x4_vec_type = LLVMVectorType(basic_types->float32_type, 4);
  1541. basic_types->f64x2_vec_type = LLVMVectorType(basic_types->float64_type, 2);
  1542. basic_types->v128_type = basic_types->i64x2_vec_type;
  1543. basic_types->v128_ptr_type = LLVMPointerType(basic_types->v128_type, 0);
  1544. basic_types->int8_ptr_type_gs =
  1545. LLVMPointerType(basic_types->int8_type, 256);
  1546. basic_types->int16_ptr_type_gs =
  1547. LLVMPointerType(basic_types->int16_type, 256);
  1548. basic_types->int32_ptr_type_gs =
  1549. LLVMPointerType(basic_types->int32_type, 256);
  1550. basic_types->int64_ptr_type_gs =
  1551. LLVMPointerType(basic_types->int64_type, 256);
  1552. basic_types->float32_ptr_type_gs =
  1553. LLVMPointerType(basic_types->float32_type, 256);
  1554. basic_types->float64_ptr_type_gs =
  1555. LLVMPointerType(basic_types->float64_type, 256);
  1556. basic_types->v128_ptr_type_gs =
  1557. LLVMPointerType(basic_types->v128_type, 256);
  1558. if (!basic_types->int8_ptr_type_gs || !basic_types->int16_ptr_type_gs
  1559. || !basic_types->int32_ptr_type_gs || !basic_types->int64_ptr_type_gs
  1560. || !basic_types->float32_ptr_type_gs
  1561. || !basic_types->float64_ptr_type_gs
  1562. || !basic_types->v128_ptr_type_gs) {
  1563. return false;
  1564. }
  1565. basic_types->i1x2_vec_type = LLVMVectorType(basic_types->int1_type, 2);
  1566. basic_types->funcref_type = LLVMInt32TypeInContext(context);
  1567. basic_types->externref_type = LLVMInt32TypeInContext(context);
  1568. if (pointer_size == 4) {
  1569. basic_types->intptr_type = basic_types->int32_type;
  1570. basic_types->intptr_ptr_type = basic_types->int32_ptr_type;
  1571. }
  1572. else {
  1573. basic_types->intptr_type = basic_types->int64_type;
  1574. basic_types->intptr_ptr_type = basic_types->int64_ptr_type;
  1575. }
  1576. return (basic_types->int8_ptr_type && basic_types->int8_pptr_type
  1577. && basic_types->int16_ptr_type && basic_types->int32_ptr_type
  1578. && basic_types->int64_ptr_type && basic_types->intptr_type
  1579. && basic_types->intptr_ptr_type && basic_types->float32_ptr_type
  1580. && basic_types->float64_ptr_type && basic_types->i8x16_vec_type
  1581. && basic_types->i16x8_vec_type && basic_types->i32x4_vec_type
  1582. && basic_types->i64x2_vec_type && basic_types->f32x4_vec_type
  1583. && basic_types->f64x2_vec_type && basic_types->i1x2_vec_type
  1584. && basic_types->meta_data_type && basic_types->funcref_type
  1585. && basic_types->externref_type)
  1586. ? true
  1587. : false;
  1588. }
  1589. static bool
  1590. aot_create_llvm_consts(AOTLLVMConsts *consts, AOTCompContext *comp_ctx)
  1591. {
  1592. #define CREATE_I1_CONST(name, value) \
  1593. if (!(consts->i1_##name = \
  1594. LLVMConstInt(comp_ctx->basic_types.int1_type, value, true))) \
  1595. return false;
  1596. CREATE_I1_CONST(zero, 0)
  1597. CREATE_I1_CONST(one, 1)
  1598. #undef CREATE_I1_CONST
  1599. if (!(consts->i8_zero = I8_CONST(0)))
  1600. return false;
  1601. if (!(consts->f32_zero = F32_CONST(0)))
  1602. return false;
  1603. if (!(consts->f64_zero = F64_CONST(0)))
  1604. return false;
  1605. #define CREATE_I32_CONST(name, value) \
  1606. if (!(consts->i32_##name = LLVMConstInt(I32_TYPE, value, true))) \
  1607. return false;
  1608. CREATE_I32_CONST(min, (uint32)INT32_MIN)
  1609. CREATE_I32_CONST(neg_one, (uint32)-1)
  1610. CREATE_I32_CONST(zero, 0)
  1611. CREATE_I32_CONST(one, 1)
  1612. CREATE_I32_CONST(two, 2)
  1613. CREATE_I32_CONST(three, 3)
  1614. CREATE_I32_CONST(four, 4)
  1615. CREATE_I32_CONST(five, 5)
  1616. CREATE_I32_CONST(six, 6)
  1617. CREATE_I32_CONST(seven, 7)
  1618. CREATE_I32_CONST(eight, 8)
  1619. CREATE_I32_CONST(nine, 9)
  1620. CREATE_I32_CONST(ten, 10)
  1621. CREATE_I32_CONST(eleven, 11)
  1622. CREATE_I32_CONST(twelve, 12)
  1623. CREATE_I32_CONST(thirteen, 13)
  1624. CREATE_I32_CONST(fourteen, 14)
  1625. CREATE_I32_CONST(fifteen, 15)
  1626. CREATE_I32_CONST(31, 31)
  1627. CREATE_I32_CONST(32, 32)
  1628. #undef CREATE_I32_CONST
  1629. #define CREATE_I64_CONST(name, value) \
  1630. if (!(consts->i64_##name = LLVMConstInt(I64_TYPE, value, true))) \
  1631. return false;
  1632. CREATE_I64_CONST(min, (uint64)INT64_MIN)
  1633. CREATE_I64_CONST(neg_one, (uint64)-1)
  1634. CREATE_I64_CONST(zero, 0)
  1635. CREATE_I64_CONST(63, 63)
  1636. CREATE_I64_CONST(64, 64)
  1637. #undef CREATE_I64_CONST
  1638. #define CREATE_V128_CONST(name, type) \
  1639. if (!(consts->name##_vec_zero = LLVMConstNull(type))) \
  1640. return false; \
  1641. if (!(consts->name##_undef = LLVMGetUndef(type))) \
  1642. return false;
  1643. CREATE_V128_CONST(i8x16, V128_i8x16_TYPE)
  1644. CREATE_V128_CONST(i16x8, V128_i16x8_TYPE)
  1645. CREATE_V128_CONST(i32x4, V128_i32x4_TYPE)
  1646. CREATE_V128_CONST(i64x2, V128_i64x2_TYPE)
  1647. CREATE_V128_CONST(f32x4, V128_f32x4_TYPE)
  1648. CREATE_V128_CONST(f64x2, V128_f64x2_TYPE)
  1649. #undef CREATE_V128_CONST
  1650. #define CREATE_VEC_ZERO_MASK(slot) \
  1651. { \
  1652. LLVMTypeRef type = LLVMVectorType(I32_TYPE, slot); \
  1653. if (!type || !(consts->i32x##slot##_zero = LLVMConstNull(type))) \
  1654. return false; \
  1655. }
  1656. CREATE_VEC_ZERO_MASK(16)
  1657. CREATE_VEC_ZERO_MASK(8)
  1658. CREATE_VEC_ZERO_MASK(4)
  1659. CREATE_VEC_ZERO_MASK(2)
  1660. #undef CREATE_VEC_ZERO_MASK
  1661. return true;
  1662. }
  1663. typedef struct ArchItem {
  1664. char *arch;
  1665. bool support_eb;
  1666. } ArchItem;
  1667. /* clang-format off */
  1668. static ArchItem valid_archs[] = {
  1669. { "x86_64", false },
  1670. { "i386", false },
  1671. { "xtensa", false },
  1672. { "mips", true },
  1673. { "mipsel", false },
  1674. { "aarch64v8", false },
  1675. { "aarch64v8.1", false },
  1676. { "aarch64v8.2", false },
  1677. { "aarch64v8.3", false },
  1678. { "aarch64v8.4", false },
  1679. { "aarch64v8.5", false },
  1680. { "aarch64_bev8", false }, /* big endian */
  1681. { "aarch64_bev8.1", false },
  1682. { "aarch64_bev8.2", false },
  1683. { "aarch64_bev8.3", false },
  1684. { "aarch64_bev8.4", false },
  1685. { "aarch64_bev8.5", false },
  1686. { "armv4", true },
  1687. { "armv4t", true },
  1688. { "armv5t", true },
  1689. { "armv5te", true },
  1690. { "armv5tej", true },
  1691. { "armv6", true },
  1692. { "armv6kz", true },
  1693. { "armv6t2", true },
  1694. { "armv6k", true },
  1695. { "armv7", true },
  1696. { "armv6m", true },
  1697. { "armv6sm", true },
  1698. { "armv7em", true },
  1699. { "armv8a", true },
  1700. { "armv8r", true },
  1701. { "armv8m.base", true },
  1702. { "armv8m.main", true },
  1703. { "armv8.1m.main", true },
  1704. { "thumbv4", true },
  1705. { "thumbv4t", true },
  1706. { "thumbv5t", true },
  1707. { "thumbv5te", true },
  1708. { "thumbv5tej", true },
  1709. { "thumbv6", true },
  1710. { "thumbv6kz", true },
  1711. { "thumbv6t2", true },
  1712. { "thumbv6k", true },
  1713. { "thumbv7", true },
  1714. { "thumbv6m", true },
  1715. { "thumbv6sm", true },
  1716. { "thumbv7em", true },
  1717. { "thumbv8a", true },
  1718. { "thumbv8r", true },
  1719. { "thumbv8m.base", true },
  1720. { "thumbv8m.main", true },
  1721. { "thumbv8.1m.main", true },
  1722. { "riscv32", true },
  1723. { "riscv64", true },
  1724. { "arc", true }
  1725. };
  1726. static const char *valid_abis[] = {
  1727. "gnu",
  1728. "eabi",
  1729. "gnueabihf",
  1730. "msvc",
  1731. "ilp32",
  1732. "ilp32f",
  1733. "ilp32d",
  1734. "lp64",
  1735. "lp64f",
  1736. "lp64d"
  1737. };
  1738. /* clang-format on */
  1739. static void
  1740. print_supported_targets()
  1741. {
  1742. uint32 i;
  1743. os_printf("Supported targets:\n");
  1744. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1745. os_printf("%s ", valid_archs[i].arch);
  1746. if (valid_archs[i].support_eb)
  1747. os_printf("%seb ", valid_archs[i].arch);
  1748. }
  1749. os_printf("\n");
  1750. }
  1751. static void
  1752. print_supported_abis()
  1753. {
  1754. uint32 i;
  1755. os_printf("Supported ABI: ");
  1756. for (i = 0; i < sizeof(valid_abis) / sizeof(const char *); i++)
  1757. os_printf("%s ", valid_abis[i]);
  1758. os_printf("\n");
  1759. }
  1760. static bool
  1761. check_target_arch(const char *target_arch)
  1762. {
  1763. uint32 i;
  1764. char *arch;
  1765. bool support_eb;
  1766. for (i = 0; i < sizeof(valid_archs) / sizeof(ArchItem); i++) {
  1767. arch = valid_archs[i].arch;
  1768. support_eb = valid_archs[i].support_eb;
  1769. if (!strncmp(target_arch, arch, strlen(arch))
  1770. && ((support_eb
  1771. && (!strcmp(target_arch + strlen(arch), "eb")
  1772. || !strcmp(target_arch + strlen(arch), "")))
  1773. || (!support_eb && !strcmp(target_arch + strlen(arch), "")))) {
  1774. return true;
  1775. }
  1776. }
  1777. return false;
  1778. }
  1779. static bool
  1780. check_target_abi(const char *target_abi)
  1781. {
  1782. uint32 i;
  1783. for (i = 0; i < sizeof(valid_abis) / sizeof(char *); i++) {
  1784. if (!strcmp(target_abi, valid_abis[i]))
  1785. return true;
  1786. }
  1787. return false;
  1788. }
  1789. static void
  1790. get_target_arch_from_triple(const char *triple, char *arch_buf, uint32 buf_size)
  1791. {
  1792. uint32 i = 0;
  1793. while (*triple != '-' && *triple != '\0' && i < buf_size - 1)
  1794. arch_buf[i++] = *triple++;
  1795. /* Make sure buffer is long enough */
  1796. bh_assert(*triple == '-' || *triple == '\0');
  1797. }
  1798. void
  1799. aot_handle_llvm_errmsg(const char *string, LLVMErrorRef err)
  1800. {
  1801. char *err_msg = LLVMGetErrorMessage(err);
  1802. aot_set_last_error_v("%s: %s", string, err_msg);
  1803. LLVMDisposeErrorMessage(err_msg);
  1804. }
  1805. static bool
  1806. create_target_machine_detect_host(AOTCompContext *comp_ctx)
  1807. {
  1808. char *triple = NULL;
  1809. LLVMTargetRef target = NULL;
  1810. char *err_msg = NULL;
  1811. char *cpu = NULL;
  1812. char *features = NULL;
  1813. LLVMTargetMachineRef target_machine = NULL;
  1814. bool ret = false;
  1815. triple = LLVMGetDefaultTargetTriple();
  1816. if (triple == NULL) {
  1817. aot_set_last_error("failed to get default target triple.");
  1818. goto fail;
  1819. }
  1820. if (LLVMGetTargetFromTriple(triple, &target, &err_msg) != 0) {
  1821. aot_set_last_error_v("failed to get llvm target from triple %s.",
  1822. err_msg);
  1823. LLVMDisposeMessage(err_msg);
  1824. goto fail;
  1825. }
  1826. if (!LLVMTargetHasJIT(target)) {
  1827. aot_set_last_error("unspported JIT on this platform.");
  1828. goto fail;
  1829. }
  1830. cpu = LLVMGetHostCPUName();
  1831. if (cpu == NULL) {
  1832. aot_set_last_error("failed to get host cpu information.");
  1833. goto fail;
  1834. }
  1835. features = LLVMGetHostCPUFeatures();
  1836. if (features == NULL) {
  1837. aot_set_last_error("failed to get host cpu features.");
  1838. goto fail;
  1839. }
  1840. LOG_VERBOSE("LLVM ORCJIT detected CPU \"%s\", with features \"%s\"\n", cpu,
  1841. features);
  1842. /* create TargetMachine */
  1843. target_machine = LLVMCreateTargetMachine(
  1844. target, triple, cpu, features, LLVMCodeGenLevelDefault,
  1845. LLVMRelocDefault, LLVMCodeModelJITDefault);
  1846. if (!target_machine) {
  1847. aot_set_last_error("failed to create target machine.");
  1848. goto fail;
  1849. }
  1850. comp_ctx->target_machine = target_machine;
  1851. /* Save target arch */
  1852. get_target_arch_from_triple(triple, comp_ctx->target_arch,
  1853. sizeof(comp_ctx->target_arch));
  1854. ret = true;
  1855. fail:
  1856. if (triple)
  1857. LLVMDisposeMessage(triple);
  1858. if (features)
  1859. LLVMDisposeMessage(features);
  1860. if (cpu)
  1861. LLVMDisposeMessage(cpu);
  1862. return ret;
  1863. }
  1864. static void
  1865. jit_stack_size_callback(void *user_data, const char *name, size_t namelen,
  1866. size_t stack_size)
  1867. {
  1868. AOTCompContext *comp_ctx = user_data;
  1869. /*
  1870. * Note: the longest name we care is
  1871. * something like "aot_func_internal#4294967295".
  1872. */
  1873. char buf[64];
  1874. uint32 func_idx;
  1875. const AOTFuncContext *func_ctx;
  1876. bool musttail;
  1877. unsigned int stack_consumption_to_call_wrapped_func;
  1878. unsigned int call_size;
  1879. int ret;
  1880. bh_assert(comp_ctx != NULL);
  1881. bh_assert(comp_ctx->jit_stack_sizes != NULL);
  1882. if (namelen >= sizeof(buf)) {
  1883. LOG_DEBUG("too long name: %.*s", (int)namelen, name);
  1884. return;
  1885. }
  1886. /* ensure NUL termination */
  1887. bh_memcpy_s(buf, sizeof(buf), name, namelen);
  1888. buf[namelen] = 0;
  1889. ret = sscanf(buf, AOT_FUNC_INTERNAL_PREFIX "%" SCNu32, &func_idx);
  1890. if (ret != 1) {
  1891. return;
  1892. }
  1893. bh_assert(func_idx < comp_ctx->func_ctx_count);
  1894. func_ctx = comp_ctx->func_ctxes[func_idx];
  1895. call_size = func_ctx->stack_consumption_for_func_call;
  1896. musttail = aot_target_precheck_can_use_musttail(comp_ctx);
  1897. stack_consumption_to_call_wrapped_func =
  1898. musttail ? 0
  1899. : aot_estimate_stack_usage_for_function_call(
  1900. comp_ctx, func_ctx->aot_func->func_type);
  1901. LOG_VERBOSE("func %.*s stack %u + %zu + %u", (int)namelen, name,
  1902. stack_consumption_to_call_wrapped_func, stack_size, call_size);
  1903. /* Note: -1 == AOT_NEG_ONE from aot_create_stack_sizes */
  1904. bh_assert(comp_ctx->jit_stack_sizes[func_idx] == (uint32)-1);
  1905. comp_ctx->jit_stack_sizes[func_idx] = stack_size + call_size;
  1906. }
  1907. static bool
  1908. orc_jit_create(AOTCompContext *comp_ctx)
  1909. {
  1910. LLVMErrorRef err;
  1911. LLVMOrcLLLazyJITRef orc_jit = NULL;
  1912. LLVMOrcLLLazyJITBuilderRef builder = NULL;
  1913. LLVMOrcJITTargetMachineBuilderRef jtmb = NULL;
  1914. bool ret = false;
  1915. builder = LLVMOrcCreateLLLazyJITBuilder();
  1916. if (builder == NULL) {
  1917. aot_set_last_error("failed to create jit builder.");
  1918. goto fail;
  1919. }
  1920. if (comp_ctx->enable_stack_bound_check || comp_ctx->enable_stack_estimation)
  1921. LLVMOrcLLJITBuilderSetCompileFuncitonCreatorWithStackSizesCallback(
  1922. builder, jit_stack_size_callback, comp_ctx);
  1923. err = LLVMOrcJITTargetMachineBuilderDetectHost(&jtmb);
  1924. if (err != LLVMErrorSuccess) {
  1925. aot_handle_llvm_errmsg(
  1926. "quited to create LLVMOrcJITTargetMachineBuilderRef", err);
  1927. goto fail;
  1928. }
  1929. LLVMOrcLLLazyJITBuilderSetNumCompileThreads(
  1930. builder, WASM_ORC_JIT_COMPILE_THREAD_NUM);
  1931. /* Ownership transfer:
  1932. LLVMOrcJITTargetMachineBuilderRef -> LLVMOrcLLJITBuilderRef */
  1933. LLVMOrcLLLazyJITBuilderSetJITTargetMachineBuilder(builder, jtmb);
  1934. err = LLVMOrcCreateLLLazyJIT(&orc_jit, builder);
  1935. if (err != LLVMErrorSuccess) {
  1936. aot_handle_llvm_errmsg("quited to create llvm lazy orcjit instance",
  1937. err);
  1938. goto fail;
  1939. }
  1940. /* Ownership transfer: LLVMOrcLLJITBuilderRef -> LLVMOrcLLJITRef */
  1941. builder = NULL;
  1942. /* Ownership transfer: local -> AOTCompContext */
  1943. comp_ctx->orc_jit = orc_jit;
  1944. orc_jit = NULL;
  1945. ret = true;
  1946. fail:
  1947. if (builder)
  1948. LLVMOrcDisposeLLLazyJITBuilder(builder);
  1949. if (orc_jit)
  1950. LLVMOrcDisposeLLLazyJIT(orc_jit);
  1951. return ret;
  1952. }
  1953. bool
  1954. aot_compiler_init(void)
  1955. {
  1956. /* Initialize LLVM environment */
  1957. LLVMInitializeCore(LLVMGetGlobalPassRegistry());
  1958. #if WASM_ENABLE_WAMR_COMPILER != 0
  1959. /* Init environment of all targets for AOT compiler */
  1960. LLVMInitializeAllTargetInfos();
  1961. LLVMInitializeAllTargets();
  1962. LLVMInitializeAllTargetMCs();
  1963. LLVMInitializeAllAsmPrinters();
  1964. #else
  1965. /* Init environment of native for JIT compiler */
  1966. LLVMInitializeNativeTarget();
  1967. LLVMInitializeNativeTarget();
  1968. LLVMInitializeNativeAsmPrinter();
  1969. #endif
  1970. return true;
  1971. }
  1972. void
  1973. aot_compiler_destroy(void)
  1974. {
  1975. LLVMShutdown();
  1976. }
  1977. AOTCompContext *
  1978. aot_create_comp_context(const AOTCompData *comp_data, aot_comp_option_t option)
  1979. {
  1980. AOTCompContext *comp_ctx, *ret = NULL;
  1981. LLVMTargetRef target;
  1982. char *triple = NULL, *triple_norm, *arch, *abi;
  1983. char *cpu = NULL, *features, buf[128];
  1984. char *triple_norm_new = NULL, *cpu_new = NULL;
  1985. char *err = NULL, *fp_round = "round.tonearest",
  1986. *fp_exce = "fpexcept.strict";
  1987. char triple_buf[32] = { 0 }, features_buf[128] = { 0 };
  1988. uint32 opt_level, size_level, i;
  1989. LLVMCodeModel code_model;
  1990. LLVMTargetDataRef target_data_ref;
  1991. /* Allocate memory */
  1992. if (!(comp_ctx = wasm_runtime_malloc(sizeof(AOTCompContext)))) {
  1993. aot_set_last_error("allocate memory failed.");
  1994. return NULL;
  1995. }
  1996. memset(comp_ctx, 0, sizeof(AOTCompContext));
  1997. comp_ctx->comp_data = comp_data;
  1998. /* Create LLVM context, module and builder */
  1999. comp_ctx->orc_thread_safe_context = LLVMOrcCreateNewThreadSafeContext();
  2000. if (!comp_ctx->orc_thread_safe_context) {
  2001. aot_set_last_error("create LLVM ThreadSafeContext failed.");
  2002. goto fail;
  2003. }
  2004. /* Get a reference to the underlying LLVMContext, note:
  2005. different from non LAZY JIT mode, no need to dispose this context,
  2006. if will be disposed when the thread safe context is disposed */
  2007. if (!(comp_ctx->context = LLVMOrcThreadSafeContextGetContext(
  2008. comp_ctx->orc_thread_safe_context))) {
  2009. aot_set_last_error("get context from LLVM ThreadSafeContext failed.");
  2010. goto fail;
  2011. }
  2012. if (!(comp_ctx->builder = LLVMCreateBuilderInContext(comp_ctx->context))) {
  2013. aot_set_last_error("create LLVM builder failed.");
  2014. goto fail;
  2015. }
  2016. /* Create LLVM module for each jit function, note:
  2017. different from non ORC JIT mode, no need to dispose it,
  2018. it will be disposed when the thread safe context is disposed */
  2019. if (!(comp_ctx->module = LLVMModuleCreateWithNameInContext(
  2020. "WASM Module", comp_ctx->context))) {
  2021. aot_set_last_error("create LLVM module failed.");
  2022. goto fail;
  2023. }
  2024. if (BH_LIST_ERROR == bh_list_init(&comp_ctx->native_symbols)) {
  2025. goto fail;
  2026. }
  2027. #if WASM_ENABLE_DEBUG_AOT != 0
  2028. if (!(comp_ctx->debug_builder = LLVMCreateDIBuilder(comp_ctx->module))) {
  2029. aot_set_last_error("create LLVM Debug Infor builder failed.");
  2030. goto fail;
  2031. }
  2032. LLVMAddModuleFlag(
  2033. comp_ctx->module, LLVMModuleFlagBehaviorWarning, "Debug Info Version",
  2034. strlen("Debug Info Version"),
  2035. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32Type(), 3, false)));
  2036. comp_ctx->debug_file = dwarf_gen_file_info(comp_ctx);
  2037. if (!comp_ctx->debug_file) {
  2038. aot_set_last_error("dwarf generate file info failed");
  2039. goto fail;
  2040. }
  2041. comp_ctx->debug_comp_unit = dwarf_gen_comp_unit_info(comp_ctx);
  2042. if (!comp_ctx->debug_comp_unit) {
  2043. aot_set_last_error("dwarf generate compile unit info failed");
  2044. goto fail;
  2045. }
  2046. #endif
  2047. if (option->enable_bulk_memory)
  2048. comp_ctx->enable_bulk_memory = true;
  2049. if (option->enable_thread_mgr)
  2050. comp_ctx->enable_thread_mgr = true;
  2051. if (option->enable_tail_call)
  2052. comp_ctx->enable_tail_call = true;
  2053. if (option->enable_ref_types)
  2054. comp_ctx->enable_ref_types = true;
  2055. if (option->enable_aux_stack_frame)
  2056. comp_ctx->enable_aux_stack_frame = true;
  2057. if (option->enable_aux_stack_check)
  2058. comp_ctx->enable_aux_stack_check = true;
  2059. if (option->is_indirect_mode)
  2060. comp_ctx->is_indirect_mode = true;
  2061. if (option->disable_llvm_intrinsics)
  2062. comp_ctx->disable_llvm_intrinsics = true;
  2063. if (option->disable_llvm_lto)
  2064. comp_ctx->disable_llvm_lto = true;
  2065. if (option->enable_llvm_pgo)
  2066. comp_ctx->enable_llvm_pgo = true;
  2067. if (option->use_prof_file)
  2068. comp_ctx->use_prof_file = option->use_prof_file;
  2069. if (option->enable_stack_estimation)
  2070. comp_ctx->enable_stack_estimation = true;
  2071. if (option->llvm_passes)
  2072. comp_ctx->llvm_passes = option->llvm_passes;
  2073. if (option->builtin_intrinsics)
  2074. comp_ctx->builtin_intrinsics = option->builtin_intrinsics;
  2075. if (option->enable_gc)
  2076. comp_ctx->enable_gc = true;
  2077. comp_ctx->opt_level = option->opt_level;
  2078. comp_ctx->size_level = option->size_level;
  2079. comp_ctx->custom_sections_wp = option->custom_sections;
  2080. comp_ctx->custom_sections_count = option->custom_sections_count;
  2081. if (option->is_jit_mode) {
  2082. comp_ctx->is_jit_mode = true;
  2083. #ifndef OS_ENABLE_HW_BOUND_CHECK
  2084. comp_ctx->enable_bound_check = true;
  2085. /* Always enable stack boundary check if `bounds-checks`
  2086. is enabled */
  2087. comp_ctx->enable_stack_bound_check = true;
  2088. #else
  2089. comp_ctx->enable_bound_check = false;
  2090. /* When `bounds-checks` is disabled, we set stack boundary
  2091. check status according to the compilation option */
  2092. #if WASM_DISABLE_STACK_HW_BOUND_CHECK != 0
  2093. /* Native stack overflow check with hardware trap is disabled,
  2094. we need to enable the check by LLVM JITed/AOTed code */
  2095. comp_ctx->enable_stack_bound_check = true;
  2096. #else
  2097. /* Native stack overflow check with hardware trap is enabled,
  2098. no need to enable the check by LLVM JITed/AOTed code */
  2099. comp_ctx->enable_stack_bound_check = false;
  2100. #endif
  2101. #endif
  2102. /* Create TargetMachine */
  2103. if (!create_target_machine_detect_host(comp_ctx))
  2104. goto fail;
  2105. /* Create LLJIT Instance */
  2106. if (!orc_jit_create(comp_ctx))
  2107. goto fail;
  2108. }
  2109. else {
  2110. /* Create LLVM target machine */
  2111. arch = option->target_arch;
  2112. abi = option->target_abi;
  2113. cpu = option->target_cpu;
  2114. features = option->cpu_features;
  2115. opt_level = option->opt_level;
  2116. size_level = option->size_level;
  2117. /* verify external llc compiler */
  2118. comp_ctx->external_llc_compiler = getenv("WAMRC_LLC_COMPILER");
  2119. if (comp_ctx->external_llc_compiler) {
  2120. #if defined(_WIN32) || defined(_WIN32_)
  2121. comp_ctx->external_llc_compiler = NULL;
  2122. LOG_WARNING("External LLC compiler not supported on Windows.");
  2123. #else
  2124. if (access(comp_ctx->external_llc_compiler, X_OK) != 0) {
  2125. LOG_WARNING("WAMRC_LLC_COMPILER [%s] not found, fallback to "
  2126. "default pipeline",
  2127. comp_ctx->external_llc_compiler);
  2128. comp_ctx->external_llc_compiler = NULL;
  2129. }
  2130. else {
  2131. comp_ctx->llc_compiler_flags = getenv("WAMRC_LLC_FLAGS");
  2132. LOG_VERBOSE("Using external LLC compiler [%s]",
  2133. comp_ctx->external_llc_compiler);
  2134. }
  2135. #endif
  2136. }
  2137. /* verify external asm compiler */
  2138. if (!comp_ctx->external_llc_compiler) {
  2139. comp_ctx->external_asm_compiler = getenv("WAMRC_ASM_COMPILER");
  2140. if (comp_ctx->external_asm_compiler) {
  2141. #if defined(_WIN32) || defined(_WIN32_)
  2142. comp_ctx->external_asm_compiler = NULL;
  2143. LOG_WARNING("External ASM compiler not supported on Windows.");
  2144. #else
  2145. if (access(comp_ctx->external_asm_compiler, X_OK) != 0) {
  2146. LOG_WARNING(
  2147. "WAMRC_ASM_COMPILER [%s] not found, fallback to "
  2148. "default pipeline",
  2149. comp_ctx->external_asm_compiler);
  2150. comp_ctx->external_asm_compiler = NULL;
  2151. }
  2152. else {
  2153. comp_ctx->asm_compiler_flags = getenv("WAMRC_ASM_FLAGS");
  2154. LOG_VERBOSE("Using external ASM compiler [%s]",
  2155. comp_ctx->external_asm_compiler);
  2156. }
  2157. #endif
  2158. }
  2159. }
  2160. if (arch) {
  2161. /* Add default sub-arch if not specified */
  2162. if (!strcmp(arch, "arm"))
  2163. arch = "armv4";
  2164. else if (!strcmp(arch, "armeb"))
  2165. arch = "armv4eb";
  2166. else if (!strcmp(arch, "thumb"))
  2167. arch = "thumbv4t";
  2168. else if (!strcmp(arch, "thumbeb"))
  2169. arch = "thumbv4teb";
  2170. else if (!strcmp(arch, "aarch64"))
  2171. arch = "aarch64v8";
  2172. else if (!strcmp(arch, "aarch64_be"))
  2173. arch = "aarch64_bev8";
  2174. }
  2175. /* Check target arch */
  2176. if (arch && !check_target_arch(arch)) {
  2177. if (!strcmp(arch, "help"))
  2178. print_supported_targets();
  2179. else
  2180. aot_set_last_error(
  2181. "Invalid target. "
  2182. "Use --target=help to list all supported targets");
  2183. goto fail;
  2184. }
  2185. /* Check target ABI */
  2186. if (abi && !check_target_abi(abi)) {
  2187. if (!strcmp(abi, "help"))
  2188. print_supported_abis();
  2189. else
  2190. aot_set_last_error(
  2191. "Invalid target ABI. "
  2192. "Use --target-abi=help to list all supported ABI");
  2193. goto fail;
  2194. }
  2195. /* Set default abi for riscv target */
  2196. if (arch && !strncmp(arch, "riscv", 5) && !abi) {
  2197. if (!strcmp(arch, "riscv64"))
  2198. abi = "lp64d";
  2199. else
  2200. abi = "ilp32d";
  2201. }
  2202. #if defined(__APPLE__) || defined(__MACH__)
  2203. if (!abi) {
  2204. /* On MacOS platform, set abi to "gnu" to avoid generating
  2205. object file of Mach-O binary format which is unsupported */
  2206. abi = "gnu";
  2207. if (!arch && !cpu && !features) {
  2208. /* Get CPU name of the host machine to avoid checking
  2209. SIMD capability failed */
  2210. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  2211. aot_set_last_error("llvm get host cpu name failed.");
  2212. goto fail;
  2213. }
  2214. }
  2215. }
  2216. #endif
  2217. if (abi) {
  2218. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  2219. const char *vendor_sys;
  2220. char *arch1 = arch, default_arch[32] = { 0 };
  2221. if (!arch1) {
  2222. char *default_triple = LLVMGetDefaultTargetTriple();
  2223. if (!default_triple) {
  2224. aot_set_last_error(
  2225. "llvm get default target triple failed.");
  2226. goto fail;
  2227. }
  2228. vendor_sys = strstr(default_triple, "-");
  2229. bh_assert(vendor_sys);
  2230. bh_memcpy_s(default_arch, sizeof(default_arch), default_triple,
  2231. (uint32)(vendor_sys - default_triple));
  2232. arch1 = default_arch;
  2233. LLVMDisposeMessage(default_triple);
  2234. }
  2235. /**
  2236. * Set <vendor>-<sys> according to abi to generate the object file
  2237. * with the correct file format which might be different from the
  2238. * default object file format of the host, e.g., generating AOT file
  2239. * for Windows/MacOS under Linux host, or generating AOT file for
  2240. * Linux/MacOS under Windows host.
  2241. */
  2242. if (!strcmp(abi, "msvc")) {
  2243. if (!strcmp(arch1, "i386"))
  2244. vendor_sys = "-pc-win32-";
  2245. else
  2246. vendor_sys = "-pc-windows-";
  2247. }
  2248. else {
  2249. vendor_sys = "-pc-linux-";
  2250. }
  2251. bh_assert(strlen(arch1) + strlen(vendor_sys) + strlen(abi)
  2252. < sizeof(triple_buf));
  2253. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch1,
  2254. (uint32)strlen(arch1));
  2255. bh_memcpy_s(triple_buf + strlen(arch1),
  2256. (uint32)(sizeof(triple_buf) - strlen(arch1)),
  2257. vendor_sys, (uint32)strlen(vendor_sys));
  2258. bh_memcpy_s(triple_buf + strlen(arch1) + strlen(vendor_sys),
  2259. (uint32)(sizeof(triple_buf) - strlen(arch1)
  2260. - strlen(vendor_sys)),
  2261. abi, (uint32)strlen(abi));
  2262. triple = triple_buf;
  2263. }
  2264. else if (arch) {
  2265. /* Construct target triple: <arch>-<vendor>-<sys>-<abi> */
  2266. const char *vendor_sys;
  2267. char *default_triple = LLVMGetDefaultTargetTriple();
  2268. if (!default_triple) {
  2269. aot_set_last_error("llvm get default target triple failed.");
  2270. goto fail;
  2271. }
  2272. if (strstr(default_triple, "windows")) {
  2273. vendor_sys = "-pc-windows-";
  2274. if (!abi)
  2275. abi = "msvc";
  2276. }
  2277. else if (strstr(default_triple, "win32")) {
  2278. vendor_sys = "-pc-win32-";
  2279. if (!abi)
  2280. abi = "msvc";
  2281. }
  2282. else {
  2283. vendor_sys = "-pc-linux-";
  2284. if (!abi)
  2285. abi = "gnu";
  2286. }
  2287. LLVMDisposeMessage(default_triple);
  2288. bh_assert(strlen(arch) + strlen(vendor_sys) + strlen(abi)
  2289. < sizeof(triple_buf));
  2290. bh_memcpy_s(triple_buf, (uint32)sizeof(triple_buf), arch,
  2291. (uint32)strlen(arch));
  2292. bh_memcpy_s(triple_buf + strlen(arch),
  2293. (uint32)(sizeof(triple_buf) - strlen(arch)), vendor_sys,
  2294. (uint32)strlen(vendor_sys));
  2295. bh_memcpy_s(triple_buf + strlen(arch) + strlen(vendor_sys),
  2296. (uint32)(sizeof(triple_buf) - strlen(arch)
  2297. - strlen(vendor_sys)),
  2298. abi, (uint32)strlen(abi));
  2299. triple = triple_buf;
  2300. }
  2301. if (!cpu && features) {
  2302. aot_set_last_error("cpu isn't specified for cpu features.");
  2303. goto fail;
  2304. }
  2305. if (!triple && !cpu) {
  2306. /* Get a triple for the host machine */
  2307. if (!(triple_norm = triple_norm_new =
  2308. LLVMGetDefaultTargetTriple())) {
  2309. aot_set_last_error("llvm get default target triple failed.");
  2310. goto fail;
  2311. }
  2312. /* Get CPU name of the host machine */
  2313. if (!(cpu = cpu_new = LLVMGetHostCPUName())) {
  2314. aot_set_last_error("llvm get host cpu name failed.");
  2315. goto fail;
  2316. }
  2317. }
  2318. else if (triple) {
  2319. /* Normalize a target triple */
  2320. if (!(triple_norm = triple_norm_new =
  2321. LLVMNormalizeTargetTriple(triple))) {
  2322. snprintf(buf, sizeof(buf),
  2323. "llvm normlalize target triple (%s) failed.", triple);
  2324. aot_set_last_error(buf);
  2325. goto fail;
  2326. }
  2327. if (!cpu)
  2328. cpu = "";
  2329. }
  2330. else {
  2331. /* triple is NULL, cpu isn't NULL */
  2332. snprintf(buf, sizeof(buf), "target isn't specified for cpu %s.",
  2333. cpu);
  2334. aot_set_last_error(buf);
  2335. goto fail;
  2336. }
  2337. /* Add module flag and cpu feature for riscv target */
  2338. if (arch && !strncmp(arch, "riscv", 5)) {
  2339. LLVMMetadataRef meta_target_abi;
  2340. if (!(meta_target_abi = LLVMMDStringInContext2(comp_ctx->context,
  2341. abi, strlen(abi)))) {
  2342. aot_set_last_error("create metadata string failed.");
  2343. goto fail;
  2344. }
  2345. LLVMAddModuleFlag(comp_ctx->module, LLVMModuleFlagBehaviorError,
  2346. "target-abi", strlen("target-abi"),
  2347. meta_target_abi);
  2348. if (!strcmp(abi, "lp64d") || !strcmp(abi, "ilp32d")) {
  2349. if (features) {
  2350. snprintf(features_buf, sizeof(features_buf), "%s%s",
  2351. features, ",+d");
  2352. features = features_buf;
  2353. }
  2354. else
  2355. features = "+d";
  2356. }
  2357. }
  2358. if (!features)
  2359. features = "";
  2360. /* Get target with triple, note that LLVMGetTargetFromTriple()
  2361. return 0 when success, but not true. */
  2362. if (LLVMGetTargetFromTriple(triple_norm, &target, &err) != 0) {
  2363. if (err) {
  2364. LLVMDisposeMessage(err);
  2365. err = NULL;
  2366. }
  2367. snprintf(buf, sizeof(buf),
  2368. "llvm get target from triple (%s) failed", triple_norm);
  2369. aot_set_last_error(buf);
  2370. goto fail;
  2371. }
  2372. /* Save target arch */
  2373. get_target_arch_from_triple(triple_norm, comp_ctx->target_arch,
  2374. sizeof(comp_ctx->target_arch));
  2375. if (option->bounds_checks == 1 || option->bounds_checks == 0) {
  2376. /* Set by user */
  2377. comp_ctx->enable_bound_check =
  2378. (option->bounds_checks == 1) ? true : false;
  2379. }
  2380. else {
  2381. /* Unset by user, use default value */
  2382. if (strstr(comp_ctx->target_arch, "64")
  2383. && !option->is_sgx_platform) {
  2384. comp_ctx->enable_bound_check = false;
  2385. }
  2386. else {
  2387. comp_ctx->enable_bound_check = true;
  2388. }
  2389. }
  2390. if (comp_ctx->enable_bound_check) {
  2391. /* Always enable stack boundary check if `bounds-checks`
  2392. is enabled */
  2393. comp_ctx->enable_stack_bound_check = true;
  2394. }
  2395. else {
  2396. /* When `bounds-checks` is disabled, we set stack boundary
  2397. check status according to the input option */
  2398. comp_ctx->enable_stack_bound_check =
  2399. (option->stack_bounds_checks == 1) ? true : false;
  2400. }
  2401. if ((comp_ctx->enable_stack_bound_check
  2402. || comp_ctx->enable_stack_estimation)
  2403. && option->stack_usage_file == NULL) {
  2404. if (!aot_generate_tempfile_name(
  2405. "wamrc-su", "su", comp_ctx->stack_usage_temp_file,
  2406. sizeof(comp_ctx->stack_usage_temp_file)))
  2407. goto fail;
  2408. comp_ctx->stack_usage_file = comp_ctx->stack_usage_temp_file;
  2409. }
  2410. else {
  2411. comp_ctx->stack_usage_file = option->stack_usage_file;
  2412. }
  2413. os_printf("Create AoT compiler with:\n");
  2414. os_printf(" target: %s\n", comp_ctx->target_arch);
  2415. os_printf(" target cpu: %s\n", cpu);
  2416. os_printf(" target triple: %s\n", triple_norm);
  2417. os_printf(" cpu features: %s\n", features);
  2418. os_printf(" opt level: %d\n", opt_level);
  2419. os_printf(" size level: %d\n", size_level);
  2420. switch (option->output_format) {
  2421. case AOT_LLVMIR_UNOPT_FILE:
  2422. os_printf(" output format: unoptimized LLVM IR\n");
  2423. break;
  2424. case AOT_LLVMIR_OPT_FILE:
  2425. os_printf(" output format: optimized LLVM IR\n");
  2426. break;
  2427. case AOT_FORMAT_FILE:
  2428. os_printf(" output format: AoT file\n");
  2429. break;
  2430. case AOT_OBJECT_FILE:
  2431. os_printf(" output format: native object file\n");
  2432. break;
  2433. }
  2434. LLVMSetTarget(comp_ctx->module, triple_norm);
  2435. if (!LLVMTargetHasTargetMachine(target)) {
  2436. snprintf(buf, sizeof(buf),
  2437. "no target machine for this target (%s).", triple_norm);
  2438. aot_set_last_error(buf);
  2439. goto fail;
  2440. }
  2441. /* Report error if target isn't arc and hasn't asm backend.
  2442. For arc target, as it cannot emit to memory buffer of elf file
  2443. currently, we let it emit to assembly file instead, and then call
  2444. arc-gcc to compile
  2445. asm file to elf file, and read elf file to memory buffer. */
  2446. if (strncmp(comp_ctx->target_arch, "arc", 3)
  2447. && !LLVMTargetHasAsmBackend(target)) {
  2448. snprintf(buf, sizeof(buf), "no asm backend for this target (%s).",
  2449. LLVMGetTargetName(target));
  2450. aot_set_last_error(buf);
  2451. goto fail;
  2452. }
  2453. /* Set code model */
  2454. if (size_level == 0)
  2455. code_model = LLVMCodeModelLarge;
  2456. else if (size_level == 1)
  2457. code_model = LLVMCodeModelMedium;
  2458. else if (size_level == 2)
  2459. code_model = LLVMCodeModelKernel;
  2460. else
  2461. code_model = LLVMCodeModelSmall;
  2462. /* Create the target machine */
  2463. if (!(comp_ctx->target_machine = LLVMCreateTargetMachineWithOpts(
  2464. target, triple_norm, cpu, features, opt_level,
  2465. LLVMRelocStatic, code_model, false,
  2466. comp_ctx->stack_usage_file))) {
  2467. aot_set_last_error("create LLVM target machine failed.");
  2468. goto fail;
  2469. }
  2470. }
  2471. triple = LLVMGetTargetMachineTriple(comp_ctx->target_machine);
  2472. if (!triple) {
  2473. aot_set_last_error("get target machine triple failed.");
  2474. goto fail;
  2475. }
  2476. if (strstr(triple, "linux") && !strcmp(comp_ctx->target_arch, "x86_64")) {
  2477. if (option->segue_flags) {
  2478. if (option->segue_flags & (1 << 0))
  2479. comp_ctx->enable_segue_i32_load = true;
  2480. if (option->segue_flags & (1 << 1))
  2481. comp_ctx->enable_segue_i64_load = true;
  2482. if (option->segue_flags & (1 << 2))
  2483. comp_ctx->enable_segue_f32_load = true;
  2484. if (option->segue_flags & (1 << 3))
  2485. comp_ctx->enable_segue_f64_load = true;
  2486. if (option->segue_flags & (1 << 4))
  2487. comp_ctx->enable_segue_v128_load = true;
  2488. if (option->segue_flags & (1 << 8))
  2489. comp_ctx->enable_segue_i32_store = true;
  2490. if (option->segue_flags & (1 << 9))
  2491. comp_ctx->enable_segue_i64_store = true;
  2492. if (option->segue_flags & (1 << 10))
  2493. comp_ctx->enable_segue_f32_store = true;
  2494. if (option->segue_flags & (1 << 11))
  2495. comp_ctx->enable_segue_f64_store = true;
  2496. if (option->segue_flags & (1 << 12))
  2497. comp_ctx->enable_segue_v128_store = true;
  2498. }
  2499. }
  2500. LLVMDisposeMessage(triple);
  2501. if (option->enable_simd && strcmp(comp_ctx->target_arch, "x86_64") != 0
  2502. && strncmp(comp_ctx->target_arch, "aarch64", 7) != 0) {
  2503. /* Disable simd if it isn't supported by target arch */
  2504. option->enable_simd = false;
  2505. }
  2506. if (option->enable_simd) {
  2507. char *tmp;
  2508. bool check_simd_ret;
  2509. comp_ctx->enable_simd = true;
  2510. if (!(tmp = LLVMGetTargetMachineCPU(comp_ctx->target_machine))) {
  2511. aot_set_last_error("get CPU from Target Machine fail");
  2512. goto fail;
  2513. }
  2514. check_simd_ret =
  2515. aot_check_simd_compatibility(comp_ctx->target_arch, tmp);
  2516. LLVMDisposeMessage(tmp);
  2517. if (!check_simd_ret) {
  2518. aot_set_last_error("SIMD compatibility check failed, "
  2519. "try adding --cpu=<cpu> to specify a cpu "
  2520. "or adding --disable-simd to disable SIMD");
  2521. goto fail;
  2522. }
  2523. }
  2524. if (!(target_data_ref =
  2525. LLVMCreateTargetDataLayout(comp_ctx->target_machine))) {
  2526. aot_set_last_error("create LLVM target data layout failed.");
  2527. goto fail;
  2528. }
  2529. LLVMSetModuleDataLayout(comp_ctx->module, target_data_ref);
  2530. comp_ctx->pointer_size = LLVMPointerSize(target_data_ref);
  2531. LLVMDisposeTargetData(target_data_ref);
  2532. comp_ctx->optimize = true;
  2533. if (option->output_format == AOT_LLVMIR_UNOPT_FILE)
  2534. comp_ctx->optimize = false;
  2535. /* Create metadata for llvm float experimental constrained intrinsics */
  2536. if (!(comp_ctx->fp_rounding_mode = LLVMMDStringInContext(
  2537. comp_ctx->context, fp_round, (uint32)strlen(fp_round)))
  2538. || !(comp_ctx->fp_exception_behavior = LLVMMDStringInContext(
  2539. comp_ctx->context, fp_exce, (uint32)strlen(fp_exce)))) {
  2540. aot_set_last_error("create float llvm metadata failed.");
  2541. goto fail;
  2542. }
  2543. if (!aot_set_llvm_basic_types(&comp_ctx->basic_types, comp_ctx->context,
  2544. comp_ctx->pointer_size)) {
  2545. aot_set_last_error("create LLVM basic types failed.");
  2546. goto fail;
  2547. }
  2548. if (!aot_create_llvm_consts(&comp_ctx->llvm_consts, comp_ctx)) {
  2549. aot_set_last_error("create LLVM const values failed.");
  2550. goto fail;
  2551. }
  2552. /* set exec_env data type to int8** */
  2553. comp_ctx->exec_env_type = comp_ctx->basic_types.int8_pptr_type;
  2554. /* set aot_inst data type to int8* */
  2555. comp_ctx->aot_inst_type = INT8_PTR_TYPE;
  2556. /* Create function context for each function */
  2557. comp_ctx->func_ctx_count = comp_data->func_count;
  2558. if (comp_data->func_count > 0
  2559. && !(comp_ctx->func_ctxes =
  2560. aot_create_func_contexts(comp_data, comp_ctx)))
  2561. goto fail;
  2562. if (cpu) {
  2563. uint32 len = (uint32)strlen(cpu) + 1;
  2564. if (!(comp_ctx->target_cpu = wasm_runtime_malloc(len))) {
  2565. aot_set_last_error("allocate memory failed");
  2566. goto fail;
  2567. }
  2568. bh_memcpy_s(comp_ctx->target_cpu, len, cpu, len);
  2569. }
  2570. if (comp_ctx->disable_llvm_intrinsics)
  2571. aot_intrinsic_fill_capability_flags(comp_ctx);
  2572. ret = comp_ctx;
  2573. fail:
  2574. if (triple_norm_new)
  2575. LLVMDisposeMessage(triple_norm_new);
  2576. if (cpu_new)
  2577. LLVMDisposeMessage(cpu_new);
  2578. if (!ret)
  2579. aot_destroy_comp_context(comp_ctx);
  2580. (void)i;
  2581. return ret;
  2582. }
  2583. void
  2584. aot_destroy_comp_context(AOTCompContext *comp_ctx)
  2585. {
  2586. if (!comp_ctx)
  2587. return;
  2588. if (comp_ctx->stack_usage_file == comp_ctx->stack_usage_temp_file) {
  2589. (void)unlink(comp_ctx->stack_usage_temp_file);
  2590. }
  2591. if (comp_ctx->target_machine)
  2592. LLVMDisposeTargetMachine(comp_ctx->target_machine);
  2593. if (comp_ctx->builder)
  2594. LLVMDisposeBuilder(comp_ctx->builder);
  2595. if (comp_ctx->orc_thread_safe_context)
  2596. LLVMOrcDisposeThreadSafeContext(comp_ctx->orc_thread_safe_context);
  2597. /* Note: don't dispose comp_ctx->context and comp_ctx->module as
  2598. they are disposed when disposing the thread safe context */
  2599. /* Has to be the last one */
  2600. if (comp_ctx->orc_jit)
  2601. LLVMOrcDisposeLLLazyJIT(comp_ctx->orc_jit);
  2602. if (comp_ctx->func_ctxes)
  2603. aot_destroy_func_contexts(comp_ctx->func_ctxes,
  2604. comp_ctx->func_ctx_count);
  2605. if (bh_list_length(&comp_ctx->native_symbols) > 0) {
  2606. AOTNativeSymbol *sym = bh_list_first_elem(&comp_ctx->native_symbols);
  2607. while (sym) {
  2608. AOTNativeSymbol *t = bh_list_elem_next(sym);
  2609. bh_list_remove(&comp_ctx->native_symbols, sym);
  2610. wasm_runtime_free(sym);
  2611. sym = t;
  2612. }
  2613. }
  2614. if (comp_ctx->target_cpu) {
  2615. wasm_runtime_free(comp_ctx->target_cpu);
  2616. }
  2617. wasm_runtime_free(comp_ctx);
  2618. }
  2619. static bool
  2620. insert_native_symbol(AOTCompContext *comp_ctx, const char *symbol, int32 idx)
  2621. {
  2622. AOTNativeSymbol *sym = wasm_runtime_malloc(sizeof(AOTNativeSymbol));
  2623. if (!sym) {
  2624. aot_set_last_error("alloc native symbol failed.");
  2625. return false;
  2626. }
  2627. memset(sym, 0, sizeof(AOTNativeSymbol));
  2628. bh_assert(strlen(symbol) <= sizeof(sym->symbol));
  2629. snprintf(sym->symbol, sizeof(sym->symbol), "%s", symbol);
  2630. sym->index = idx;
  2631. if (BH_LIST_ERROR == bh_list_insert(&comp_ctx->native_symbols, sym)) {
  2632. wasm_runtime_free(sym);
  2633. aot_set_last_error("insert native symbol to list failed.");
  2634. return false;
  2635. }
  2636. return true;
  2637. }
  2638. int32
  2639. aot_get_native_symbol_index(AOTCompContext *comp_ctx, const char *symbol)
  2640. {
  2641. int32 idx = -1;
  2642. AOTNativeSymbol *sym = NULL;
  2643. sym = bh_list_first_elem(&comp_ctx->native_symbols);
  2644. /* Lookup an existing symobl record */
  2645. while (sym) {
  2646. if (strcmp(sym->symbol, symbol) == 0) {
  2647. idx = sym->index;
  2648. break;
  2649. }
  2650. sym = bh_list_elem_next(sym);
  2651. }
  2652. /* Given symbol is not exist in list, then we alloc a new index for it */
  2653. if (idx < 0) {
  2654. if (comp_ctx->pointer_size == sizeof(uint32)
  2655. && (!strncmp(symbol, "f64#", 4) || !strncmp(symbol, "i64#", 4))) {
  2656. idx = bh_list_length(&comp_ctx->native_symbols);
  2657. /* Add 4 bytes padding on 32-bit target to make sure that
  2658. the f64 const is stored on 8-byte aligned address */
  2659. if (idx & 1) {
  2660. if (!insert_native_symbol(comp_ctx, "__ignore", idx)) {
  2661. return -1;
  2662. }
  2663. }
  2664. }
  2665. idx = bh_list_length(&comp_ctx->native_symbols);
  2666. if (!insert_native_symbol(comp_ctx, symbol, idx)) {
  2667. return -1;
  2668. }
  2669. if (comp_ctx->pointer_size == sizeof(uint32)
  2670. && (!strncmp(symbol, "f64#", 4) || !strncmp(symbol, "i64#", 4))) {
  2671. /* f64 const occupies 2 pointer slots on 32-bit target */
  2672. if (!insert_native_symbol(comp_ctx, "__ignore", idx + 1)) {
  2673. return -1;
  2674. }
  2675. }
  2676. }
  2677. return idx;
  2678. }
  2679. void
  2680. aot_value_stack_push(AOTValueStack *stack, AOTValue *value)
  2681. {
  2682. if (!stack->value_list_head)
  2683. stack->value_list_head = stack->value_list_end = value;
  2684. else {
  2685. stack->value_list_end->next = value;
  2686. value->prev = stack->value_list_end;
  2687. stack->value_list_end = value;
  2688. }
  2689. }
  2690. AOTValue *
  2691. aot_value_stack_pop(AOTValueStack *stack)
  2692. {
  2693. AOTValue *value = stack->value_list_end;
  2694. bh_assert(stack->value_list_end);
  2695. if (stack->value_list_head == stack->value_list_end)
  2696. stack->value_list_head = stack->value_list_end = NULL;
  2697. else {
  2698. stack->value_list_end = stack->value_list_end->prev;
  2699. stack->value_list_end->next = NULL;
  2700. value->prev = NULL;
  2701. }
  2702. return value;
  2703. }
  2704. void
  2705. aot_value_stack_destroy(AOTValueStack *stack)
  2706. {
  2707. AOTValue *value = stack->value_list_head, *p;
  2708. while (value) {
  2709. p = value->next;
  2710. wasm_runtime_free(value);
  2711. value = p;
  2712. }
  2713. stack->value_list_head = NULL;
  2714. stack->value_list_end = NULL;
  2715. }
  2716. void
  2717. aot_block_stack_push(AOTBlockStack *stack, AOTBlock *block)
  2718. {
  2719. if (!stack->block_list_head)
  2720. stack->block_list_head = stack->block_list_end = block;
  2721. else {
  2722. stack->block_list_end->next = block;
  2723. block->prev = stack->block_list_end;
  2724. stack->block_list_end = block;
  2725. }
  2726. }
  2727. AOTBlock *
  2728. aot_block_stack_pop(AOTBlockStack *stack)
  2729. {
  2730. AOTBlock *block = stack->block_list_end;
  2731. bh_assert(stack->block_list_end);
  2732. if (stack->block_list_head == stack->block_list_end)
  2733. stack->block_list_head = stack->block_list_end = NULL;
  2734. else {
  2735. stack->block_list_end = stack->block_list_end->prev;
  2736. stack->block_list_end->next = NULL;
  2737. block->prev = NULL;
  2738. }
  2739. return block;
  2740. }
  2741. void
  2742. aot_block_stack_destroy(AOTBlockStack *stack)
  2743. {
  2744. AOTBlock *block = stack->block_list_head, *p;
  2745. while (block) {
  2746. p = block->next;
  2747. aot_value_stack_destroy(&block->value_stack);
  2748. aot_block_destroy(block);
  2749. block = p;
  2750. }
  2751. stack->block_list_head = NULL;
  2752. stack->block_list_end = NULL;
  2753. }
  2754. void
  2755. aot_block_destroy(AOTBlock *block)
  2756. {
  2757. aot_value_stack_destroy(&block->value_stack);
  2758. if (block->param_types)
  2759. wasm_runtime_free(block->param_types);
  2760. if (block->param_phis)
  2761. wasm_runtime_free(block->param_phis);
  2762. if (block->else_param_phis)
  2763. wasm_runtime_free(block->else_param_phis);
  2764. if (block->result_types)
  2765. wasm_runtime_free(block->result_types);
  2766. if (block->result_phis)
  2767. wasm_runtime_free(block->result_phis);
  2768. wasm_runtime_free(block);
  2769. }
  2770. bool
  2771. aot_checked_addr_list_add(AOTFuncContext *func_ctx, uint32 local_idx,
  2772. uint32 offset, uint32 bytes)
  2773. {
  2774. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2775. if (!(node = wasm_runtime_malloc(sizeof(AOTCheckedAddr)))) {
  2776. aot_set_last_error("allocate memory failed.");
  2777. return false;
  2778. }
  2779. node->local_idx = local_idx;
  2780. node->offset = offset;
  2781. node->bytes = bytes;
  2782. node->next = func_ctx->checked_addr_list;
  2783. func_ctx->checked_addr_list = node;
  2784. return true;
  2785. }
  2786. void
  2787. aot_checked_addr_list_del(AOTFuncContext *func_ctx, uint32 local_idx)
  2788. {
  2789. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2790. AOTCheckedAddr *node_prev = NULL, *node_next;
  2791. while (node) {
  2792. node_next = node->next;
  2793. if (node->local_idx == local_idx) {
  2794. if (!node_prev)
  2795. func_ctx->checked_addr_list = node_next;
  2796. else
  2797. node_prev->next = node_next;
  2798. wasm_runtime_free(node);
  2799. }
  2800. else {
  2801. node_prev = node;
  2802. }
  2803. node = node_next;
  2804. }
  2805. }
  2806. bool
  2807. aot_checked_addr_list_find(AOTFuncContext *func_ctx, uint32 local_idx,
  2808. uint32 offset, uint32 bytes)
  2809. {
  2810. AOTCheckedAddr *node = func_ctx->checked_addr_list;
  2811. while (node) {
  2812. if (node->local_idx == local_idx && node->offset == offset
  2813. && node->bytes >= bytes) {
  2814. return true;
  2815. }
  2816. node = node->next;
  2817. }
  2818. return false;
  2819. }
  2820. void
  2821. aot_checked_addr_list_destroy(AOTFuncContext *func_ctx)
  2822. {
  2823. AOTCheckedAddr *node = func_ctx->checked_addr_list, *node_next;
  2824. while (node) {
  2825. node_next = node->next;
  2826. wasm_runtime_free(node);
  2827. node = node_next;
  2828. }
  2829. func_ctx->checked_addr_list = NULL;
  2830. }
  2831. bool
  2832. aot_build_zero_function_ret(const AOTCompContext *comp_ctx,
  2833. AOTFuncContext *func_ctx, AOTFuncType *func_type)
  2834. {
  2835. LLVMValueRef ret = NULL;
  2836. if (func_type->result_count) {
  2837. switch (func_type->types[func_type->param_count]) {
  2838. case VALUE_TYPE_I32:
  2839. ret = LLVMBuildRet(comp_ctx->builder, I32_ZERO);
  2840. break;
  2841. case VALUE_TYPE_I64:
  2842. ret = LLVMBuildRet(comp_ctx->builder, I64_ZERO);
  2843. break;
  2844. case VALUE_TYPE_F32:
  2845. ret = LLVMBuildRet(comp_ctx->builder, F32_ZERO);
  2846. break;
  2847. case VALUE_TYPE_F64:
  2848. ret = LLVMBuildRet(comp_ctx->builder, F64_ZERO);
  2849. break;
  2850. case VALUE_TYPE_V128:
  2851. ret =
  2852. LLVMBuildRet(comp_ctx->builder, LLVM_CONST(i64x2_vec_zero));
  2853. break;
  2854. case VALUE_TYPE_FUNCREF:
  2855. case VALUE_TYPE_EXTERNREF:
  2856. ret = LLVMBuildRet(comp_ctx->builder, REF_NULL);
  2857. break;
  2858. default:
  2859. bh_assert(0);
  2860. }
  2861. }
  2862. else {
  2863. ret = LLVMBuildRetVoid(comp_ctx->builder);
  2864. }
  2865. if (!ret) {
  2866. aot_set_last_error("llvm build ret failed.");
  2867. return false;
  2868. }
  2869. #if WASM_ENABLE_DEBUG_AOT != 0
  2870. /* debug_func is NULL for precheck function */
  2871. if (func_ctx->debug_func != NULL) {
  2872. LLVMMetadataRef return_location =
  2873. dwarf_gen_func_ret_location(comp_ctx, func_ctx);
  2874. LLVMInstructionSetDebugLoc(ret, return_location);
  2875. }
  2876. #endif
  2877. return true;
  2878. }
  2879. static LLVMValueRef
  2880. __call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2881. const AOTFuncContext *func_ctx, const char *name,
  2882. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2883. int param_count, LLVMValueRef *param_values)
  2884. {
  2885. LLVMValueRef func, ret;
  2886. LLVMTypeRef func_type;
  2887. const char *symname;
  2888. int32 func_idx;
  2889. if (comp_ctx->disable_llvm_intrinsics
  2890. && aot_intrinsic_check_capability(comp_ctx, name)) {
  2891. if (func_ctx == NULL) {
  2892. aot_set_last_error_v("invalid func_ctx for intrinsic: %s", name);
  2893. return NULL;
  2894. }
  2895. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2896. (uint32)param_count, false))) {
  2897. aot_set_last_error("create LLVM intrinsic function type failed.");
  2898. return NULL;
  2899. }
  2900. if (!(func_type = LLVMPointerType(func_type, 0))) {
  2901. aot_set_last_error(
  2902. "create LLVM intrinsic function pointer type failed.");
  2903. return NULL;
  2904. }
  2905. if (!(symname = aot_intrinsic_get_symbol(name))) {
  2906. aot_set_last_error_v("runtime intrinsic not implemented: %s\n",
  2907. name);
  2908. return NULL;
  2909. }
  2910. func_idx =
  2911. aot_get_native_symbol_index((AOTCompContext *)comp_ctx, symname);
  2912. if (func_idx < 0) {
  2913. aot_set_last_error_v("get runtime intrinsc index failed: %s\n",
  2914. name);
  2915. return NULL;
  2916. }
  2917. if (!(func = aot_get_func_from_table(comp_ctx, func_ctx->native_symbol,
  2918. func_type, func_idx))) {
  2919. aot_set_last_error_v("get runtime intrinsc failed: %s\n", name);
  2920. return NULL;
  2921. }
  2922. }
  2923. else {
  2924. /* Declare llvm intrinsic function if necessary */
  2925. if (!(func = LLVMGetNamedFunction(func_ctx->module, name))) {
  2926. if (!(func_type = LLVMFunctionType(ret_type, param_types,
  2927. (uint32)param_count, false))) {
  2928. aot_set_last_error(
  2929. "create LLVM intrinsic function type failed.");
  2930. return NULL;
  2931. }
  2932. if (!(func = LLVMAddFunction(func_ctx->module, name, func_type))) {
  2933. aot_set_last_error("add LLVM intrinsic function failed.");
  2934. return NULL;
  2935. }
  2936. }
  2937. }
  2938. #if LLVM_VERSION_MAJOR >= 14
  2939. func_type =
  2940. LLVMFunctionType(ret_type, param_types, (uint32)param_count, false);
  2941. #endif
  2942. /* Call the LLVM intrinsic function */
  2943. if (!(ret = LLVMBuildCall2(comp_ctx->builder, func_type, func, param_values,
  2944. (uint32)param_count, "call"))) {
  2945. aot_set_last_error("llvm build intrinsic call failed.");
  2946. return NULL;
  2947. }
  2948. return ret;
  2949. }
  2950. LLVMValueRef
  2951. aot_call_llvm_intrinsic(const AOTCompContext *comp_ctx,
  2952. const AOTFuncContext *func_ctx, const char *intrinsic,
  2953. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2954. int param_count, ...)
  2955. {
  2956. LLVMValueRef *param_values, ret;
  2957. va_list argptr;
  2958. uint64 total_size;
  2959. int i = 0;
  2960. /* Create param values */
  2961. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2962. if (total_size >= UINT32_MAX
  2963. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2964. aot_set_last_error("allocate memory for param values failed.");
  2965. return false;
  2966. }
  2967. /* Load each param value */
  2968. va_start(argptr, param_count);
  2969. while (i < param_count)
  2970. param_values[i++] = va_arg(argptr, LLVMValueRef);
  2971. va_end(argptr);
  2972. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2973. param_types, param_count, param_values);
  2974. wasm_runtime_free(param_values);
  2975. return ret;
  2976. }
  2977. LLVMValueRef
  2978. aot_call_llvm_intrinsic_v(const AOTCompContext *comp_ctx,
  2979. const AOTFuncContext *func_ctx, const char *intrinsic,
  2980. LLVMTypeRef ret_type, LLVMTypeRef *param_types,
  2981. int param_count, va_list param_value_list)
  2982. {
  2983. LLVMValueRef *param_values, ret;
  2984. uint64 total_size;
  2985. int i = 0;
  2986. /* Create param values */
  2987. total_size = sizeof(LLVMValueRef) * (uint64)param_count;
  2988. if (total_size >= UINT32_MAX
  2989. || !(param_values = wasm_runtime_malloc((uint32)total_size))) {
  2990. aot_set_last_error("allocate memory for param values failed.");
  2991. return false;
  2992. }
  2993. /* Load each param value */
  2994. while (i < param_count)
  2995. param_values[i++] = va_arg(param_value_list, LLVMValueRef);
  2996. ret = __call_llvm_intrinsic(comp_ctx, func_ctx, intrinsic, ret_type,
  2997. param_types, param_count, param_values);
  2998. wasm_runtime_free(param_values);
  2999. return ret;
  3000. }
  3001. LLVMValueRef
  3002. aot_get_func_from_table(const AOTCompContext *comp_ctx, LLVMValueRef base,
  3003. LLVMTypeRef func_type, int32 index)
  3004. {
  3005. LLVMValueRef func;
  3006. LLVMValueRef func_addr;
  3007. if (!(func_addr = I32_CONST(index))) {
  3008. aot_set_last_error("construct function index failed.");
  3009. goto fail;
  3010. }
  3011. if (!(func_addr =
  3012. LLVMBuildInBoundsGEP2(comp_ctx->builder, OPQ_PTR_TYPE, base,
  3013. &func_addr, 1, "func_addr"))) {
  3014. aot_set_last_error("get function addr by index failed.");
  3015. goto fail;
  3016. }
  3017. func =
  3018. LLVMBuildLoad2(comp_ctx->builder, OPQ_PTR_TYPE, func_addr, "func_tmp");
  3019. if (func == NULL) {
  3020. aot_set_last_error("get function pointer failed.");
  3021. goto fail;
  3022. }
  3023. if (!(func =
  3024. LLVMBuildBitCast(comp_ctx->builder, func, func_type, "func"))) {
  3025. aot_set_last_error("cast function fialed.");
  3026. goto fail;
  3027. }
  3028. return func;
  3029. fail:
  3030. return NULL;
  3031. }
  3032. LLVMValueRef
  3033. aot_load_const_from_table(AOTCompContext *comp_ctx, LLVMValueRef base,
  3034. const WASMValue *value, uint8 value_type)
  3035. {
  3036. LLVMValueRef const_index, const_addr, const_value;
  3037. LLVMTypeRef const_ptr_type, const_type;
  3038. char buf[128] = { 0 };
  3039. int32 index;
  3040. switch (value_type) {
  3041. case VALUE_TYPE_I32:
  3042. /* Store the raw int bits of i32 const as a hex string */
  3043. snprintf(buf, sizeof(buf), "i32#%08" PRIX32, value->i32);
  3044. const_ptr_type = INT32_PTR_TYPE;
  3045. const_type = I32_TYPE;
  3046. break;
  3047. case VALUE_TYPE_I64:
  3048. /* Store the raw int bits of i64 const as a hex string */
  3049. snprintf(buf, sizeof(buf), "i64#%016" PRIX64, value->i64);
  3050. const_ptr_type = INT64_PTR_TYPE;
  3051. const_type = I64_TYPE;
  3052. break;
  3053. case VALUE_TYPE_F32:
  3054. /* Store the raw int bits of f32 const as a hex string */
  3055. snprintf(buf, sizeof(buf), "f32#%08" PRIX32, value->i32);
  3056. const_ptr_type = F32_PTR_TYPE;
  3057. const_type = F32_TYPE;
  3058. break;
  3059. case VALUE_TYPE_F64:
  3060. /* Store the raw int bits of f64 const as a hex string */
  3061. snprintf(buf, sizeof(buf), "f64#%016" PRIX64, value->i64);
  3062. const_ptr_type = F64_PTR_TYPE;
  3063. const_type = F64_TYPE;
  3064. break;
  3065. default:
  3066. bh_assert(0);
  3067. return NULL;
  3068. }
  3069. /* Load f32/f64 const from exec_env->native_symbol[index] */
  3070. index = aot_get_native_symbol_index(comp_ctx, buf);
  3071. if (index < 0) {
  3072. return NULL;
  3073. }
  3074. if (!(const_index = I32_CONST(index))) {
  3075. aot_set_last_error("construct const index failed.");
  3076. return NULL;
  3077. }
  3078. if (!(const_addr =
  3079. LLVMBuildInBoundsGEP2(comp_ctx->builder, OPQ_PTR_TYPE, base,
  3080. &const_index, 1, "const_addr_tmp"))) {
  3081. aot_set_last_error("get const addr by index failed.");
  3082. return NULL;
  3083. }
  3084. if (!(const_addr = LLVMBuildBitCast(comp_ctx->builder, const_addr,
  3085. const_ptr_type, "const_addr"))) {
  3086. aot_set_last_error("cast const fialed.");
  3087. return NULL;
  3088. }
  3089. if (!(const_value = LLVMBuildLoad2(comp_ctx->builder, const_type,
  3090. const_addr, "const_value"))) {
  3091. aot_set_last_error("load const failed.");
  3092. return NULL;
  3093. }
  3094. (void)const_type;
  3095. return const_value;
  3096. }
  3097. bool
  3098. aot_set_cond_br_weights(AOTCompContext *comp_ctx, LLVMValueRef cond_br,
  3099. int32 weights_true, int32 weights_false)
  3100. {
  3101. LLVMMetadataRef md_nodes[3], meta_data;
  3102. LLVMValueRef meta_data_as_value;
  3103. md_nodes[0] = LLVMMDStringInContext2(comp_ctx->context, "branch_weights",
  3104. strlen("branch_weights"));
  3105. md_nodes[1] = LLVMValueAsMetadata(I32_CONST(weights_true));
  3106. md_nodes[2] = LLVMValueAsMetadata(I32_CONST(weights_false));
  3107. meta_data = LLVMMDNodeInContext2(comp_ctx->context, md_nodes, 3);
  3108. meta_data_as_value = LLVMMetadataAsValue(comp_ctx->context, meta_data);
  3109. LLVMSetMetadata(cond_br, 2, meta_data_as_value);
  3110. return true;
  3111. }