agjasmin.pas 43 KB

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