agjasmin.pas 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. {
  2. Copyright (c) 1998-2010 by the Free Pascal team
  3. This unit implements the Jasmin assembler writer
  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 for writing Jasmin assembler (JVM bytecode) output.
  18. }
  19. unit agjasmin;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. cclasses,
  24. globtype,globals,
  25. symconst,symbase,symdef,symsym,
  26. aasmbase,aasmtai,aasmdata,aasmcpu,
  27. assemble;
  28. type
  29. TJasminInstrWriter = class;
  30. {# This is a derived class which is used to write
  31. Jasmin-styled assembler.
  32. }
  33. { TJasminAssembler }
  34. TJasminAssembler=class(texternalassembler)
  35. protected
  36. jasminjar: tcmdstr;
  37. asmfiles: TCmdStrList;
  38. procedure WriteExtraHeader(obj: tobjectdef);
  39. procedure WriteInstruction(hp: tai);
  40. procedure NewAsmFileForObjectDef(obj: tobjectdef);
  41. function VisibilityToStr(vis: tvisibility): string;
  42. function MethodDefinition(pd: tprocdef): string;
  43. function ConstValue(csym: tconstsym): ansistring;
  44. function ConstAssignmentValue(csym: tconstsym): ansistring;
  45. function ConstDefinition(sym: tconstsym): string;
  46. function FieldDefinition(sym: tabstractvarsym): string;
  47. function InnerObjDef(obj: tobjectdef): string;
  48. procedure WriteProcDef(pd: tprocdef);
  49. procedure WriteFieldSym(sym: tabstractvarsym);
  50. procedure WriteConstSym(sym: tconstsym);
  51. procedure WriteSymtableVarSyms(st: TSymtable);
  52. procedure WriteSymtableProcdefs(st: TSymtable);
  53. procedure WriteSymtableObjectDefs(st: TSymtable);
  54. public
  55. constructor Create(smart: boolean); override;
  56. function MakeCmdLine: TCmdStr;override;
  57. procedure WriteTree(p:TAsmList);override;
  58. procedure WriteAsmList;override;
  59. destructor destroy; override;
  60. protected
  61. InstrWriter: TJasminInstrWriter;
  62. end;
  63. {# This is the base class for writing instructions.
  64. The WriteInstruction() method must be overridden
  65. to write a single instruction to the assembler
  66. file.
  67. }
  68. { TJasminInstrWriter }
  69. TJasminInstrWriter = class
  70. constructor create(_owner: TJasminAssembler);
  71. procedure WriteInstruction(hp : tai); virtual;
  72. protected
  73. owner: TJasminAssembler;
  74. end;
  75. implementation
  76. uses
  77. SysUtils,
  78. cutils,cfileutl,systems,script,
  79. fmodule,finput,verbose,
  80. symtype,symtable,jvmdef,
  81. itcpujas,cpubase,cpuinfo,cgutils,
  82. widestr
  83. ;
  84. const
  85. line_length = 70;
  86. type
  87. t64bitarray = array[0..7] of byte;
  88. t32bitarray = array[0..3] of byte;
  89. {****************************************************************************}
  90. { Support routines }
  91. {****************************************************************************}
  92. function fixline(s:string):string;
  93. {
  94. return s with all leading and ending spaces and tabs removed
  95. }
  96. var
  97. i,j,k : integer;
  98. begin
  99. i:=length(s);
  100. while (i>0) and (s[i] in [#9,' ']) do
  101. dec(i);
  102. j:=1;
  103. while (j<i) and (s[j] in [#9,' ']) do
  104. inc(j);
  105. for k:=j to i do
  106. if s[k] in [#0..#31,#127..#255] then
  107. s[k]:='.';
  108. fixline:=Copy(s,j,i-j+1);
  109. end;
  110. function constastr(p: pchar; len: longint): ansistring;
  111. var
  112. i,runstart,runlen: longint;
  113. procedure flush;
  114. begin
  115. if runlen>0 then
  116. begin
  117. setlength(result,length(result)+runlen);
  118. move(p[runstart],result[length(result)-runlen+1],runlen);
  119. runlen:=0;
  120. end;
  121. end;
  122. begin
  123. result:='"';
  124. runlen:=0;
  125. runstart:=0;
  126. for i:=0 to len-1 do
  127. begin
  128. { escape control codes }
  129. case p[i] of
  130. { LF and CR must be escaped specially, because \uXXXX parsing
  131. happens in the pre-processor, so it's the same as actually
  132. inserting a newline in the middle of a string constant }
  133. #10:
  134. begin
  135. flush;
  136. result:=result+'\n';
  137. end;
  138. #13:
  139. begin
  140. flush;
  141. result:=result+'\r';
  142. end;
  143. '"','\':
  144. begin
  145. flush;
  146. result:=result+'\'+p[i];
  147. end
  148. else if p[i]<#32 then
  149. begin
  150. flush;
  151. result:=result+'\u'+hexstr(ord(p[i]),4);
  152. end
  153. else if p[i]<#127 then
  154. begin
  155. if runlen=0 then
  156. runstart:=i;
  157. inc(runlen);
  158. end
  159. else
  160. // since Jasmin expects an UTF-16 string, we can't safely
  161. // have high ASCII characters since they'll be
  162. // re-interpreted as utf-16 anyway
  163. internalerror(2010122808);
  164. end;
  165. end;
  166. flush;
  167. result:=result+'"';
  168. end;
  169. function constwstr(w: pcompilerwidechar; len: longint): ansistring;
  170. var
  171. i: longint;
  172. begin
  173. result:='"';
  174. for i:=0 to len-1 do
  175. begin
  176. { escape control codes }
  177. case w[i] of
  178. 10:
  179. result:=result+'\n';
  180. 13:
  181. result:=result+'\r';
  182. ord('"'),ord('\'):
  183. result:=result+'\'+chr(w[i]);
  184. else if (w[i]<32) or
  185. (w[i]>127) then
  186. result:=result+'\u'+hexstr(w[i],4)
  187. else
  188. result:=result+char(w[i]);
  189. end;
  190. end;
  191. result:=result+'"';
  192. end;
  193. function constsingle(s: single): string;
  194. begin
  195. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  196. end;
  197. function constdouble(d: double): string;
  198. begin
  199. // force interpretation as double (since we write it out as an
  200. // integer, we never have to swap the endianess). We have to
  201. // include the sign separately because of the way Java parses
  202. // hex numbers (0x8000000000000000 is not a valid long)
  203. result:=hexstr(abs(int64(t64bitarray(d))),16);
  204. if int64(t64bitarray(d))<0 then
  205. result:='-'+result;
  206. result:='0dx'+result;
  207. end;
  208. {****************************************************************************}
  209. { Jasmin Assembler writer }
  210. {****************************************************************************}
  211. destructor TJasminAssembler.Destroy;
  212. begin
  213. InstrWriter.free;
  214. asmfiles.free;
  215. inherited destroy;
  216. end;
  217. procedure TJasminAssembler.WriteTree(p:TAsmList);
  218. var
  219. ch : char;
  220. hp : tai;
  221. hp1 : tailineinfo;
  222. s : string;
  223. i,pos : longint;
  224. InlineLevel : longint;
  225. do_line : boolean;
  226. begin
  227. if not assigned(p) then
  228. exit;
  229. InlineLevel:=0;
  230. { lineinfo is only needed for al_procedures (PFV) }
  231. do_line:=(cs_asm_source in current_settings.globalswitches);
  232. hp:=tai(p.first);
  233. while assigned(hp) do
  234. begin
  235. prefetch(pointer(hp.next)^);
  236. if not(hp.typ in SkipLineInfo) then
  237. begin
  238. hp1 := hp as tailineinfo;
  239. current_filepos:=hp1.fileinfo;
  240. { no line info for inlined code }
  241. if do_line and (inlinelevel=0) then
  242. begin
  243. { load infile }
  244. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  245. begin
  246. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  247. if assigned(infile) then
  248. begin
  249. { open only if needed !! }
  250. if (cs_asm_source in current_settings.globalswitches) then
  251. infile.open;
  252. end;
  253. { avoid unnecessary reopens of the same file !! }
  254. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  255. { be sure to change line !! }
  256. lastfileinfo.line:=-1;
  257. end;
  258. { write source }
  259. if (cs_asm_source in current_settings.globalswitches) and
  260. assigned(infile) then
  261. begin
  262. if (infile<>lastinfile) then
  263. begin
  264. AsmWriteLn(target_asm.comment+'['+infile.name^+']');
  265. if assigned(lastinfile) then
  266. lastinfile.close;
  267. end;
  268. if (hp1.fileinfo.line<>lastfileinfo.line) and
  269. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  270. begin
  271. if (hp1.fileinfo.line<>0) and
  272. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  273. AsmWriteLn(target_asm.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  274. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  275. { set it to a negative value !
  276. to make that is has been read already !! PM }
  277. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  278. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  279. end;
  280. end;
  281. lastfileinfo:=hp1.fileinfo;
  282. lastinfile:=infile;
  283. end;
  284. end;
  285. case hp.typ of
  286. ait_comment :
  287. Begin
  288. AsmWrite(target_asm.comment);
  289. AsmWritePChar(tai_comment(hp).str);
  290. AsmLn;
  291. End;
  292. ait_regalloc :
  293. begin
  294. if (cs_asm_regalloc in current_settings.globalswitches) then
  295. begin
  296. AsmWrite(#9+target_asm.comment+'Register ');
  297. repeat
  298. AsmWrite(std_regname(Tai_regalloc(hp).reg));
  299. if (hp.next=nil) or
  300. (tai(hp.next).typ<>ait_regalloc) or
  301. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  302. break;
  303. hp:=tai(hp.next);
  304. AsmWrite(',');
  305. until false;
  306. AsmWrite(' ');
  307. AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  308. end;
  309. end;
  310. ait_tempalloc :
  311. begin
  312. if (cs_asm_tempalloc in current_settings.globalswitches) then
  313. begin
  314. {$ifdef EXTDEBUG}
  315. if assigned(tai_tempalloc(hp).problem) then
  316. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  317. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  318. else
  319. {$endif EXTDEBUG}
  320. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  321. tostr(tai_tempalloc(hp).tempsize)+' '+tempallocstr[tai_tempalloc(hp).allocation]);
  322. end;
  323. end;
  324. ait_align :
  325. begin
  326. end;
  327. ait_section :
  328. begin
  329. end;
  330. ait_datablock :
  331. begin
  332. internalerror(2010122701);
  333. end;
  334. ait_const:
  335. begin
  336. AsmWriteln('constant');
  337. // internalerror(2010122702);
  338. end;
  339. ait_real_64bit :
  340. begin
  341. internalerror(2010122703);
  342. end;
  343. ait_real_32bit :
  344. begin
  345. internalerror(2010122703);
  346. end;
  347. ait_comp_64bit :
  348. begin
  349. internalerror(2010122704);
  350. end;
  351. ait_string :
  352. begin
  353. pos:=0;
  354. for i:=1 to tai_string(hp).len do
  355. begin
  356. if pos=0 then
  357. begin
  358. AsmWrite(#9'strconst: '#9'"');
  359. pos:=20;
  360. end;
  361. ch:=tai_string(hp).str[i-1];
  362. case ch of
  363. #0, {This can't be done by range, because a bug in FPC}
  364. #1..#31,
  365. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  366. '"' : s:='\"';
  367. '\' : s:='\\';
  368. else
  369. s:=ch;
  370. end;
  371. AsmWrite(s);
  372. inc(pos,length(s));
  373. if (pos>line_length) or (i=tai_string(hp).len) then
  374. begin
  375. AsmWriteLn('"');
  376. pos:=0;
  377. end;
  378. end;
  379. end;
  380. ait_label :
  381. begin
  382. if (tai_label(hp).labsym.is_used) then
  383. begin
  384. AsmWrite(tai_label(hp).labsym.name);
  385. AsmWriteLn(':');
  386. end;
  387. end;
  388. ait_symbol :
  389. begin
  390. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  391. begin
  392. end
  393. else
  394. begin
  395. AsmWrite('data symbol: ');
  396. AsmWriteln(tai_symbol(hp).sym.name);
  397. // internalerror(2010122706);
  398. end;
  399. end;
  400. ait_symbol_end :
  401. begin
  402. end;
  403. ait_instruction :
  404. begin
  405. WriteInstruction(hp);
  406. end;
  407. ait_force_line,
  408. ait_function_name : ;
  409. ait_cutobject :
  410. begin
  411. end;
  412. ait_marker :
  413. if tai_marker(hp).kind=mark_NoLineInfoStart then
  414. inc(InlineLevel)
  415. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  416. dec(InlineLevel);
  417. ait_directive :
  418. begin
  419. AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  420. if assigned(tai_directive(hp).name) then
  421. AsmWrite(tai_directive(hp).name^);
  422. AsmLn;
  423. end;
  424. ait_jvar:
  425. begin
  426. AsmWrite('.var ');
  427. AsmWrite(tostr(tai_jvar(hp).stackslot));
  428. AsmWrite(' is ');
  429. AsmWrite(tai_jvar(hp).desc^);
  430. AsmWrite(' from ');
  431. AsmWrite(tai_jvar(hp).startlab.name);
  432. AsmWrite(' to ');
  433. AsmWriteLn(tai_jvar(hp).stoplab.name);
  434. end;
  435. ait_jcatch:
  436. begin
  437. AsmWrite('.catch ');
  438. AsmWrite(tai_jcatch(hp).name^);
  439. AsmWrite(' from ');
  440. AsmWrite(tai_jcatch(hp).startlab.name);
  441. AsmWrite(' to ');
  442. AsmWrite(tai_jcatch(hp).stoplab.name);
  443. AsmWrite(' using ');
  444. AsmWriteLn(tai_jcatch(hp).handlerlab.name);
  445. end;
  446. else
  447. internalerror(2010122707);
  448. end;
  449. hp:=tai(hp.next);
  450. end;
  451. end;
  452. procedure TJasminAssembler.WriteExtraHeader(obj: tobjectdef);
  453. var
  454. superclass,
  455. intf: tobjectdef;
  456. n: string;
  457. i: longint;
  458. begin
  459. { JVM 1.5+ }
  460. AsmWriteLn('.bytecode 49.0');
  461. // include files are not support by Java, and the directory of the main
  462. // source file must not be specified
  463. if assigned(current_module.mainsource) then
  464. n:=ExtractFileName(current_module.mainsource^)
  465. else
  466. n:=InputFileName;
  467. AsmWriteLn('.source '+ExtractFileName(n));
  468. { class/interface name }
  469. if not assigned(obj) then
  470. begin
  471. { fake class type for unit -> name=unitname and
  472. superclass=java.lang.object }
  473. AsmWriteLn('.class '+current_module.realmodulename^);
  474. AsmWriteLn('.super java/lang/Object');
  475. end
  476. else
  477. begin
  478. case obj.objecttype of
  479. odt_javaclass:
  480. begin
  481. AsmWriteLn('.class '+obj.jvm_full_typename(false));
  482. superclass:=obj.childof;
  483. end;
  484. odt_interfacejava:
  485. begin
  486. AsmWriteLn('.interface abstract '+obj.objextname^);
  487. { interfaces must always specify Java.lang.object as
  488. superclass }
  489. superclass:=java_jlobject;
  490. end
  491. else
  492. internalerror(2011010906);
  493. end;
  494. { superclass }
  495. if assigned(superclass) then
  496. begin
  497. AsmWrite('.super ');
  498. if assigned(superclass.import_lib) then
  499. AsmWrite(superclass.import_lib^+'/');
  500. AsmWriteln(superclass.objextname^);
  501. end;
  502. { implemented interfaces }
  503. if assigned(obj.ImplementedInterfaces) then
  504. begin
  505. for i:=0 to obj.ImplementedInterfaces.count-1 do
  506. begin
  507. intf:=TImplementedInterface(obj.ImplementedInterfaces[i]).IntfDef;
  508. AsmWrite('.implements ');
  509. if assigned(intf.import_lib) then
  510. AsmWrite(intf.import_lib^+'/');
  511. AsmWriteln(intf.objextname^);
  512. end;
  513. end;
  514. { in case of nested class: relation to parent class }
  515. if obj.owner.symtabletype=objectsymtable then
  516. AsmWriteln(InnerObjDef(obj));
  517. { all all nested classes }
  518. for i:=0 to obj.symtable.deflist.count-1 do
  519. if is_java_class_or_interface(tdef(obj.symtable.deflist[i])) then
  520. AsmWriteln(InnerObjDef(tobjectdef(obj.symtable.deflist[i])));
  521. end;
  522. AsmLn;
  523. end;
  524. procedure TJasminAssembler.WriteInstruction(hp: tai);
  525. begin
  526. InstrWriter.WriteInstruction(hp);
  527. end;
  528. function TJasminAssembler.MakeCmdLine: TCmdStr;
  529. const
  530. jasminjarname = 'jasmin.jar';
  531. var
  532. filenames: tcmdstr;
  533. jasminjarfound: boolean;
  534. begin
  535. if jasminjar='' then
  536. begin
  537. jasminjarfound:=false;
  538. if utilsdirectory<>'' then
  539. jasminjarfound:=FindFile(jasminjarname,utilsdirectory,false,jasminjar);
  540. if not jasminjarfound then
  541. jasminjarfound:=FindFileInExeLocations(jasminjarname,false,jasminjar);
  542. if (not jasminjarfound) and not(cs_asm_extern in current_settings.globalswitches) then
  543. begin
  544. Message1(exec_e_assembler_not_found,jasminjarname);
  545. current_settings.globalswitches:=current_settings.globalswitches+[cs_asm_extern];
  546. end;
  547. if jasminjarfound then
  548. Message1(exec_t_using_assembler,jasminjar);
  549. end;
  550. result:=target_asm.asmcmd;
  551. filenames:=maybequoted(ScriptFixFileName(AsmFileName));
  552. while not asmfiles.empty do
  553. filenames:=filenames+' '+asmfiles.GetFirst;
  554. Replace(result,'$ASM',filenames);
  555. if (path<>'') then
  556. Replace(result,'$OBJDIR',maybequoted(ScriptFixFileName(path)))
  557. else
  558. Replace(result,'$OBJDIR','.');
  559. Replace(result,'$JASMINJAR',maybequoted(ScriptFixFileName(jasminjar)));
  560. end;
  561. procedure TJasminAssembler.NewAsmFileForObjectDef(obj: tobjectdef);
  562. begin
  563. if AsmSize<>AsmStartSize then
  564. begin
  565. AsmClose;
  566. asmfiles.Concat(maybequoted(ScriptFixFileName(AsmFileName)));
  567. end
  568. else
  569. AsmClear;
  570. AsmFileName:=obj.jvm_full_typename(false);
  571. AsmFileName:=Path+FixFileName(AsmFileName)+target_info.asmext;
  572. AsmCreate(cut_normal);
  573. end;
  574. function TJasminAssembler.VisibilityToStr(vis: tvisibility): string;
  575. begin
  576. case vis of
  577. vis_hidden,
  578. vis_strictprivate:
  579. result:='private ';
  580. vis_strictprotected:
  581. result:='protected ';
  582. vis_protected,
  583. vis_private:
  584. { pick default visibility = "package" visibility; required because
  585. other classes in the same unit can also access these symbols }
  586. result:='';
  587. vis_public:
  588. result:='public '
  589. else
  590. internalerror(2010122609);
  591. end;
  592. end;
  593. function TJasminAssembler.MethodDefinition(pd: tprocdef): string;
  594. begin
  595. result:=VisibilityToStr(pd.visibility);
  596. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  597. (po_staticmethod in pd.procoptions) then
  598. result:=result+'static ';
  599. if is_javainterface(tdef(pd.owner.defowner)) then
  600. result:=result+'abstract ';
  601. if po_finalmethod in pd.procoptions then
  602. result:=result+'final ';
  603. result:=result+pd.jvmmangledbasename;
  604. end;
  605. function TJasminAssembler.ConstValue(csym: tconstsym): ansistring;
  606. begin
  607. case csym.consttyp of
  608. constord:
  609. { always interpret as signed value, because the JVM does not
  610. support unsigned 64 bit values }
  611. result:=tostr(csym.value.valueord.svalue);
  612. conststring:
  613. result:=constastr(pchar(csym.value.valueptr),csym.value.len);
  614. constreal:
  615. case tfloatdef(csym.constdef).floattype of
  616. s32real:
  617. result:=constsingle(pbestreal(csym.value.valueptr)^);
  618. s64real:
  619. result:=constdouble(pbestreal(csym.value.valueptr)^);
  620. else
  621. internalerror(2011021204);
  622. end;
  623. constset:
  624. result:='TODO: add support for constant sets';
  625. constpointer:
  626. { can only be null, but that's the default value and should not
  627. be written; there's no primitive type that can hold nill }
  628. internalerror(2011021201);
  629. constnil:
  630. internalerror(2011021202);
  631. constresourcestring:
  632. result:='TODO: add support for constant resource strings';
  633. constwstring:
  634. result:=constwstr(pcompilerwidestring(csym.value.valueptr)^.data,pcompilerwidestring(csym.value.valueptr)^.len);
  635. constguid:
  636. result:='TODO: add support for constant guids';
  637. else
  638. internalerror(2011021205);
  639. end;
  640. end;
  641. function TJasminAssembler.ConstAssignmentValue(csym: tconstsym): ansistring;
  642. begin
  643. { nil is the default value -> don't write explicitly }
  644. case csym.consttyp of
  645. constpointer:
  646. begin
  647. if csym.value.valueordptr<>0 then
  648. internalerror(2011021206);
  649. result:='';
  650. end;
  651. constnil:
  652. result:='';
  653. else
  654. result:=' = '+ConstValue(csym)
  655. end;
  656. end;
  657. function TJasminAssembler.ConstDefinition(sym: tconstsym): string;
  658. begin
  659. result:=VisibilityToStr(sym.visibility);
  660. { formal constants are always class-level, not instance-level }
  661. result:=result+'static final ';
  662. result:=result+jvmmangledbasename(sym);
  663. result:=result+ConstAssignmentValue(tconstsym(sym));
  664. end;
  665. function TJasminAssembler.FieldDefinition(sym: tabstractvarsym): string;
  666. var
  667. vissym: tabstractvarsym;
  668. begin
  669. vissym:=sym;
  670. { static field definition -> get original field definition for
  671. visibility }
  672. if (vissym.typ=staticvarsym) and
  673. (vissym.owner.symtabletype=objectsymtable) then
  674. begin
  675. vissym:=tabstractvarsym(search_struct_member(
  676. tobjectdef(vissym.owner.defowner),
  677. internal_static_field_name(vissym.name)));
  678. if not assigned(vissym) or
  679. (vissym.typ<>fieldvarsym) then
  680. internalerror(2011011501);
  681. end;
  682. case vissym.typ of
  683. staticvarsym:
  684. begin
  685. if vissym.owner.symtabletype=globalsymtable then
  686. result:='public '
  687. else
  688. { package visbility }
  689. result:='';
  690. end;
  691. fieldvarsym:
  692. result:=VisibilityToStr(tstoredsym(vissym).visibility);
  693. else
  694. internalerror(2011011204);
  695. end;
  696. if (vissym.owner.symtabletype in [staticsymtable,globalsymtable]) or
  697. (sp_static in vissym.symoptions) then
  698. result:=result+'static ';
  699. result:=result+jvmmangledbasename(sym);
  700. end;
  701. function TJasminAssembler.InnerObjDef(obj: tobjectdef): string;
  702. var
  703. kindname: string;
  704. begin
  705. if obj.owner.defowner.typ<>objectdef then
  706. internalerror(2011021701);
  707. case obj.objecttype of
  708. odt_javaclass:
  709. kindname:='class ';
  710. odt_interfacejava:
  711. kindname:='interface ';
  712. else
  713. internalerror(2011021702);
  714. end;
  715. result:=
  716. '.inner '+
  717. kindname+
  718. VisibilityToStr(obj.typesym.visibility)+
  719. { Nested classes in the Pascal sense are equivalent to "static"
  720. inner classes in Java -- will be changed when support for
  721. Java-style non-static classes is added }
  722. ' static '+
  723. obj.objextname^+
  724. ' inner '+
  725. obj.jvm_full_typename(true)+
  726. ' outer '+
  727. tobjectdef(obj.owner.defowner).jvm_full_typename(true);
  728. end;
  729. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  730. begin
  731. if not assigned(pd.exprasmlist) and
  732. (not is_javainterface(pd.struct) or
  733. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  734. exit;
  735. AsmWrite('.method ');
  736. AsmWriteln(MethodDefinition(pd));
  737. WriteTree(pd.exprasmlist);
  738. AsmWriteln('.end method');
  739. AsmLn;
  740. end;
  741. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  742. begin
  743. { internal static field definition alias -> skip }
  744. if sp_static in sym.symoptions then
  745. exit;
  746. AsmWrite('.field ');
  747. AsmWriteln(FieldDefinition(sym));
  748. end;
  749. procedure TJasminAssembler.WriteConstSym(sym: tconstsym);
  750. begin
  751. AsmWrite('.field ');
  752. AsmWriteln(ConstDefinition(sym));
  753. end;
  754. procedure TJasminAssembler.WriteSymtableVarSyms(st: TSymtable);
  755. var
  756. sym : tsym;
  757. i : longint;
  758. begin
  759. if not assigned(st) then
  760. exit;
  761. for i:=0 to st.SymList.Count-1 do
  762. begin
  763. sym:=tsym(st.SymList[i]);
  764. case sym.typ of
  765. staticvarsym,
  766. fieldvarsym:
  767. begin
  768. WriteFieldSym(tabstractvarsym(sym));
  769. end;
  770. constsym:
  771. begin
  772. WriteConstSym(tconstsym(sym));
  773. end;
  774. end;
  775. end;
  776. end;
  777. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  778. var
  779. i : longint;
  780. def : tdef;
  781. begin
  782. if not assigned(st) then
  783. exit;
  784. for i:=0 to st.DefList.Count-1 do
  785. begin
  786. def:=tdef(st.DefList[i]);
  787. case def.typ of
  788. procdef :
  789. begin
  790. { methods are also in the static/globalsymtable of the unit
  791. -> make sure they are only written for the objectdefs that
  792. own them }
  793. if not(st.symtabletype in [staticsymtable,globalsymtable]) or
  794. (def.owner=st) then
  795. begin
  796. WriteProcDef(tprocdef(def));
  797. if assigned(tprocdef(def).localst) then
  798. WriteSymtableProcdefs(tprocdef(def).localst);
  799. end;
  800. end;
  801. end;
  802. end;
  803. end;
  804. procedure TJasminAssembler.WriteSymtableObjectDefs(st: TSymtable);
  805. var
  806. i : longint;
  807. def : tdef;
  808. obj : tobjectdef;
  809. nestedclasses: tfpobjectlist;
  810. begin
  811. if not assigned(st) then
  812. exit;
  813. nestedclasses:=tfpobjectlist.create(false);
  814. for i:=0 to st.DefList.Count-1 do
  815. begin
  816. def:=tdef(st.DefList[i]);
  817. case def.typ of
  818. objectdef:
  819. if not(oo_is_external in tobjectdef(def).objectoptions) then
  820. nestedclasses.add(def);
  821. end;
  822. end;
  823. for i:=0 to nestedclasses.count-1 do
  824. begin
  825. obj:=tobjectdef(nestedclasses[i]);
  826. NewAsmFileForObjectDef(obj);
  827. WriteExtraHeader(obj);
  828. WriteSymtableVarSyms(obj.symtable);
  829. AsmLn;
  830. WriteSymtableProcDefs(obj.symtable);
  831. WriteSymtableObjectDefs(obj.symtable);
  832. end;
  833. nestedclasses.free;
  834. end;
  835. constructor TJasminAssembler.Create(smart: boolean);
  836. begin
  837. inherited create(smart);
  838. InstrWriter:=TJasminInstrWriter.Create(self);
  839. asmfiles:=TCmdStrList.Create;
  840. end;
  841. procedure TJasminAssembler.WriteAsmList;
  842. begin
  843. {$ifdef EXTDEBUG}
  844. if assigned(current_module.mainsource) then
  845. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource^);
  846. {$endif}
  847. AsmStartSize:=AsmSize;
  848. WriteExtraHeader(nil);
  849. (*
  850. for hal:=low(TasmlistType) to high(TasmlistType) do
  851. begin
  852. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  853. writetree(current_asmdata.asmlists[hal]);
  854. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  855. end;
  856. *)
  857. { print all global variables }
  858. WriteSymtableVarSyms(current_module.globalsymtable);
  859. WriteSymtableVarSyms(current_module.localsymtable);
  860. AsmLn;
  861. { print all global procedures/functions }
  862. WriteSymtableProcdefs(current_module.globalsymtable);
  863. WriteSymtableProcdefs(current_module.localsymtable);
  864. WriteSymtableObjectDefs(current_module.globalsymtable);
  865. WriteSymtableObjectDefs(current_module.localsymtable);
  866. AsmLn;
  867. {$ifdef EXTDEBUG}
  868. if assigned(current_module.mainsource) then
  869. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource^);
  870. {$endif EXTDEBUG}
  871. end;
  872. {****************************************************************************}
  873. { Jasmin Instruction Writer }
  874. {****************************************************************************}
  875. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  876. begin
  877. inherited create;
  878. owner := _owner;
  879. end;
  880. function getreferencestring(var ref : treference) : string;
  881. begin
  882. if (ref.arrayreftype<>art_none) or
  883. (ref.index<>NR_NO) then
  884. internalerror(2010122809);
  885. if assigned(ref.symbol) then
  886. begin
  887. // global symbol or field -> full type and name
  888. // ref.base can be <> NR_NO in case an instance field is loaded.
  889. // This register is not part of this instruction, it will have
  890. // been placed on the stack by the previous one.
  891. if (ref.offset<>0) then
  892. internalerror(2010122811);
  893. result:=ref.symbol.name;
  894. end
  895. else
  896. begin
  897. // local symbol -> stack slot, stored in offset
  898. if ref.base<>NR_STACK_POINTER_REG then
  899. internalerror(2010122810);
  900. result:=tostr(ref.offset);
  901. end;
  902. end;
  903. function getopstr(const o:toper) : ansistring;
  904. var
  905. d: double;
  906. s: single;
  907. begin
  908. case o.typ of
  909. top_reg:
  910. // should have been translated into a memory location by the
  911. // register allocator)
  912. if (cs_no_regalloc in current_settings.globalswitches) then
  913. getopstr:=std_regname(o.reg)
  914. else
  915. internalerror(2010122803);
  916. top_const:
  917. str(o.val,result);
  918. top_ref:
  919. getopstr:=getreferencestring(o.ref^);
  920. top_single:
  921. begin
  922. result:=constsingle(o.sval);
  923. end;
  924. top_double:
  925. begin
  926. result:=constdouble(o.dval);
  927. end;
  928. top_string:
  929. begin
  930. result:=constastr(o.pcval,o.pcvallen);
  931. end;
  932. top_wstring:
  933. begin
  934. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  935. end
  936. else
  937. internalerror(2010122802);
  938. end;
  939. end;
  940. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  941. var
  942. s: ansistring;
  943. i: byte;
  944. sep: string[3];
  945. begin
  946. s:=#9+jas_op2str[taicpu(hp).opcode];
  947. if taicpu(hp).ops<>0 then
  948. begin
  949. sep:=#9;
  950. for i:=0 to taicpu(hp).ops-1 do
  951. begin
  952. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  953. sep:=' ';
  954. end;
  955. end;
  956. owner.AsmWriteLn(s);
  957. end;
  958. {****************************************************************************}
  959. { Jasmin Instruction Writer }
  960. {****************************************************************************}
  961. const
  962. as_jvm_jasmin_info : tasminfo =
  963. (
  964. id : as_jvm_jasmin;
  965. idtxt : 'Jasmin';
  966. asmbin : 'java';
  967. asmcmd : '-jar $JASMINJAR $ASM -d $OBJDIR';
  968. supported_targets : [system_jvm_java32];
  969. flags : [];
  970. labelprefix : 'L';
  971. comment : ' ; ';
  972. );
  973. begin
  974. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  975. end.