cpupi.pas 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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);
  806. var
  807. hp: tai;
  808. begin
  809. hp:=tai(list.first);
  810. while assigned(hp) do
  811. begin
  812. if (hp.typ=ait_instruction) and (taicpu(hp).is_br_generated_by_goto) then
  813. begin
  814. if (taicpu(hp).opcode<>a_br) or
  815. (taicpu(hp).ops<>1) or
  816. (taicpu(hp).oper[0]^.typ<>top_ref) or
  817. (taicpu(hp).oper[0]^.ref^.offset<>0) or
  818. (taicpu(hp).oper[0]^.ref^.base<>NR_NO) or
  819. (taicpu(hp).oper[0]^.ref^.index<>NR_NO) or
  820. (taicpu(hp).oper[0]^.ref^.symbol=nil) then
  821. internalerror(2023102203);
  822. if not is_goto_target(taicpu(hp).oper[0]^.ref^.symbol) then
  823. internalerror(2023102204);
  824. end;
  825. hp:=tai(hp.next);
  826. end;
  827. end;
  828. var
  829. localslist: TAsmList;
  830. labels_resolved: Boolean;
  831. begin
  832. check_goto_br_instructions(aktproccode);
  833. localslist:=prepare_locals;
  834. replace_local_frame_pointer(aktproccode);
  835. labels_resolved:=resolve_labels_simple(aktproccode);
  836. {$ifndef DEBUG_WASM_GOTO}
  837. if not labels_resolved then
  838. {$endif DEBUG_WASM_GOTO}
  839. resolve_labels_complex(aktproccode);
  840. add_extra_allocated_locals(localslist);
  841. insert_localslist(aktproccode,localslist);
  842. localslist.Free;
  843. inherited postprocess_code;
  844. end;
  845. procedure tcpuprocinfo.set_first_temp_offset;
  846. var
  847. sz : integer;
  848. i : integer;
  849. sym: tsym;
  850. begin
  851. {
  852. Stackframe layout:
  853. sp:
  854. <incoming parameters>
  855. sp+first_temp_offset:
  856. <locals>
  857. <temp>
  858. }
  859. procdef.init_paraloc_info(calleeside);
  860. sz := procdef.calleeargareasize;
  861. tg.setfirsttemp(sz);
  862. end;
  863. procedure tcpuprocinfo.add_goto_target(l: tasmlabel);
  864. begin
  865. FGotoTargets.Add(l.Name,l);
  866. end;
  867. function tcpuprocinfo.is_goto_target(l: tasmsymbol): Boolean;
  868. begin
  869. result:=FGotoTargets.FindIndexOf(l.Name)<>-1;
  870. end;
  871. initialization
  872. cprocinfo:=tcpuprocinfo;
  873. end.