cpupi.pas 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. {
  2. Copyright (c) 2002-2010 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the CPU specific part of tprocinfo
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit cpupi;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. cutils,globtype,aasmdata,aasmcpu,aasmtai,
  22. procinfo,cpubase,cpuinfo, symtype,aasmbase,cgbase,
  23. psub, cclasses;
  24. type
  25. { tcpuprocinfo }
  26. tcpuprocinfo=class(tcgprocinfo)
  27. private
  28. FFirstFreeLocal: Integer;
  29. FAllocatedLocals: array of TWasmBasicType;
  30. FGotoTargets: TFPHashObjectList;
  31. function ConvertBranchTargetNumbersToLabels(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  32. function ConvertIfToBrIf(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  33. function ConvertLoopToBr(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  34. function StripBlockInstructions(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  35. { used for allocating locals during the postprocess_code stage (i.e. after register allocation) }
  36. function AllocWasmLocal(wbt: TWasmBasicType): Integer;
  37. public
  38. { label to the nearest local exception handler }
  39. CurrRaiseLabel : tasmlabel;
  40. constructor create(aparent: tprocinfo); override;
  41. destructor destroy; override;
  42. function calc_stackframe_size : longint;override;
  43. procedure setup_eh; override;
  44. procedure generate_exit_label(list: tasmlist); override;
  45. procedure postprocess_code; override;
  46. procedure set_first_temp_offset;override;
  47. procedure add_goto_target(l : tasmlabel);
  48. function is_goto_target(l : tasmsymbol): Boolean;
  49. end;
  50. implementation
  51. uses
  52. systems,verbose,globals,tgcpu,cgexcept,
  53. tgobj,paramgr,symconst,symdef,symtable,symcpu,cgutils,pass_2,parabase,
  54. fmodule,hlcgobj,hlcgcpu,defutil,itcpugas;
  55. {*****************************************************************************
  56. twasmexceptionstatehandler_noexceptions
  57. *****************************************************************************}
  58. type
  59. { twasmexceptionstatehandler_noexceptions }
  60. twasmexceptionstatehandler_noexceptions = class(tcgexceptionstatehandler)
  61. class procedure get_exception_temps(list:TAsmList;var t:texceptiontemps); override;
  62. class procedure unget_exception_temps(list:TAsmList;const t:texceptiontemps); override;
  63. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  64. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  65. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  66. end;
  67. class procedure twasmexceptionstatehandler_noexceptions.get_exception_temps(list:TAsmList;var t:texceptiontemps);
  68. begin
  69. if not assigned(exceptionreasontype) then
  70. exceptionreasontype:=search_system_proc('fpc_setjmp').returndef;
  71. reference_reset(t.envbuf,0,[]);
  72. reference_reset(t.jmpbuf,0,[]);
  73. tg.gethltemp(list,exceptionreasontype,exceptionreasontype.size,tt_persistent,t.reasonbuf);
  74. end;
  75. class procedure twasmexceptionstatehandler_noexceptions.unget_exception_temps(list:TAsmList;const t:texceptiontemps);
  76. begin
  77. tg.ungettemp(list,t.reasonbuf);
  78. end;
  79. class procedure twasmexceptionstatehandler_noexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  80. begin
  81. exceptstate.exceptionlabel:=nil;
  82. exceptstate.oldflowcontrol:=flowcontrol;
  83. exceptstate.finallycodelabel:=nil;
  84. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  85. end;
  86. class procedure twasmexceptionstatehandler_noexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  87. begin
  88. end;
  89. class procedure twasmexceptionstatehandler_noexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  90. begin
  91. list.Concat(tai_comment.Create(strpnew('TODO: handle_nested_exception')));
  92. end;
  93. {*****************************************************************************
  94. twasmexceptionstatehandler_jsexceptions
  95. *****************************************************************************}
  96. type
  97. twasmexceptionstatehandler_jsexceptions = class(tcgexceptionstatehandler)
  98. class procedure get_exception_temps(list:TAsmList;var t:texceptiontemps); override;
  99. class procedure unget_exception_temps(list:TAsmList;const t:texceptiontemps); override;
  100. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  101. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  102. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  103. end;
  104. class procedure twasmexceptionstatehandler_jsexceptions.get_exception_temps(list:TAsmList;var t:texceptiontemps);
  105. begin
  106. if not assigned(exceptionreasontype) then
  107. exceptionreasontype:=search_system_proc('fpc_setjmp').returndef;
  108. reference_reset(t.envbuf,0,[]);
  109. reference_reset(t.jmpbuf,0,[]);
  110. tg.gethltemp(list,exceptionreasontype,exceptionreasontype.size,tt_persistent,t.reasonbuf);
  111. end;
  112. class procedure twasmexceptionstatehandler_jsexceptions.unget_exception_temps(list:TAsmList;const t:texceptiontemps);
  113. begin
  114. tg.ungettemp(list,t.reasonbuf);
  115. end;
  116. class procedure twasmexceptionstatehandler_jsexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  117. begin
  118. exceptstate.exceptionlabel:=nil;
  119. exceptstate.oldflowcontrol:=flowcontrol;
  120. exceptstate.finallycodelabel:=nil;
  121. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  122. end;
  123. class procedure twasmexceptionstatehandler_jsexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  124. begin
  125. end;
  126. class procedure twasmexceptionstatehandler_jsexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  127. begin
  128. list.Concat(tai_comment.Create(strpnew('TODO: handle_nested_exception')));
  129. end;
  130. {*****************************************************************************
  131. twasmexceptionstatehandler_nativeexceptions
  132. *****************************************************************************}
  133. type
  134. { twasmexceptionstatehandler_nativeexceptions }
  135. twasmexceptionstatehandler_nativeexceptions = class(tcgexceptionstatehandler)
  136. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  137. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  138. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  139. { start of an "on" (catch) block }
  140. class procedure begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister); override;
  141. { end of an "on" (catch) block }
  142. class procedure end_catch(list: TAsmList); override;
  143. end;
  144. class procedure twasmexceptionstatehandler_nativeexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  145. begin
  146. exceptstate.exceptionlabel:=nil;
  147. exceptstate.oldflowcontrol:=flowcontrol;
  148. exceptstate.finallycodelabel:=nil;
  149. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  150. end;
  151. class procedure twasmexceptionstatehandler_nativeexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  152. begin
  153. end;
  154. class procedure twasmexceptionstatehandler_nativeexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  155. begin
  156. Message1(parser_f_unsupported_feature,'nested exception');
  157. end;
  158. class procedure twasmexceptionstatehandler_nativeexceptions.begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister);
  159. var
  160. pd: tprocdef;
  161. href2: treference;
  162. fpc_catches_res,
  163. paraloc1: tcgpara;
  164. exceptloc: tlocation;
  165. indirect: boolean;
  166. otherunit: boolean;
  167. begin
  168. paraloc1.init;
  169. otherunit:=findunitsymtable(excepttype.owner).moduleid<>findunitsymtable(current_procinfo.procdef.owner).moduleid;
  170. indirect:=(tf_supports_packages in target_info.flags) and
  171. (target_info.system in systems_indirect_var_imports) and
  172. (cs_imported_data in current_settings.localswitches) and
  173. otherunit;
  174. { send the vmt parameter }
  175. pd:=search_system_proc('fpc_catches');
  176. reference_reset_symbol(href2, current_asmdata.RefAsmSymbol(excepttype.vmt_mangledname, AT_DATA, indirect), 0, sizeof(pint), []);
  177. if otherunit then
  178. current_module.add_extern_asmsym(excepttype.vmt_mangledname, AB_EXTERNAL, AT_DATA);
  179. paramanager.getcgtempparaloc(list, pd, 1, paraloc1);
  180. hlcg.a_loadaddr_ref_cgpara(list, excepttype.vmt_def, href2, paraloc1);
  181. paramanager.freecgpara(list, paraloc1);
  182. fpc_catches_res:=hlcg.g_call_system_proc(list, pd, [@paraloc1], nil);
  183. location_reset(exceptloc, LOC_REGISTER, def_cgsize(fpc_catches_res.def));
  184. exceptloc.register:=hlcg.getaddressregister(list, fpc_catches_res.def);
  185. hlcg.gen_load_cgpara_loc(list, fpc_catches_res.def, fpc_catches_res, exceptloc, true);
  186. { is it this catch? }
  187. thlcgwasm(hlcg).a_cmp_const_reg_stack(list, fpc_catches_res.def, OC_NE, 0, exceptloc.register);
  188. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_if));
  189. thlcgwasm(hlcg).decstack(current_asmdata.CurrAsmList,1);
  190. paraloc1.done;
  191. exceptlocdef:=fpc_catches_res.def;
  192. exceptlocreg:=exceptloc.register;
  193. end;
  194. class procedure twasmexceptionstatehandler_nativeexceptions.end_catch(list: TAsmList);
  195. begin
  196. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_end_if));
  197. end;
  198. {*****************************************************************************
  199. twasmexceptionstatehandler_bfexceptions
  200. *****************************************************************************}
  201. type
  202. { twasmexceptionstatehandler_bfexceptions }
  203. twasmexceptionstatehandler_bfexceptions = class(tcgexceptionstatehandler)
  204. class procedure new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate); override;
  205. class procedure free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean); override;
  206. class procedure handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate); override;
  207. { start of an "on" (catch) block }
  208. class procedure begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister); override;
  209. { end of an "on" (catch) block }
  210. class procedure end_catch(list: TAsmList); override;
  211. end;
  212. class procedure twasmexceptionstatehandler_bfexceptions.new_exception(list:TAsmList;const t:texceptiontemps; const exceptframekind: texceptframekind; out exceptstate: texceptionstate);
  213. begin
  214. exceptstate.exceptionlabel:=nil;
  215. exceptstate.oldflowcontrol:=flowcontrol;
  216. exceptstate.finallycodelabel:=nil;
  217. flowcontrol:=[fc_inflowcontrol,fc_catching_exceptions];
  218. end;
  219. class procedure twasmexceptionstatehandler_bfexceptions.free_exception(list: TAsmList; const t: texceptiontemps; const s: texceptionstate; a: aint; endexceptlabel: tasmlabel; onlyfree:boolean);
  220. begin
  221. end;
  222. class procedure twasmexceptionstatehandler_bfexceptions.handle_nested_exception(list:TAsmList;var t:texceptiontemps;var entrystate: texceptionstate);
  223. begin
  224. Message1(parser_f_unsupported_feature,'nested exception');
  225. end;
  226. class procedure twasmexceptionstatehandler_bfexceptions.begin_catch(list: TAsmList; excepttype: tobjectdef; nextonlabel: tasmlabel; out exceptlocdef: tdef; out exceptlocreg: tregister);
  227. var
  228. pd: tprocdef;
  229. href2: treference;
  230. fpc_catches_res,
  231. paraloc1: tcgpara;
  232. exceptloc: tlocation;
  233. indirect: boolean;
  234. otherunit: boolean;
  235. begin
  236. paraloc1.init;
  237. otherunit:=findunitsymtable(excepttype.owner).moduleid<>findunitsymtable(current_procinfo.procdef.owner).moduleid;
  238. indirect:=(tf_supports_packages in target_info.flags) and
  239. (target_info.system in systems_indirect_var_imports) and
  240. (cs_imported_data in current_settings.localswitches) and
  241. otherunit;
  242. { send the vmt parameter }
  243. pd:=search_system_proc('fpc_catches');
  244. reference_reset_symbol(href2, current_asmdata.RefAsmSymbol(excepttype.vmt_mangledname, AT_DATA, indirect), 0, sizeof(pint), []);
  245. if otherunit then
  246. current_module.add_extern_asmsym(excepttype.vmt_mangledname, AB_EXTERNAL, AT_DATA);
  247. paramanager.getcgtempparaloc(list, pd, 1, paraloc1);
  248. hlcg.a_loadaddr_ref_cgpara(list, excepttype.vmt_def, href2, paraloc1);
  249. paramanager.freecgpara(list, paraloc1);
  250. fpc_catches_res:=hlcg.g_call_system_proc(list, pd, [@paraloc1], nil);
  251. location_reset(exceptloc, LOC_REGISTER, def_cgsize(fpc_catches_res.def));
  252. exceptloc.register:=hlcg.getaddressregister(list, fpc_catches_res.def);
  253. hlcg.gen_load_cgpara_loc(list, fpc_catches_res.def, fpc_catches_res, exceptloc, true);
  254. { is it this catch? }
  255. thlcgwasm(hlcg).a_cmp_const_reg_stack(list, fpc_catches_res.def, OC_NE, 0, exceptloc.register);
  256. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_if));
  257. thlcgwasm(hlcg).decstack(current_asmdata.CurrAsmList,1);
  258. paraloc1.done;
  259. exceptlocdef:=fpc_catches_res.def;
  260. exceptlocreg:=exceptloc.register;
  261. end;
  262. class procedure twasmexceptionstatehandler_bfexceptions.end_catch(list: TAsmList);
  263. begin
  264. current_asmdata.CurrAsmList.concat(taicpu.op_none(a_end_if));
  265. end;
  266. {*****************************************************************************
  267. twasmblockitem
  268. *****************************************************************************}
  269. type
  270. { twasmblockitem }
  271. twasmblockitem = class(TLinkedListItem)
  272. blockstart: taicpu;
  273. elseinstr: taicpu;
  274. constructor Create(ablockstart: taicpu);
  275. end;
  276. constructor twasmblockitem.Create(ablockstart: taicpu);
  277. begin
  278. blockstart:=ablockstart;
  279. end;
  280. {*****************************************************************************
  281. twasmblockstack
  282. *****************************************************************************}
  283. type
  284. { twasmblockstack }
  285. twasmblockstack = class(tlinkedlist)
  286. end;
  287. {*****************************************************************************
  288. tcpuprocinfo
  289. *****************************************************************************}
  290. function tcpuprocinfo.ConvertBranchTargetNumbersToLabels(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  291. var
  292. instr: taicpu;
  293. bl: taicpu_wasm_structured_instruction;
  294. l: TAsmLabel;
  295. begin
  296. result.typ:=amfrtNoChange;
  297. if ai.typ<>ait_instruction then
  298. exit;
  299. instr:=taicpu(ai);
  300. if not (instr.opcode in [a_br,a_br_if]) then
  301. exit;
  302. if instr.ops<>1 then
  303. internalerror(2023101601);
  304. if instr.oper[0]^.typ<>top_const then
  305. exit;
  306. bl:=blockstack[instr.oper[0]^.val];
  307. l:=bl.getlabel;
  308. instr.loadsymbol(0,l,0);
  309. end;
  310. function tcpuprocinfo.ConvertIfToBrIf(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  311. begin
  312. result.typ:=amfrtNoChange;
  313. if (ai.typ=ait_wasm_structured_instruction) and (taicpu_wasm_structured_instruction(ai).wstyp=aitws_if) then
  314. begin
  315. result.typ:=amfrtNewList;
  316. result.newlist:=TAsmList.Create;
  317. tai_wasmstruc_if(ai).ConvertToBrIf(result.newlist,@AllocWasmLocal);
  318. end;
  319. end;
  320. function tcpuprocinfo.ConvertLoopToBr(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  321. begin
  322. result.typ:=amfrtNoChange;
  323. if (ai.typ=ait_wasm_structured_instruction) and (taicpu_wasm_structured_instruction(ai).wstyp=aitws_loop) then
  324. begin
  325. result.typ:=amfrtNewList;
  326. result.newlist:=TAsmList.Create;
  327. tai_wasmstruc_loop(ai).ConvertToBr(result.newlist);
  328. end;
  329. end;
  330. function tcpuprocinfo.StripBlockInstructions(ai: tai; blockstack: twasmstruc_stack): TAsmMapFuncResult;
  331. var
  332. instr: taicpu;
  333. begin
  334. result.typ:=amfrtNoChange;
  335. if ai.typ<>ait_instruction then
  336. exit;
  337. instr:=taicpu(ai);
  338. if instr.opcode in [a_block,a_end_block] then
  339. result.typ:=amfrtDeleteAi;
  340. end;
  341. function tcpuprocinfo.AllocWasmLocal(wbt: TWasmBasicType): Integer;
  342. begin
  343. SetLength(FAllocatedLocals,Length(FAllocatedLocals)+1);
  344. FAllocatedLocals[High(FAllocatedLocals)]:=wbt;
  345. result:=High(FAllocatedLocals)+FFirstFreeLocal;
  346. end;
  347. constructor tcpuprocinfo.create(aparent: tprocinfo);
  348. begin
  349. inherited create(aparent);
  350. FGotoTargets:=TFPHashObjectList.Create(false);
  351. if ts_wasm_bf_exceptions in current_settings.targetswitches then
  352. current_asmdata.getjumplabel(CurrRaiseLabel);
  353. end;
  354. destructor tcpuprocinfo.destroy;
  355. begin
  356. FGotoTargets.Free;
  357. inherited destroy;
  358. end;
  359. function tcpuprocinfo.calc_stackframe_size: longint;
  360. begin
  361. { the stack frame in WebAssembly should always have a 16-byte alignment }
  362. Result:=Align(inherited calc_stackframe_size,16);
  363. end;
  364. procedure tcpuprocinfo.setup_eh;
  365. begin
  366. if ts_wasm_native_exceptions in current_settings.targetswitches then
  367. cexceptionstatehandler:=twasmexceptionstatehandler_nativeexceptions
  368. else if ts_wasm_js_exceptions in current_settings.targetswitches then
  369. cexceptionstatehandler:=twasmexceptionstatehandler_jsexceptions
  370. else if ts_wasm_no_exceptions in current_settings.targetswitches then
  371. cexceptionstatehandler:=twasmexceptionstatehandler_noexceptions
  372. else if ts_wasm_bf_exceptions in current_settings.targetswitches then
  373. cexceptionstatehandler:=twasmexceptionstatehandler_bfexceptions
  374. else
  375. internalerror(2021091701);
  376. end;
  377. procedure tcpuprocinfo.generate_exit_label(list: tasmlist);
  378. begin
  379. list.concat(taicpu.op_none(a_end_block));
  380. inherited generate_exit_label(list);
  381. end;
  382. procedure tcpuprocinfo.postprocess_code;
  383. function findfirst_tai_functype(asmlist: TAsmList): tai_functype;
  384. var
  385. hp: tai;
  386. begin
  387. result:=nil;
  388. if not assigned(asmlist) then
  389. exit;
  390. hp:=tai(asmlist.first);
  391. while assigned(hp) do
  392. begin
  393. if hp.typ=ait_functype then
  394. begin
  395. result:=tai_functype(hp);
  396. exit;
  397. end;
  398. hp:=tai(hp.Next);
  399. end;
  400. end;
  401. procedure replace_local_frame_pointer(asmlist: TAsmList);
  402. var
  403. hp: tai;
  404. instr: taicpu;
  405. l: Integer;
  406. begin
  407. if not assigned(asmlist) then
  408. exit;
  409. hp:=tai(asmlist.first);
  410. while assigned(hp) do
  411. begin
  412. if hp.typ=ait_instruction then
  413. begin
  414. instr:=taicpu(hp);
  415. for l:=0 to instr.ops-1 do
  416. if (instr.oper[l]^.typ=top_reg) and (instr.oper[l]^.reg=NR_LOCAL_FRAME_POINTER_REG) then
  417. instr.loadref(l,tcpuprocdef(current_procinfo.procdef).frame_pointer_ref);
  418. end;
  419. hp:=tai(hp.Next);
  420. end;
  421. end;
  422. function FindNextInstruction(hp: tai): taicpu;
  423. begin
  424. result:=nil;
  425. if not assigned(hp) then
  426. exit;
  427. repeat
  428. hp:=tai(hp.next);
  429. until not assigned(hp) or (hp.typ=ait_instruction);
  430. if assigned(hp) then
  431. result:=taicpu(hp);
  432. end;
  433. procedure resolve_labels_pass1(asmlist: TAsmList);
  434. var
  435. hp: tai;
  436. lastinstr, nextinstr: taicpu;
  437. cur_nesting_depth: longint;
  438. lbl: tai_label;
  439. blockstack: twasmblockstack;
  440. cblock: twasmblockitem;
  441. begin
  442. blockstack:=twasmblockstack.create;
  443. cur_nesting_depth:=0;
  444. lastinstr:=nil;
  445. hp:=tai(asmlist.first);
  446. while assigned(hp) do
  447. begin
  448. case hp.typ of
  449. ait_instruction:
  450. begin
  451. lastinstr:=taicpu(hp);
  452. case lastinstr.opcode of
  453. a_block,
  454. a_loop,
  455. a_if,
  456. a_try:
  457. begin
  458. blockstack.Concat(twasmblockitem.create(lastinstr));
  459. inc(cur_nesting_depth);
  460. end;
  461. a_else:
  462. begin
  463. cblock:=twasmblockitem(blockstack.Last);
  464. if (cblock=nil) or
  465. (cblock.blockstart.opcode<>a_if) or
  466. assigned(cblock.elseinstr) then
  467. Message1(parser_f_unsupported_feature,'misplaced a_else');
  468. cblock.elseinstr:=lastinstr;
  469. end;
  470. a_end_block,
  471. a_end_loop,
  472. a_end_if,
  473. a_end_try:
  474. begin
  475. dec(cur_nesting_depth);
  476. if cur_nesting_depth<0 then
  477. Message1(parser_f_unsupported_feature,'negative nesting level');
  478. cblock:=twasmblockitem(blockstack.GetLast);
  479. if (cblock=nil) or
  480. ((cblock.blockstart.opcode=a_block) and (lastinstr.opcode<>a_end_block)) or
  481. ((cblock.blockstart.opcode=a_loop) and (lastinstr.opcode<>a_end_loop)) or
  482. ((cblock.blockstart.opcode=a_if) and (lastinstr.opcode<>a_end_if)) or
  483. ((cblock.blockstart.opcode=a_try) and (lastinstr.opcode<>a_end_try)) then
  484. Message1(parser_f_unsupported_feature,'incompatible nesting level');
  485. cblock.free;
  486. end;
  487. else
  488. ;
  489. end;
  490. end;
  491. ait_label:
  492. begin
  493. lbl:=tai_label(hp);
  494. lbl.labsym.nestingdepth:=-1;
  495. nextinstr:=FindNextInstruction(hp);
  496. if assigned(nextinstr) and (nextinstr.opcode in [a_end_block,a_end_try,a_end_if]) then
  497. lbl.labsym.nestingdepth:=cur_nesting_depth
  498. else if assigned(lastinstr) and (lastinstr.opcode=a_loop) then
  499. lbl.labsym.nestingdepth:=cur_nesting_depth
  500. else if assigned(lastinstr) and (lastinstr.opcode in [a_end_block,a_end_try,a_end_if]) then
  501. lbl.labsym.nestingdepth:=cur_nesting_depth+1
  502. else if assigned(nextinstr) and (nextinstr.opcode=a_loop) then
  503. lbl.labsym.nestingdepth:=cur_nesting_depth+1;
  504. end;
  505. else
  506. ;
  507. end;
  508. hp:=tai(hp.Next);
  509. end;
  510. if cur_nesting_depth<>0 then
  511. Message1(parser_f_unsupported_feature,'unbalanced nesting level');
  512. blockstack.free;
  513. end;
  514. function resolve_labels_pass2(asmlist: TAsmList): Boolean;
  515. var
  516. hp: tai;
  517. instr: taicpu;
  518. hlabel: tasmsymbol;
  519. cur_nesting_depth: longint;
  520. begin
  521. Result:=true;
  522. cur_nesting_depth:=0;
  523. hp:=tai(asmlist.first);
  524. while assigned(hp) do
  525. begin
  526. if hp.typ=ait_instruction then
  527. begin
  528. instr:=taicpu(hp);
  529. case instr.opcode of
  530. a_block,
  531. a_loop,
  532. a_if,
  533. a_try:
  534. inc(cur_nesting_depth);
  535. a_end_block,
  536. a_end_loop,
  537. a_end_if,
  538. a_end_try:
  539. begin
  540. dec(cur_nesting_depth);
  541. if cur_nesting_depth<0 then
  542. Message1(parser_f_unsupported_feature,'negative nesting level');
  543. end;
  544. a_br,
  545. a_br_if:
  546. begin
  547. if instr.ops<>1 then
  548. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong operand count');
  549. if instr.oper[0]^.typ=top_ref then
  550. begin
  551. if not assigned(instr.oper[0]^.ref^.symbol) then
  552. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong ref operand');
  553. if (instr.oper[0]^.ref^.base<>NR_NO) or
  554. (instr.oper[0]^.ref^.index<>NR_NO) or
  555. (instr.oper[0]^.ref^.offset<>0) then
  556. Message1(parser_f_unsupported_feature,'a_br or a_br_if with wrong ref type');
  557. if (instr.oper[0]^.ref^.symbol.nestingdepth<>-1) and
  558. (cur_nesting_depth>=instr.oper[0]^.ref^.symbol.nestingdepth) then
  559. instr.loadconst(0,cur_nesting_depth-instr.oper[0]^.ref^.symbol.nestingdepth)
  560. else
  561. begin
  562. result:=false;
  563. hlabel:=tasmsymbol(instr.oper[0]^.ref^.symbol);
  564. asmlist.insertafter(tai_comment.create(strpnew('Unable to find destination of label '+hlabel.name)),hp);
  565. end;
  566. end;
  567. end;
  568. else
  569. ;
  570. end;
  571. end;
  572. hp:=tai(hp.Next);
  573. end;
  574. if cur_nesting_depth<>0 then
  575. Message1(parser_f_unsupported_feature,'unbalanced nesting level');
  576. end;
  577. function resolve_labels_simple(asmlist: TAsmList): Boolean;
  578. begin
  579. if not assigned(asmlist) then
  580. exit(true);
  581. resolve_labels_pass1(asmlist);
  582. result:=resolve_labels_pass2(asmlist);
  583. end;
  584. procedure resolve_labels_via_state_machine(asmlist: TAsmList);
  585. var
  586. blocks: TFPHashObjectList;
  587. curr_block, tmplist: TAsmList;
  588. hp, hpnext: tai;
  589. block_nr, machine_state, target_block_index: Integer;
  590. state_machine_loop_start_label, state_machine_exit: TAsmLabel;
  591. begin
  592. blocks:=TFPHashObjectList.Create;
  593. curr_block:=TAsmList.Create;
  594. blocks.Add('.start',curr_block);
  595. repeat
  596. hp:=tai(asmlist.First);
  597. if assigned(hp) then
  598. begin
  599. asmlist.Remove(hp);
  600. if hp.typ=ait_label then
  601. begin
  602. curr_block:=TAsmList.Create;
  603. blocks.Add(tai_label(hp).labsym.Name,curr_block);
  604. end;
  605. curr_block.Concat(hp);
  606. end;
  607. until not assigned(hp);
  608. { asmlist is now empty }
  609. asmlist.Concat(tai_comment.Create(strpnew('labels resolved via state machine')));
  610. machine_state:=AllocWasmLocal(wbt_i32);
  611. asmlist.Concat(tai_comment.Create(strpnew('machine state is in local '+tostr(machine_state))));
  612. asmlist.Concat(taicpu.op_const(a_i32_const,0));
  613. asmlist.Concat(taicpu.op_const(a_local_set,machine_state));
  614. asmlist.Concat(taicpu.op_none(a_block));
  615. asmlist.Concat(taicpu.op_none(a_loop));
  616. current_asmdata.getjumplabel(state_machine_loop_start_label);
  617. asmlist.concat(tai_label.create(state_machine_loop_start_label));
  618. current_asmdata.getjumplabel(state_machine_exit);
  619. for block_nr:=0 to blocks.Count-1 do
  620. asmlist.Concat(taicpu.op_none(a_block));
  621. for block_nr:=0 to blocks.Count-1 do
  622. begin
  623. { TODO: this sequence can be replaced with a single br_table instruction }
  624. asmlist.Concat(taicpu.op_const(a_local_get,machine_state));
  625. asmlist.Concat(taicpu.op_const(a_i32_const,block_nr));
  626. asmlist.Concat(taicpu.op_none(a_i32_eq));
  627. asmlist.Concat(taicpu.op_const(a_br_if,block_nr));
  628. end;
  629. asmlist.Concat(taicpu.op_none(a_unreachable));
  630. tmplist:=TAsmList.Create;
  631. for block_nr:=0 to blocks.Count-1 do
  632. begin
  633. asmlist.Concat(taicpu.op_none(a_end_block));
  634. asmlist.Concat(tai_comment.Create(strpnew('block '+tostr(block_nr)+' for label '+blocks.NameOfIndex(block_nr))));
  635. curr_block:=TAsmList(blocks[block_nr]);
  636. hp:=tai(curr_block.First);
  637. while assigned(hp) do
  638. begin
  639. hpnext:=tai(hp.next);
  640. if (hp.typ=ait_instruction) and (taicpu(hp).opcode in [a_br,a_br_if]) and
  641. (taicpu(hp).ops=1) and
  642. (taicpu(hp).oper[0]^.typ=top_ref) and
  643. assigned(taicpu(hp).oper[0]^.ref^.symbol) then
  644. begin
  645. target_block_index:=blocks.FindIndexOf(taicpu(hp).oper[0]^.ref^.symbol.Name);
  646. curr_block.InsertBefore(tai_comment.Create(strpnew(
  647. 'branch '+gas_op2str[taicpu(hp).opcode]+
  648. ' '+taicpu(hp).oper[0]^.ref^.symbol.Name+
  649. ' target_block_index='+tostr(target_block_index))),hp);
  650. if target_block_index<>-1 then
  651. begin
  652. tmplist.Clear;
  653. if taicpu(hp).opcode=a_br_if then
  654. tmplist.Concat(taicpu.op_none(a_if));
  655. tmplist.Concat(taicpu.op_const(a_i32_const,target_block_index));
  656. tmplist.Concat(taicpu.op_const(a_local_set,machine_state));
  657. tmplist.Concat(taicpu.op_sym(a_br,state_machine_loop_start_label));
  658. if taicpu(hp).opcode=a_br_if then
  659. tmplist.Concat(taicpu.op_none(a_end_if));
  660. curr_block.insertListAfter(hp,tmplist);
  661. curr_block.Remove(hp);
  662. end;
  663. end;
  664. hp:=hpnext;
  665. end;
  666. if block_nr<(blocks.Count-1) then
  667. begin
  668. curr_block.Concat(taicpu.op_const(a_i32_const,block_nr+1));
  669. curr_block.Concat(taicpu.op_const(a_local_set,machine_state));
  670. curr_block.Concat(taicpu.op_sym(a_br,state_machine_loop_start_label));
  671. end
  672. else
  673. curr_block.Concat(taicpu.op_sym(a_br,state_machine_exit));
  674. asmlist.concatList(curr_block);
  675. end;
  676. tmplist.Free;
  677. asmlist.Concat(taicpu.op_none(a_end_loop));
  678. asmlist.Concat(taicpu.op_none(a_end_block));
  679. asmlist.concat(tai_label.create(state_machine_exit));
  680. end;
  681. procedure filter_start_exit_code(asmlist: TAsmList; out entry_code, proc_body, exit_code: TAsmList);
  682. var
  683. hp, hpnext, hpprev: tai;
  684. begin
  685. entry_code:=TAsmList.Create;
  686. proc_body:=TAsmList.Create;
  687. exit_code:=TAsmList.Create;
  688. repeat
  689. hp:=tai(asmlist.First);
  690. if assigned(hp) then
  691. begin
  692. hpnext:=tai(hp.next);
  693. if (hp.typ=ait_instruction) and (taicpu(hp).opcode=a_block) then
  694. break;
  695. asmlist.Remove(hp);
  696. entry_code.Concat(hp);
  697. hp:=hpnext;
  698. end;
  699. until not assigned(hp);
  700. repeat
  701. hp:=tai(asmlist.Last);
  702. if assigned(hp) then
  703. begin
  704. hpprev:=tai(hp.Previous);
  705. if (hp.typ=ait_instruction) and (taicpu(hp).opcode=a_end_block) then
  706. break;
  707. asmlist.Remove(hp);
  708. exit_code.Insert(hp);
  709. hp:=hpprev;
  710. end;
  711. until not assigned(hp);
  712. proc_body.insertList(asmlist);
  713. end;
  714. procedure resolve_labels_of_asmlist_with_try_blocks_recursive(asmlist: TAsmList);
  715. var
  716. hp: tai;
  717. i: Integer;
  718. begin
  719. if not assigned(asmlist) then
  720. exit;
  721. hp:=tai(asmlist.First);
  722. while assigned(hp) do
  723. begin
  724. if hp.typ=ait_wasm_structured_instruction then
  725. begin
  726. if not (taicpu_wasm_structured_instruction(hp).wstyp in [aitws_try_catch,aitws_try_delegate]) then
  727. internalerror(2023102201);
  728. resolve_labels_of_asmlist_with_try_blocks_recursive(tai_wasmstruc_try(hp).try_asmlist);
  729. if taicpu_wasm_structured_instruction(hp).wstyp=aitws_try_catch then
  730. with tai_wasmstruc_try_catch(hp) do
  731. begin
  732. for i:=low(catch_list) to high(catch_list) do
  733. resolve_labels_of_asmlist_with_try_blocks_recursive(catch_list[i].asmlist);
  734. resolve_labels_of_asmlist_with_try_blocks_recursive(catch_all_asmlist);
  735. end
  736. else if taicpu_wasm_structured_instruction(hp).wstyp=aitws_try_delegate then
  737. {nothing}
  738. else
  739. internalerror(2023102202);
  740. end;
  741. hp:=tai(hp.next);
  742. end;
  743. resolve_labels_via_state_machine(asmlist);
  744. end;
  745. procedure resolve_labels_complex(var asmlist: TAsmList);
  746. var
  747. entry_code, proc_body, exit_code: TAsmList;
  748. begin
  749. filter_start_exit_code(asmlist,entry_code,proc_body,exit_code);
  750. asmlist.Free;
  751. asmlist:=proc_body;
  752. proc_body:=nil;
  753. wasm_convert_to_structured_asmlist(asmlist);
  754. map_structured_asmlist(asmlist,@ConvertBranchTargetNumbersToLabels);
  755. map_structured_asmlist(asmlist,@ConvertIfToBrIf);
  756. map_structured_asmlist(asmlist,@ConvertLoopToBr);
  757. wasm_convert_to_flat_asmlist(asmlist);
  758. map_structured_asmlist(asmlist,@StripBlockInstructions);
  759. wasm_convert_to_structured_asmlist(asmlist);
  760. resolve_labels_of_asmlist_with_try_blocks_recursive(asmlist);
  761. wasm_convert_to_flat_asmlist(asmlist);
  762. asmlist.insertList(entry_code);
  763. entry_code.free;
  764. asmlist.concatList(exit_code);
  765. exit_code.free;
  766. if not resolve_labels_simple(asmlist) then
  767. internalerror(2023102101);
  768. end;
  769. function prepare_locals: TAsmList;
  770. var
  771. local: tai_local;
  772. first: Boolean;
  773. l : TWasmLocal;
  774. begin
  775. result:=TAsmList.create;
  776. local:=nil;
  777. first:=true;
  778. l:=ttgwasm(tg).localvars.first;
  779. FFirstFreeLocal:=Length(findfirst_tai_functype(aktproccode).functype.params);
  780. while Assigned(l) do
  781. begin
  782. local:=tai_local.create(l.typ);
  783. local.first:=first;
  784. first:=false;
  785. result.Concat(local);
  786. l:=l.nextseq;
  787. Inc(FFirstFreeLocal);
  788. end;
  789. end;
  790. procedure add_extra_allocated_locals(localslist: TAsmList);
  791. var
  792. t: TWasmBasicType;
  793. begin
  794. for t in FAllocatedLocals do
  795. localslist.Concat(tai_local.create(t));
  796. end;
  797. procedure insert_localslist(destlist,localslist: TAsmList);
  798. begin
  799. if assigned(localslist) then
  800. begin
  801. tai_local(localslist.Last).last:=true;
  802. destlist.insertListAfter(findfirst_tai_functype(destlist),localslist);
  803. end;
  804. end;
  805. procedure check_goto_br_instructions(list: TAsmList; out HasGotoBrInstructions: boolean);
  806. var
  807. hp: tai;
  808. begin
  809. HasGotoBrInstructions:=False;
  810. hp:=tai(list.first);
  811. while assigned(hp) do
  812. begin
  813. if (hp.typ=ait_instruction) and (taicpu(hp).is_br_generated_by_goto) then
  814. begin
  815. HasGotoBrInstructions:=True;
  816. if (taicpu(hp).opcode<>a_br) or
  817. (taicpu(hp).ops<>1) or
  818. (taicpu(hp).oper[0]^.typ<>top_ref) or
  819. (taicpu(hp).oper[0]^.ref^.offset<>0) or
  820. (taicpu(hp).oper[0]^.ref^.base<>NR_NO) or
  821. (taicpu(hp).oper[0]^.ref^.index<>NR_NO) or
  822. (taicpu(hp).oper[0]^.ref^.symbol=nil) then
  823. internalerror(2023102203);
  824. if not is_goto_target(taicpu(hp).oper[0]^.ref^.symbol) then
  825. internalerror(2023102204);
  826. end;
  827. hp:=tai(hp.next);
  828. end;
  829. end;
  830. var
  831. localslist: TAsmList;
  832. labels_resolved, has_goto: Boolean;
  833. begin
  834. check_goto_br_instructions(aktproccode,has_goto);
  835. localslist:=prepare_locals;
  836. replace_local_frame_pointer(aktproccode);
  837. labels_resolved:=false;
  838. if not has_goto then
  839. { TODO: make resolve_labels_simple handle goto labels correctly }
  840. labels_resolved:=resolve_labels_simple(aktproccode);
  841. {$ifndef DEBUG_WASM_GOTO}
  842. if not labels_resolved then
  843. {$endif DEBUG_WASM_GOTO}
  844. resolve_labels_complex(aktproccode);
  845. add_extra_allocated_locals(localslist);
  846. insert_localslist(aktproccode,localslist);
  847. localslist.Free;
  848. inherited postprocess_code;
  849. end;
  850. procedure tcpuprocinfo.set_first_temp_offset;
  851. var
  852. sz : integer;
  853. i : integer;
  854. sym: tsym;
  855. begin
  856. {
  857. Stackframe layout:
  858. sp:
  859. <incoming parameters>
  860. sp+first_temp_offset:
  861. <locals>
  862. <temp>
  863. }
  864. procdef.init_paraloc_info(calleeside);
  865. sz := procdef.calleeargareasize;
  866. tg.setfirsttemp(sz);
  867. end;
  868. procedure tcpuprocinfo.add_goto_target(l: tasmlabel);
  869. begin
  870. FGotoTargets.Add(l.Name,l);
  871. end;
  872. function tcpuprocinfo.is_goto_target(l: tasmsymbol): Boolean;
  873. begin
  874. result:=FGotoTargets.FindIndexOf(l.Name)<>-1;
  875. end;
  876. initialization
  877. cprocinfo:=tcpuprocinfo;
  878. end.