agllvmmc.pas 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. {
  2. Copyright (c) 1998-2020 by the Free Pascal team
  3. This unit implements the llvm-mc ("llvm machine code playground")
  4. assembler writer for WebAssembly
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit agllvmmc;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. systems,cgutils,
  23. globtype,globals,
  24. symbase,symdef,symtype,symconst,symcpu,
  25. aasmbase,aasmtai,aasmdata,aasmcpu,
  26. assemble,aggas;
  27. type
  28. { TLLVMMachineCodePlaygroundAssembler }
  29. TLLVMMachineCodePlaygroundAssembler=class(TGNUassembler)
  30. protected
  31. procedure WriteProcDef(pd: tprocdef);
  32. procedure WriteSymtableProcdefs(st: TSymtable);
  33. procedure WriteImports;
  34. function sectionname(atype:TAsmSectiontype;const aname:string;aorder:TAsmSectionOrder):string;override;
  35. public
  36. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  37. procedure WriteAsmList;override;
  38. end;
  39. { TWASM32InstrWriter }
  40. TWASM32InstrWriter = class(TCPUInstrWriter)
  41. procedure WriteInstruction(hp : tai);override;
  42. end;
  43. implementation
  44. uses
  45. cutils,
  46. fmodule,finput,
  47. itcpugas,
  48. cpubase,
  49. hlcgobj,hlcgcpu,
  50. verbose;
  51. { TLLVMMachineCodePlaygroundAssembler }
  52. procedure TLLVMMachineCodePlaygroundAssembler.WriteProcDef(pd: tprocdef);
  53. begin
  54. if not assigned(tcpuprocdef(pd).exprasmlist) and
  55. not(po_abstractmethod in pd.procoptions) and
  56. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  57. exit;
  58. writer.AsmWriteLn(asminfo^.comment+'WriteProcDef('+pd.mangledname+')');
  59. WriteTree(tcpuprocdef(pd).exprasmlist);
  60. writer.AsmWriteLn(asminfo^.comment+'WriteProcDef('+pd.mangledname+') done');
  61. end;
  62. procedure TLLVMMachineCodePlaygroundAssembler.WriteSymtableProcdefs(st: TSymtable);
  63. var
  64. i : longint;
  65. def : tdef;
  66. begin
  67. if not assigned(st) then
  68. exit;
  69. for i:=0 to st.DefList.Count-1 do
  70. begin
  71. def:=tdef(st.DefList[i]);
  72. case def.typ of
  73. procdef :
  74. begin
  75. { methods are also in the static/globalsymtable of the unit
  76. -> make sure they are only written for the objectdefs that
  77. own them }
  78. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  79. (def.owner=st)) and
  80. not(df_generic in def.defoptions) then
  81. begin
  82. WriteProcDef(tprocdef(def));
  83. if assigned(tprocdef(def).localst) then
  84. WriteSymtableProcdefs(tprocdef(def).localst);
  85. end;
  86. end;
  87. else
  88. ;
  89. end;
  90. end;
  91. end;
  92. procedure TLLVMMachineCodePlaygroundAssembler.WriteImports;
  93. var
  94. i : integer;
  95. proc : tprocdef;
  96. list : TAsmList;
  97. begin
  98. for i:=0 to current_module.deflist.Count-1 do
  99. if tdef(current_module.deflist[i]).typ = procdef then
  100. begin
  101. proc := tprocdef(current_module.deflist[i]);
  102. if (po_external in proc.procoptions) and assigned(proc.import_dll) then
  103. begin
  104. //WriteProcDef(proc);
  105. list:=TAsmList.Create;
  106. thlcgwasm(hlcg).g_procdef(list,proc);
  107. WriteTree(list);
  108. list.free;
  109. writer.AsmWrite(#9'.import_module'#9);
  110. writer.AsmWrite(proc.mangledname);
  111. writer.AsmWrite(', ');
  112. writer.AsmWriteLn(proc.import_dll^);
  113. writer.AsmWrite(#9'.import_name'#9);
  114. writer.AsmWrite(proc.mangledname);
  115. writer.AsmWrite(', ');
  116. writer.AsmWriteLn(proc.import_name^);
  117. end;
  118. end;
  119. end;
  120. function TLLVMMachineCodePlaygroundAssembler.sectionname(atype: TAsmSectiontype; const aname: string; aorder: TAsmSectionOrder): string;
  121. begin
  122. if atype=sec_fpc then
  123. atype:=sec_data;
  124. Result:=inherited sectionname(atype, aname, aorder)+',"",@';
  125. end;
  126. constructor TLLVMMachineCodePlaygroundAssembler.CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  127. begin
  128. inherited;
  129. InstrWriter:=TWASM32InstrWriter.create(self);
  130. end;
  131. procedure TLLVMMachineCodePlaygroundAssembler.WriteAsmList;
  132. begin
  133. inherited;
  134. { print all global procedures/functions }
  135. WriteSymtableProcdefs(current_module.globalsymtable);
  136. WriteSymtableProcdefs(current_module.localsymtable);
  137. writer.AsmWriteLn(#9'.globaltype'#9+STACK_POINTER_SYM+', i32');
  138. WriteImports;
  139. end;
  140. { TWASM32InstrWriter }
  141. procedure TWASM32InstrWriter.WriteInstruction(hp: tai);
  142. function getreferencestring(var ref : treference) : ansistring;
  143. begin
  144. if (ref.index<>NR_NO) then
  145. internalerror(2010122809);
  146. if assigned(ref.symbol) then
  147. begin
  148. // global symbol or field -> full type and name
  149. // ref.base can be <> NR_NO in case an instance field is loaded.
  150. // This register is not part of this instruction, it will have
  151. // been placed on the stack by the previous one.
  152. result:=ref.symbol.name;
  153. if ref.offset>0 then
  154. result:=result+'+'+tostr(ref.offset)
  155. else if ref.offset<0 then
  156. result:=result+tostr(ref.offset);
  157. end
  158. else
  159. begin
  160. // local symbol -> stack slot, stored in offset
  161. if ref.base<>NR_STACK_POINTER_REG then
  162. internalerror(2010122810);
  163. result:=tostr(ref.offset);
  164. end;
  165. end;
  166. function constsingle(s: single): ansistring;
  167. begin
  168. // wat2wasm is using strtof() internally
  169. str(s, result); //'0x'+hexstr(longint(t32bitarray(s)),8);
  170. end;
  171. function constdouble(d: double): ansistring;
  172. begin
  173. // force interpretation as double (since we write it out as an
  174. // integer, we never have to swap the endianess). We have to
  175. // include the sign separately because of the way Java parses
  176. // hex numbers (0x8000000000000000 is not a valid long)
  177. //result:=hexstr(abs(int64(t64bitarray(d))),16);
  178. //if int64(t64bitarray(d))<0 then
  179. // result:='-'+result;
  180. //result:='0dx'+result;
  181. str(d, result);
  182. end;
  183. function getopstr(const o:toper) : ansistring;
  184. var
  185. d: double;
  186. s: single;
  187. begin
  188. case o.typ of
  189. top_reg:
  190. // should have been translated into a memory location by the
  191. // register allocator)
  192. if (cs_no_regalloc in current_settings.globalswitches) then
  193. getopstr:=std_regname(o.reg)
  194. else
  195. internalerror(2010122803);
  196. top_const:
  197. str(o.val,result);
  198. top_ref:
  199. getopstr:=getreferencestring(o.ref^);
  200. top_single:
  201. begin
  202. result:=constsingle(o.sval);
  203. end;
  204. top_double:
  205. begin
  206. result:=constdouble(o.dval);
  207. end;
  208. {top_string:
  209. begin
  210. result:=constastr(o.pcval,o.pcvallen);
  211. end;
  212. top_wstring:
  213. begin
  214. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  215. end}
  216. else
  217. internalerror(2010122802);
  218. end;
  219. end;
  220. var
  221. cpu : taicpu;
  222. i : integer;
  223. isprm : boolean;
  224. writer: TExternalAssemblerOutputFile;
  225. begin
  226. writer:=owner.writer;
  227. cpu := taicpu(hp);
  228. writer.AsmWrite(#9#9);
  229. writer.AsmWrite(gas_op2str[cpu.opcode]);
  230. if (cpu.opcode = a_call_indirect) then begin
  231. // special wat2wasm syntax "call_indirect (type x)"
  232. writer.AsmWrite(#9);
  233. isprm := true;
  234. for i:=1 to length(cpu.typecode) do
  235. if cpu.typecode[i]=':' then
  236. isprm:=false
  237. else begin
  238. if isprm then writer.AsmWrite('(param ')
  239. else writer.AsmWrite('(result ');
  240. case cpu.typecode[i] of
  241. 'i': writer.AsmWrite('i32');
  242. 'I': writer.AsmWrite('i64');
  243. 'f': writer.AsmWrite('f32');
  244. 'F': writer.AsmWrite('f64');
  245. end;
  246. writer.AsmWrite(')');
  247. end;
  248. writer.AsmLn;
  249. exit;
  250. end;
  251. if (cpu.opcode = a_if) then
  252. writer.AsmWrite(' (result i32)') //todo: this is a hardcode, but shouldn't
  253. else
  254. cpu := taicpu(hp);
  255. if cpu.ops<>0 then
  256. begin
  257. for i:=0 to cpu.ops-1 do
  258. begin
  259. writer.AsmWrite(#9);
  260. writer.AsmWrite(getopstr(cpu.oper[i]^));
  261. end;
  262. end;
  263. if (cpu.opcode = a_call_indirect) then
  264. // special wat2wasm syntax "call_indirect (type x)"
  265. writer.AsmWrite(')');
  266. writer.AsmLn;
  267. end;
  268. const
  269. as_wasm32_llvm_mc_info : tasminfo =
  270. (
  271. id : as_wasm32_llvm_mc;
  272. idtxt : 'LLVM-MC';
  273. asmbin : 'llvm-mc';
  274. asmcmd : '--assemble --arch=wasm32 --filetype=obj -o $OBJ $EXTRAOPT $ASM';
  275. supported_targets : [system_wasm32_wasm,system_wasm32_wasi];
  276. flags : [];
  277. labelprefix : '.L';
  278. labelmaxlen : -1;
  279. comment : '# ';
  280. dollarsign : '$';
  281. );
  282. initialization
  283. RegisterAssembler(as_wasm32_llvm_mc_info,TLLVMMachineCodePlaygroundAssembler);
  284. end.