aot_llvm.c 137 KB

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