agjasmin.pas 42 KB

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