aasmcnst.pas 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. {
  2. Copyright (c) 2014 by Jonas Maebe, member of the Free Pascal development
  3. team
  4. This unit implements typed constant data elements at the assembler level
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit aasmcnst;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cclasses,globtype,constexp,
  23. aasmbase,aasmdata,aasmtai,
  24. symconst,symtype,symdef,symsym;
  25. type
  26. { typed const: integer/floating point/string/pointer/... const along with
  27. tdef info; tck_simple_procvar2proc is to indicate that we mean the
  28. procdef corresponding to the procvar rather than the tmethod-like
  29. struct in case of a complex procvar }
  30. ttypedconstkind = (tck_simple, tck_simple_procvar2proc, tck_array, tck_record);
  31. { the type of the element and its def }
  32. tai_abstracttypedconst = class abstract (tai)
  33. protected
  34. fadetyp: ttypedconstkind;
  35. { the def of this element }
  36. fdef: tdef;
  37. public
  38. constructor create(_adetyp: ttypedconstkind; _def: tdef);
  39. property adetyp: ttypedconstkind read fadetyp;
  40. property def: tdef read fdef;
  41. end;
  42. { a simple data element; the value is stored as a tai }
  43. tai_simpletypedconst = class(tai_abstracttypedconst)
  44. protected
  45. fval: tai;
  46. public
  47. constructor create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  48. property val: tai read fval;
  49. end;
  50. { an aggregate data element (record or array). Values are stored as an
  51. array of tsimpledataelement. }
  52. tai_aggregatetypedconst = class(tai_abstracttypedconst)
  53. public type
  54. { iterator to walk over all individual items in the aggregate }
  55. tadeenumerator = class(tobject)
  56. private
  57. fvalues: tfplist;
  58. fvaluespos: longint;
  59. function getcurrent: tai_abstracttypedconst;
  60. public
  61. constructor create(data: tai_aggregatetypedconst);
  62. function movenext: boolean;
  63. procedure reset;
  64. property current: tai_abstracttypedconst read getcurrent;
  65. end;
  66. protected
  67. fvalues: tfplist;
  68. fisstring: boolean;
  69. { converts the existing data to a single tai_string }
  70. procedure convert_to_string;
  71. procedure add_to_string(strtai: tai_string; othertai: tai);
  72. public
  73. constructor create(_adetyp: ttypedconstkind; _fdef: tdef);
  74. function getenumerator: tadeenumerator;
  75. procedure addvalue(val: tai_abstracttypedconst);
  76. procedure finish;
  77. destructor destroy; override;
  78. end;
  79. { Warning: never directly create a ttai_typedconstbuilder instance,
  80. instead create a cai_typedconstbuilder (this class can be overridden) }
  81. ttai_lowleveltypedconstbuilder = class abstract
  82. protected
  83. { temporary list in which all data is collected }
  84. fasmlist: tasmlist;
  85. { while queueing elements of a compound expression, this is the current
  86. offset in the top-level array/record }
  87. fqueue_offset: asizeint;
  88. { ensure that finalize_asmlist is called only once }
  89. fasmlist_finalized: boolean;
  90. { returns whether def must be handled as an aggregate on the current
  91. platform }
  92. function aggregate_kind(def: tdef): ttypedconstkind; virtual;
  93. { finalize the asmlist: add the necessary symbols etc }
  94. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; lab: boolean); virtual;
  95. public
  96. { sym is the symbol for which this typed constant data is emitted. }
  97. constructor create; virtual;
  98. destructor destroy; override;
  99. { add a simple constant data element (p) to the typed constant.
  100. def is the type of the added value }
  101. procedure emit_tai(p: tai; def: tdef); virtual;
  102. { same as above, for a special case: when the def is a procvardef and we
  103. want to use it explicitly as a procvdef (i.e., not as a record with a
  104. code and data pointer in case of a complex procvardef) }
  105. procedure emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef); virtual;
  106. { begin a potential aggregate type. Must be called for any type
  107. that consists of multiple tai constant data entries, or that
  108. represents an aggregate at the Pascal level (a record, a non-dynamic
  109. array, ... }
  110. procedure maybe_begin_aggregate(def: tdef); virtual;
  111. { end a potential aggregate type. Must be paired with every
  112. maybe_begin_aggregate }
  113. procedure maybe_end_aggregate(def: tdef); virtual;
  114. { The next group of routines are for constructing complex expressions.
  115. While parsing a typed constant these operators are encountered from
  116. outer to inner, so that is also the order in which they should be
  117. added to the queue. Only one queue can be active at a time. There is
  118. no default implementation. }
  119. { Init the queue. Gives an internalerror if a queu was already active }
  120. procedure queue_init(todef: tdef); virtual;
  121. { queue an array/string indexing operation (performs all range checking,
  122. so it doesn't have to be duplicated in all descendents). Returns the
  123. length of the elements (in bytes) and the index in the vector
  124. (0-based) }
  125. procedure queue_vecn(def: tdef; const index: tconstexprint); virtual;
  126. { queue a subscripting operation }
  127. procedure queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym); virtual;
  128. { queue a type conversion operation }
  129. procedure queue_typeconvn(fromdef, todef: tdef); virtual;
  130. { queue an address taking operation }
  131. procedure queue_addrn(fromdef, todef: tdef); virtual;
  132. { (these default implementations don't do anything but indicate the
  133. queue has been flushed by resetting fqueueu_offset)
  134. finalise the queue (so a new one can be created) and flush the
  135. previously queued operations, applying them in reverse order on a...}
  136. { ... procdef }
  137. procedure queue_emit_proc(pd: tprocdef); virtual;
  138. { ... staticvarsym }
  139. procedure queue_emit_staticvar(vs: tstaticvarsym); virtual;
  140. { ... labelsym }
  141. procedure queue_emit_label(l: tlabelsym); virtual;
  142. { ... constsym }
  143. procedure queue_emit_const(cs: tconstsym); virtual;
  144. { ... asmsym }
  145. procedure queue_emit_asmsym(sym: tasmsymbol; def: tdef); virtual;
  146. { finalize the asmlist (if necessary) and return it.
  147. At the end, the generated data can be found in the asmlist. It will
  148. be freed when the builder is destroyed, so add its contents to
  149. another list first. This property should only be accessed once all
  150. data has been added. }
  151. function get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint; lab: boolean): tasmlist;
  152. { returns the offset of the string data relative to ansi/unicode/widestring
  153. constant labels. On most platforms, this is 0 (with the header at a
  154. negative offset), but on some platforms such negative offsets are not
  155. supported }
  156. class function get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint; virtual;
  157. end;
  158. ttai_lowleveltypedconstbuilderclass = class of ttai_lowleveltypedconstbuilder;
  159. var
  160. ctai_typedconstbuilder: ttai_lowleveltypedconstbuilderclass;
  161. implementation
  162. uses
  163. verbose,globals,systems,
  164. defutil;
  165. {****************************************************************************
  166. tai_abstracttypedconst
  167. ****************************************************************************}
  168. constructor tai_abstracttypedconst.create(_adetyp: ttypedconstkind; _def: tdef);
  169. begin
  170. inherited create;
  171. typ:=ait_typedconst;
  172. fadetyp:=_adetyp;
  173. fdef:=_def;
  174. end;
  175. {****************************************************************************
  176. tai_simpletypedconst
  177. ****************************************************************************}
  178. constructor tai_simpletypedconst.create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  179. begin
  180. inherited create(_adetyp,_def);
  181. fval:=_val;
  182. end;
  183. {****************************************************************************
  184. tai_aggregatetypedconst.tadeenumerator
  185. ****************************************************************************}
  186. constructor tai_aggregatetypedconst.tadeenumerator.create(data: tai_aggregatetypedconst);
  187. begin
  188. fvalues:=data.fvalues;
  189. fvaluespos:=-1;
  190. end;
  191. function tai_aggregatetypedconst.tadeenumerator.getcurrent: tai_abstracttypedconst;
  192. begin
  193. result:=tai_abstracttypedconst(fvalues[fvaluespos]);
  194. end;
  195. function tai_aggregatetypedconst.tadeenumerator.movenext: boolean;
  196. begin
  197. if fvaluespos<pred(fvalues.count) then
  198. begin
  199. inc(fvaluespos);
  200. result:=true
  201. end
  202. else
  203. result:=false;
  204. end;
  205. procedure tai_aggregatetypedconst.tadeenumerator.reset;
  206. begin
  207. fvaluespos:=0
  208. end;
  209. {****************************************************************************
  210. tai_aggregatetypedconst
  211. ****************************************************************************}
  212. procedure tai_aggregatetypedconst.convert_to_string;
  213. var
  214. ai: tai_abstracttypedconst;
  215. newstr: tai_string;
  216. begin
  217. newstr:=tai_string.Create('');
  218. for ai in self do
  219. begin
  220. if ai.adetyp<>tck_simple then
  221. internalerror(2014070103);
  222. add_to_string(newstr,tai_simpletypedconst(ai).val);
  223. ai.free;
  224. end;
  225. fvalues.count:=0;
  226. { the "nil" def will be replaced with an array def of the appropriate
  227. size once we're finished adding data, so we don't create intermediate
  228. arraydefs all the time }
  229. fvalues.add(tai_simpletypedconst.create(tck_simple,nil,newstr));
  230. end;
  231. procedure tai_aggregatetypedconst.add_to_string(strtai: tai_string; othertai: tai);
  232. begin
  233. case othertai.typ of
  234. ait_string:
  235. begin
  236. strtai.str:=reallocmem(strtai.str,strtai.len+tai_string(othertai).len+1);
  237. { also copy null terminator }
  238. move(tai_string(othertai).str[0],strtai.str[strtai.len],tai_string(othertai).len+1);
  239. { the null terminator is not part of the length }
  240. strtai.len:=strtai.len+tai_string(othertai).len;
  241. end;
  242. ait_const:
  243. begin
  244. if tai_const(othertai).size<>1 then
  245. internalerror(2014070101);
  246. strtai.str:=reallocmem(strtai.str,strtai.len+1);
  247. strtai.str[strtai.len]:=ansichar(tai_const(othertai).value);
  248. strtai.str[strtai.len+1]:=#0;
  249. inc(strtai.len);
  250. end;
  251. else
  252. internalerror(2014070102);
  253. end;
  254. end;
  255. constructor tai_aggregatetypedconst.create(_adetyp: ttypedconstkind; _fdef: tdef);
  256. begin
  257. inherited;
  258. fisstring:=false;
  259. fvalues:=tfplist.create;
  260. end;
  261. function tai_aggregatetypedconst.getenumerator: tadeenumerator;
  262. begin
  263. result:=tadeenumerator.create(self);
  264. end;
  265. procedure tai_aggregatetypedconst.addvalue(val: tai_abstracttypedconst);
  266. begin
  267. { merge string constants and ordinal constants added in an array of
  268. char, to unify the length and the string data }
  269. if fisstring or
  270. ((val.adetyp=tck_simple) and
  271. (tai_simpletypedconst(val).val.typ=ait_string)) then
  272. begin
  273. if not fisstring and
  274. (fvalues.count>0) then
  275. convert_to_string;
  276. fisstring:=true;
  277. case fvalues.count of
  278. 0: fvalues.add(val);
  279. 1:
  280. begin
  281. add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
  282. val.free
  283. end
  284. else
  285. internalerror(2014070104);
  286. end;
  287. end
  288. else
  289. fvalues.add(val);
  290. end;
  291. procedure tai_aggregatetypedconst.finish;
  292. begin
  293. if fisstring then
  294. begin
  295. { set the def: an array of char with the same length as the string
  296. data }
  297. if fvalues.count<>1 then
  298. internalerror(2014070105);
  299. tai_simpletypedconst(fvalues[0]).fdef:=
  300. getarraydef(cansichartype,
  301. tai_string(tai_simpletypedconst(fvalues[0]).val).len);
  302. end;
  303. end;
  304. destructor tai_aggregatetypedconst.destroy;
  305. begin
  306. fvalues.free;
  307. inherited destroy;
  308. end;
  309. {*****************************************************************************
  310. ttai_lowleveltypedconstbuilder
  311. *****************************************************************************}
  312. function ttai_lowleveltypedconstbuilder.aggregate_kind(def: tdef): ttypedconstkind;
  313. begin
  314. if (def.typ in [recorddef,filedef,variantdef]) or
  315. is_object(def) or
  316. ((def.typ=procvardef) and
  317. not tprocvardef(def).is_addressonly) then
  318. result:=tck_record
  319. else if ((def.typ=arraydef) and
  320. not is_dynamic_array(def)) or
  321. ((def.typ=setdef) and
  322. not is_smallset(def)) or
  323. is_shortstring(def) then
  324. result:=tck_array
  325. else
  326. result:=tck_simple;
  327. end;
  328. procedure ttai_lowleveltypedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; lab: boolean);
  329. var
  330. prelist: tasmlist;
  331. begin
  332. prelist:=tasmlist.create_without_marker;
  333. maybe_new_object_file(prelist);
  334. { only now add items based on the symbolname, because it may be
  335. modified by the "section" specifier in case of a typed constant }
  336. new_section(prelist,section,secname,const_align(alignment));
  337. if not lab then
  338. if sym.bind=AB_GLOBAL then
  339. prelist.concat(tai_symbol.Create_Global(sym,0))
  340. else
  341. prelist.concat(tai_symbol.Create(sym,0))
  342. else
  343. prelist.concat(tai_label.Create(tasmlabel(sym)));
  344. { insert the symbol information before the data }
  345. fasmlist.insertlist(prelist);
  346. { end of the symbol }
  347. fasmlist.concat(tai_symbol_end.Createname(sym.name));
  348. { free the temporary list }
  349. prelist.free;
  350. end;
  351. function ttai_lowleveltypedconstbuilder.get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint; lab: boolean): tasmlist;
  352. begin
  353. if not fasmlist_finalized then
  354. begin
  355. finalize_asmlist(sym,def,section,secname,alignment,lab);
  356. fasmlist_finalized:=true;
  357. end;
  358. result:=fasmlist;
  359. end;
  360. class function ttai_lowleveltypedconstbuilder.get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint;
  361. const
  362. ansistring_header_size =
  363. { encoding }
  364. 2 +
  365. { elesize }
  366. 2 +
  367. {$ifdef cpu64bitaddr}
  368. { alignment }
  369. 4 +
  370. {$endif cpu64bitaddr}
  371. { reference count }
  372. sizeof(pint) +
  373. { length }
  374. sizeof(pint);
  375. unicodestring_header_size = ansistring_header_size;
  376. begin
  377. { darwin's linker does not support negative offsets }
  378. if not(target_info.system in systems_darwin) then
  379. result:=0
  380. else case typ of
  381. st_ansistring:
  382. result:=ansistring_header_size;
  383. st_unicodestring:
  384. result:=unicodestring_header_size;
  385. st_widestring:
  386. if winlikewidestring then
  387. result:=0
  388. else
  389. result:=unicodestring_header_size;
  390. else
  391. result:=0;
  392. end;
  393. end;
  394. constructor ttai_lowleveltypedconstbuilder.create;
  395. begin
  396. inherited create;
  397. fasmlist:=tasmlist.create_without_marker;
  398. { queue is empty }
  399. fqueue_offset:=low(fqueue_offset);
  400. end;
  401. destructor ttai_lowleveltypedconstbuilder.destroy;
  402. begin
  403. { the queue should have been flushed if it was used }
  404. if fqueue_offset<>low(fqueue_offset) then
  405. internalerror(2014062901);
  406. fasmlist.free;
  407. inherited destroy;
  408. end;
  409. procedure ttai_lowleveltypedconstbuilder.emit_tai(p: tai; def: tdef);
  410. begin
  411. { by default, we ignore the def info since we don't care about it at the
  412. the assembler level }
  413. fasmlist.concat(p);
  414. end;
  415. procedure ttai_lowleveltypedconstbuilder.emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef);
  416. begin
  417. { nothing special by default, since we don't care about the type }
  418. emit_tai(p,pvdef);
  419. end;
  420. procedure ttai_lowleveltypedconstbuilder.maybe_begin_aggregate(def: tdef);
  421. begin
  422. { do nothing }
  423. end;
  424. procedure ttai_lowleveltypedconstbuilder.maybe_end_aggregate(def: tdef);
  425. begin
  426. { do nothing }
  427. end;
  428. procedure ttai_lowleveltypedconstbuilder.queue_init(todef: tdef);
  429. begin
  430. { nested call to init? }
  431. if fqueue_offset<>low(fqueue_offset) then
  432. internalerror(2014062101);
  433. fqueue_offset:=0;
  434. end;
  435. procedure ttai_lowleveltypedconstbuilder.queue_vecn(def: tdef; const index: tconstexprint);
  436. var
  437. elelen,
  438. vecbase: asizeint;
  439. v: tconstexprint;
  440. begin
  441. elelen:=1;
  442. vecbase:=0;
  443. case def.typ of
  444. stringdef :
  445. ;
  446. arraydef :
  447. begin
  448. if not is_packed_array(def) then
  449. begin
  450. elelen:=tarraydef(def).elesize;
  451. vecbase:=tarraydef(def).lowrange;
  452. end
  453. else
  454. Message(parser_e_packed_dynamic_open_array);
  455. end;
  456. else
  457. Message(parser_e_illegal_expression);
  458. end;
  459. { Prevent overflow }
  460. v:=index-vecbase;
  461. if (v<int64(low(fqueue_offset))) or (v>int64(high(fqueue_offset))) then
  462. message3(type_e_range_check_error_bounds,tostr(v),tostr(low(fqueue_offset)),tostr(high(fqueue_offset)));
  463. if high(fqueue_offset)-fqueue_offset div elelen>v then
  464. inc(fqueue_offset,elelen*v.svalue)
  465. else
  466. message3(type_e_range_check_error_bounds,tostr(index),tostr(vecbase),tostr(high(fqueue_offset)-fqueue_offset div elelen+vecbase))
  467. end;
  468. procedure ttai_lowleveltypedconstbuilder.queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym);
  469. begin
  470. inc(fqueue_offset,vs.fieldoffset);
  471. end;
  472. procedure ttai_lowleveltypedconstbuilder.queue_typeconvn(fromdef, todef: tdef);
  473. begin
  474. { do nothing }
  475. end;
  476. procedure ttai_lowleveltypedconstbuilder.queue_addrn(fromdef, todef: tdef);
  477. begin
  478. { do nothing }
  479. end;
  480. procedure ttai_lowleveltypedconstbuilder.queue_emit_proc(pd: tprocdef);
  481. begin
  482. emit_tai(Tai_const.Createname(pd.mangledname,fqueue_offset),pd);
  483. fqueue_offset:=low(fqueue_offset);
  484. end;
  485. procedure ttai_lowleveltypedconstbuilder.queue_emit_staticvar(vs: tstaticvarsym);
  486. begin
  487. { getpointerdef because we are emitting a pointer to the staticvarsym
  488. data, not the data itself }
  489. emit_tai(Tai_const.Createname(vs.mangledname,fqueue_offset),getpointerdef(vs.vardef));
  490. fqueue_offset:=low(fqueue_offset);
  491. end;
  492. procedure ttai_lowleveltypedconstbuilder.queue_emit_label(l: tlabelsym);
  493. begin
  494. emit_tai(Tai_const.Createname(l.mangledname,fqueue_offset),voidcodepointertype);
  495. fqueue_offset:=low(fqueue_offset);
  496. end;
  497. procedure ttai_lowleveltypedconstbuilder.queue_emit_const(cs: tconstsym);
  498. begin
  499. if cs.consttyp<>constresourcestring then
  500. internalerror(2014062102);
  501. if fqueue_offset<>0 then
  502. internalerror(2014062103);
  503. { warning: update if/when the type of resource strings changes }
  504. emit_tai(Tai_const.Createname(make_mangledname('RESSTR',cs.owner,cs.name),AT_DATA,sizeof(pint)),cansistringtype);
  505. fqueue_offset:=low(fqueue_offset);
  506. end;
  507. procedure ttai_lowleveltypedconstbuilder.queue_emit_asmsym(sym: tasmsymbol; def: tdef);
  508. begin
  509. { getpointerdef, because "sym" represents the address of whatever the
  510. data is }
  511. def:=getpointerdef(def);
  512. emit_tai(Tai_const.Create_sym_offset(sym,fqueue_offset),def);
  513. fqueue_offset:=low(fqueue_offset);
  514. end;
  515. begin
  516. ctai_typedconstbuilder:=ttai_lowleveltypedconstbuilder;
  517. end.