aasmcnst.pas 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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 }
  28. ttypedconstkind = (tck_simple, tck_array, tck_record);
  29. { the type of the element and its def }
  30. tai_abstracttypedconst = class abstract (tai)
  31. private
  32. procedure setdef(def: tdef);
  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 write setdef;
  41. end;
  42. { a simple data element; the value is stored as a tai }
  43. tai_simpletypedconst = class(tai_abstracttypedconst)
  44. private
  45. procedure setval(AValue: tai);
  46. protected
  47. fval: tai;
  48. public
  49. constructor create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  50. property val: tai read fval write setval;
  51. end;
  52. { an aggregate data element (record or array). Values are stored as an
  53. array of tsimpledataelement. }
  54. tai_aggregatetypedconst = class(tai_abstracttypedconst)
  55. public type
  56. { iterator to walk over all individual items in the aggregate }
  57. tadeenumerator = class(tobject)
  58. private
  59. fvalues: tfplist;
  60. fvaluespos: longint;
  61. function getcurrent: tai_abstracttypedconst;
  62. public
  63. constructor create(data: tai_aggregatetypedconst);
  64. function movenext: boolean;
  65. procedure reset;
  66. property current: tai_abstracttypedconst read getcurrent;
  67. end;
  68. protected
  69. fvalues: tfplist;
  70. fisstring: boolean;
  71. { converts the existing data to a single tai_string }
  72. procedure convert_to_string;
  73. procedure add_to_string(strtai: tai_string; othertai: tai);
  74. public
  75. constructor create(_adetyp: ttypedconstkind; _fdef: tdef);
  76. function getenumerator: tadeenumerator;
  77. procedure addvalue(val: tai_abstracttypedconst);
  78. function valuecount: longint;
  79. procedure insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  80. procedure finish;
  81. destructor destroy; override;
  82. end;
  83. tasmlabofs = record
  84. lab: tasmlabel;
  85. ofs: asizeint;
  86. end;
  87. { flags for the finalisation of the typed const builder asmlist }
  88. ttcasmlistoption = (
  89. { the tasmsymbol is a tasmlabel }
  90. tcalo_is_lab,
  91. { start a new section (e.g., because we don't know the current section
  92. type) }
  93. tcalo_new_section,
  94. { this symbol is the start of a block of data that should be
  95. dead-stripable/smartlinkable; may imply starting a new section, but
  96. not necessarily (depends on what the platform requirements are) }
  97. tcalo_make_dead_strippable
  98. );
  99. ttcasmlistoptions = set of ttcasmlistoption;
  100. { information about aggregates we are parsing }
  101. taggregateinformation = class
  102. private
  103. fnextfieldname: TIDString;
  104. function getcuroffset: asizeint;
  105. function getfieldoffset(l: longint): asizeint;
  106. procedure setnextfieldname(AValue: TIDString);
  107. protected
  108. { type of the aggregate }
  109. fdef: tdef;
  110. { type of the aggregate }
  111. ftyp: ttypedconstkind;
  112. { symtable entry of the previously emitted field in case of a
  113. record/object (nil if none emitted yet), used to insert alignment bytes
  114. if necessary for variant records and objects }
  115. fcurfield,
  116. { field corresponding to the data that will be emitted next in case of a
  117. record/object (nil if not set), used to handle variant records and
  118. objects }
  119. fnextfield: tfieldvarsym;
  120. { similar as the fcurfield/fnextfield above, but instead of fieldvarsyms
  121. these are indices in the symlist of a recorddef that correspond to
  122. fieldvarsyms. These are used only for non-variant records, simply
  123. traversing the fields in order. We could use the above method here as
  124. well, but to find the next field we'd always have to use
  125. symlist.indexof(fcurfield), which would be quite slow. These have -1 as
  126. value if they're not set }
  127. fcurindex,
  128. fnextindex: longint;
  129. { anonymous record that is being built as we add constant data }
  130. fanonrecord: boolean;
  131. property curindex: longint read fcurindex write fcurindex;
  132. property nextindex: longint read fnextindex write fnextindex;
  133. public
  134. constructor create(_def: tdef; _typ: ttypedconstkind); virtual;
  135. { calculated padding bytes for alignment if needed, and add the def of the
  136. next field in case we are constructing an anonymous record }
  137. function prepare_next_field(nextfielddef: tdef): asizeint; virtual;
  138. property def: tdef read fdef;
  139. property typ: ttypedconstkind read ftyp;
  140. property curfield: tfieldvarsym read fcurfield write fcurfield;
  141. property nextfield: tfieldvarsym read fnextfield write fnextfield;
  142. property nextfieldname: TIDString write setnextfieldname;
  143. property fieldoffset[l: longint]: asizeint read getfieldoffset;
  144. property curoffset: asizeint read getcuroffset;
  145. property anonrecord: boolean read fanonrecord write fanonrecord;
  146. end;
  147. taggregateinformationclass = class of taggregateinformation;
  148. { Warning: never directly create a ttai_typedconstbuilder instance,
  149. instead create a cai_typedconstbuilder (this class can be overridden) }
  150. ttai_typedconstbuilder = class abstract
  151. { class type to use when creating new aggregate information instances }
  152. protected class var
  153. caggregateinformation: taggregateinformationclass;
  154. private
  155. function getcurragginfo: taggregateinformation;
  156. procedure set_next_field(AValue: tfieldvarsym);
  157. procedure set_next_field_name(AValue: TIDString);
  158. protected
  159. { temporary list in which all data is collected }
  160. fasmlist: tasmlist;
  161. { options for the final asmlist }
  162. foptions: ttcasmlistoptions;
  163. { while queueing elements of a compound expression, this is the current
  164. offset in the top-level array/record }
  165. fqueue_offset: asizeint;
  166. fqueued_def: tdef;
  167. { array of caggregateinformation instances }
  168. faggregateinformation: tfpobjectlist;
  169. { Support for generating data that is only referenced from the typed
  170. constant data that we are currently generated. Such data can all be put
  171. in the same dead-strippable unit, as it's either all included or none of
  172. it is included. This data can be spread over multiple kinds of sections
  173. though (e.g. rodata and rodata_no_rel), so per section keep track whether
  174. we already started a dead-strippable unit and if so, what the section
  175. name was (so that on platforms that perform the dead stripping based on
  176. sections, we put all data for one typed constant into a single section
  177. with the same name) }
  178. protected type
  179. tinternal_data_section_info = record
  180. secname: TSymStr;
  181. sectype: TAsmSectiontype;
  182. end;
  183. protected var
  184. { all internally generated data must be stored in the same list, as it must
  185. be consecutive (if it's spread over multiple lists, we don't know in
  186. which order they'll be concatenated) -> keep track of this list }
  187. finternal_data_asmlist: tasmlist;
  188. { kind of the last section we started in the finternal_data_asmlist, to
  189. avoid creating unnecessary section statements }
  190. finternal_data_current_section: TAsmSectiontype;
  191. { info about in which kinds of sections we have already emitted internal
  192. data, and what their names were }
  193. finternal_data_section_info: array of tinternal_data_section_info;
  194. { ensure that finalize_asmlist is called only once }
  195. fasmlist_finalized: boolean;
  196. { returns whether def must be handled as an aggregate on the current
  197. platform }
  198. function aggregate_kind(def: tdef): ttypedconstkind; virtual;
  199. { finalize the asmlist: add the necessary symbols etc }
  200. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  201. { called by the public emit_tai() routines to actually add the typed
  202. constant data; the public ones also take care of adding extra padding
  203. bytes etc (by calling this one) }
  204. procedure do_emit_tai(p: tai; def: tdef); virtual;
  205. { calls prepare_next_field() and adds the padding bytes in the current
  206. location }
  207. procedure pad_next_field(nextfielddef: tdef);
  208. { returns the index in finternal_data_section_info of the info for the
  209. section of type typ. Returns -1 if there is no such info yet }
  210. function get_internal_data_section_index(typ: TAsmSectiontype): longint;
  211. { get a start label for an internal data section (at the start of a
  212. potentially dead-strippable part) }
  213. function get_internal_data_section_start_label: tasmlabel; virtual;
  214. { get a label in the middle of an internal data section (no dead
  215. stripping) }
  216. function get_internal_data_section_internal_label: tasmlabel; virtual;
  217. { easy access to the top level aggregate information instance }
  218. property curagginfo: taggregateinformation read getcurragginfo;
  219. public
  220. constructor create(const options: ttcasmlistoptions); virtual;
  221. destructor destroy; override;
  222. public
  223. { returns a builder for generating data that is only referrenced by the
  224. typed constant date we are currently generating (e.g. string data for a
  225. pchar constant). Also returns the label that will be placed at the start
  226. of that data. list is the tasmlist to which the data will be added.
  227. secname can be empty to use a default }
  228. procedure start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  229. { finish a previously started internal data builder, including
  230. concatenating all generated data to the provided list and freeing the
  231. builder }
  232. procedure finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  233. { add a simple constant data element (p) to the typed constant.
  234. def is the type of the added value }
  235. procedure emit_tai(p: tai; def: tdef); virtual;
  236. { same as above, for a special case: when the def is a procvardef and we
  237. want to use it explicitly as a procdef (i.e., not as a record with a
  238. code and data pointer in case of a complex procvardef) }
  239. procedure emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef); virtual;
  240. protected
  241. procedure maybe_emit_tail_padding(def: tdef); virtual;
  242. function emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel):tasmlabofs;
  243. procedure begin_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  244. procedure end_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  245. { when building an anonymous record, we cannot immediately insert the
  246. alignment before it in case it's nested, since we only know the required
  247. alignment once all fields have been inserted -> mark the location before
  248. the anonymous record, and insert the alignment once it's finished }
  249. procedure mark_anon_aggregate_alignment; virtual; abstract;
  250. procedure insert_marked_aggregate_alignment(def: tdef); virtual; abstract;
  251. public
  252. class function get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): string;
  253. { the datalist parameter specifies where the data for the string constant
  254. will be emitted (via an internal data builder) }
  255. function emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  256. function emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  257. { emits a tasmlabofs as returned by emit_*string_const }
  258. procedure emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);virtual;
  259. { emit a shortstring constant, and return its def }
  260. function emit_shortstring_const(const str: shortstring): tdef;
  261. { emit a guid constant }
  262. procedure emit_guid_const(const guid: tguid);
  263. { emit a procdef constant }
  264. procedure emit_procdef_const(pd: tprocdef);
  265. { emit an ordinal constant }
  266. procedure emit_ord_const(value: int64; def: tdef);
  267. { begin a potential aggregate type. Must be called for any type
  268. that consists of multiple tai constant data entries, or that
  269. represents an aggregate at the Pascal level (a record, a non-dynamic
  270. array, ... }
  271. procedure maybe_begin_aggregate(def: tdef);
  272. { end a potential aggregate type. Must be paired with every
  273. maybe_begin_aggregate }
  274. procedure maybe_end_aggregate(def: tdef);
  275. { similar as above, but in case
  276. a) it's definitely a record
  277. b) the def of the record should be automatically constructed based on
  278. the types of the emitted fields
  279. packrecords: same as "pacrecords x"
  280. recordalign: specify the (minimum) alignment of the start of the record
  281. (no equivalent in source code), used as an alternative for explicit
  282. align statements. Use "1" if it should be calculated based on the
  283. fields
  284. recordalignmin: same as "codealign recordmin=x"
  285. maxcrecordalign: specify maximum C record alignment (no equivalent in
  286. source code)
  287. }
  288. function begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef; virtual;
  289. function end_anonymous_record: trecorddef; virtual;
  290. { The next group of routines are for constructing complex expressions.
  291. While parsing a typed constant these operators are encountered from
  292. outer to inner, so that is also the order in which they should be
  293. added to the queue. Only one queue can be active at a time. }
  294. { Init the queue. Gives an internalerror if a queue was already active }
  295. procedure queue_init(todef: tdef); virtual;
  296. { queue an array/string indexing operation (performs all range checking,
  297. so it doesn't have to be duplicated in all descendents). }
  298. procedure queue_vecn(def: tdef; const index: tconstexprint); virtual;
  299. { queue a subscripting operation }
  300. procedure queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym); virtual;
  301. { queue indexing a record recursively via several field names. The fields
  302. are specified in the inner to outer order (i.e., def.field1.field2) }
  303. function queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  304. { queue a type conversion operation }
  305. procedure queue_typeconvn(fromdef, todef: tdef); virtual;
  306. { finalise the queue (so a new one can be created) and flush the
  307. previously queued operations, applying them in reverse order on a...}
  308. { ... procdef }
  309. procedure queue_emit_proc(pd: tprocdef); virtual;
  310. { ... staticvarsym }
  311. procedure queue_emit_staticvar(vs: tstaticvarsym); virtual;
  312. { ... labelsym }
  313. procedure queue_emit_label(l: tlabelsym); virtual;
  314. { ... constsym }
  315. procedure queue_emit_const(cs: tconstsym); virtual;
  316. { ... asmsym/asmlabel }
  317. procedure queue_emit_asmsym(sym: tasmsymbol; def: tdef); virtual;
  318. { ... an ordinal constant }
  319. procedure queue_emit_ordconst(value: int64; def: tdef); virtual;
  320. protected
  321. { returns whether queue_init has been called without a corresponding
  322. queue_emit_* to finish it }
  323. function queue_is_active: boolean;
  324. public
  325. { finalize the internal asmlist (if necessary) and return it.
  326. This asmlist will be freed when the builder is destroyed, so add its
  327. contents to another list first. This property should only be accessed
  328. once all data has been added. }
  329. function get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  330. { returns the offset of the string data relative to ansi/unicode/widestring
  331. constant labels. On most platforms, this is 0 (with the header at a
  332. negative offset), but on some platforms such negative offsets are not
  333. supported this is equal to the header size }
  334. class function get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint; virtual;
  335. { set the fieldvarsym whose data we will emit next; needed
  336. in case of variant records, so we know which part of the variant gets
  337. initialised. Also in case of objects, because the fieldvarsyms are spread
  338. over the symtables of the entire inheritance tree }
  339. property next_field: tfieldvarsym write set_next_field;
  340. { set the name of the next field that will be emitted for an anonymous
  341. record (or the next of the next started anonymous record) }
  342. property next_field_name: TIDString write set_next_field_name;
  343. protected
  344. { this one always return the actual offset, called by the above (and
  345. overridden versions) }
  346. class function get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  347. end;
  348. ttai_typedconstbuilderclass = class of ttai_typedconstbuilder;
  349. tlowlevelaggregateinformation = class(taggregateinformation)
  350. protected
  351. fanonrecmarker: tai;
  352. public
  353. property anonrecmarker: tai read fanonrecmarker write fanonrecmarker;
  354. end;
  355. ttai_lowleveltypedconstbuilder = class(ttai_typedconstbuilder)
  356. protected
  357. procedure mark_anon_aggregate_alignment; override;
  358. procedure insert_marked_aggregate_alignment(def: tdef); override;
  359. public
  360. { set the default value for caggregateinformation (= tlowlevelaggregateinformation) }
  361. class constructor classcreate;
  362. end;
  363. var
  364. ctai_typedconstbuilder: ttai_typedconstbuilderclass;
  365. implementation
  366. uses
  367. verbose,globals,systems,widestr,
  368. fmodule,
  369. symbase,symtable,defutil;
  370. {****************************************************************************
  371. taggregateinformation
  372. ****************************************************************************}
  373. function taggregateinformation.getcuroffset: asizeint;
  374. var
  375. field: tfieldvarsym;
  376. begin
  377. if assigned(curfield) then
  378. result:=curfield.fieldoffset+curfield.vardef.size
  379. else if curindex<>-1 then
  380. begin
  381. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[curindex]);
  382. result:=field.fieldoffset+field.vardef.size
  383. end
  384. else
  385. result:=0
  386. end;
  387. function taggregateinformation.getfieldoffset(l: longint): asizeint;
  388. var
  389. field: tfieldvarsym;
  390. begin
  391. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[l]);
  392. result:=field.fieldoffset;
  393. end;
  394. procedure taggregateinformation.setnextfieldname(AValue: TIDString);
  395. begin
  396. if (fnextfieldname<>'') or
  397. not anonrecord then
  398. internalerror(2015071503);
  399. fnextfieldname:=AValue;
  400. end;
  401. constructor taggregateinformation.create(_def: tdef; _typ: ttypedconstkind);
  402. begin
  403. fdef:=_def;
  404. ftyp:=_typ;
  405. fcurindex:=-1;
  406. fnextindex:=-1;
  407. end;
  408. function taggregateinformation.prepare_next_field(nextfielddef: tdef): asizeint;
  409. var
  410. currentoffset,nextoffset: asizeint;
  411. i: longint;
  412. begin
  413. { get the next field and its offset, and make that next field the current
  414. one }
  415. if assigned(nextfield) then
  416. begin
  417. nextoffset:=nextfield.fieldoffset;
  418. currentoffset:=curoffset;
  419. curfield:=nextfield;
  420. end
  421. else
  422. begin
  423. { must set nextfield for unions and objects, as we cannot
  424. automatically detect the "next" field in that case }
  425. if ((def.typ=recorddef) and
  426. trecorddef(def).isunion) or
  427. is_object(def) then
  428. internalerror(2014091202);
  429. { if we are constructing this record as data gets emitted, add a field
  430. for this data }
  431. if anonrecord then
  432. begin
  433. trecorddef(def).add_field_by_def(fnextfieldname,nextfielddef);
  434. fnextfieldname:='';
  435. end
  436. else if fnextfieldname<>'' then
  437. internalerror(2015071501);
  438. { find next field }
  439. i:=curindex;
  440. repeat
  441. inc(i);
  442. until (tsym(tabstractrecorddef(def).symtable.symlist[i]).typ=fieldvarsym) and
  443. not(sp_static in tsym(tabstractrecorddef(def).symtable.symlist[i]).symoptions);
  444. nextoffset:=fieldoffset[i];
  445. currentoffset:=curoffset;
  446. curindex:=i;
  447. end;
  448. { need padding? }
  449. result:=nextoffset-currentoffset;
  450. end;
  451. {****************************************************************************
  452. tai_abstracttypedconst
  453. ****************************************************************************}
  454. procedure tai_abstracttypedconst.setdef(def: tdef);
  455. begin
  456. { should not be changed, rewrite the calling code if this happens }
  457. if assigned(fdef) then
  458. Internalerror(2014080203);
  459. fdef:=def;
  460. end;
  461. constructor tai_abstracttypedconst.create(_adetyp: ttypedconstkind; _def: tdef);
  462. begin
  463. inherited create;
  464. typ:=ait_typedconst;
  465. fadetyp:=_adetyp;
  466. fdef:=_def;
  467. end;
  468. {****************************************************************************
  469. tai_simpletypedconst
  470. ****************************************************************************}
  471. procedure tai_simpletypedconst.setval(AValue: tai);
  472. begin
  473. fval:=AValue;
  474. end;
  475. constructor tai_simpletypedconst.create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  476. begin
  477. inherited create(_adetyp,_def);
  478. fval:=_val;
  479. end;
  480. {****************************************************************************
  481. tai_aggregatetypedconst.tadeenumerator
  482. ****************************************************************************}
  483. constructor tai_aggregatetypedconst.tadeenumerator.create(data: tai_aggregatetypedconst);
  484. begin
  485. fvalues:=data.fvalues;
  486. fvaluespos:=-1;
  487. end;
  488. function tai_aggregatetypedconst.tadeenumerator.getcurrent: tai_abstracttypedconst;
  489. begin
  490. result:=tai_abstracttypedconst(fvalues[fvaluespos]);
  491. end;
  492. function tai_aggregatetypedconst.tadeenumerator.movenext: boolean;
  493. begin
  494. if fvaluespos<pred(fvalues.count) then
  495. begin
  496. inc(fvaluespos);
  497. result:=true
  498. end
  499. else
  500. result:=false;
  501. end;
  502. procedure tai_aggregatetypedconst.tadeenumerator.reset;
  503. begin
  504. fvaluespos:=0
  505. end;
  506. {****************************************************************************
  507. tai_aggregatetypedconst
  508. ****************************************************************************}
  509. procedure tai_aggregatetypedconst.convert_to_string;
  510. var
  511. ai: tai_abstracttypedconst;
  512. newstr: tai_string;
  513. begin
  514. newstr:=tai_string.Create('');
  515. for ai in self do
  516. begin
  517. if ai.adetyp<>tck_simple then
  518. internalerror(2014070103);
  519. add_to_string(newstr,tai_simpletypedconst(ai).val);
  520. ai.free;
  521. end;
  522. fvalues.count:=0;
  523. { the "nil" def will be replaced with an array def of the appropriate
  524. size once we're finished adding data, so we don't create intermediate
  525. arraydefs all the time }
  526. fvalues.add(tai_simpletypedconst.create(tck_simple,nil,newstr));
  527. end;
  528. procedure tai_aggregatetypedconst.add_to_string(strtai: tai_string; othertai: tai);
  529. begin
  530. case othertai.typ of
  531. ait_string:
  532. begin
  533. strtai.str:=reallocmem(strtai.str,strtai.len+tai_string(othertai).len+1);
  534. { also copy null terminator }
  535. move(tai_string(othertai).str[0],strtai.str[strtai.len],tai_string(othertai).len+1);
  536. { the null terminator is not part of the string data }
  537. strtai.len:=strtai.len+tai_string(othertai).len;
  538. end;
  539. ait_const:
  540. begin
  541. if tai_const(othertai).size<>1 then
  542. internalerror(2014070101);
  543. strtai.str:=reallocmem(strtai.str,strtai.len+1);
  544. strtai.str[strtai.len]:=ansichar(tai_const(othertai).value);
  545. strtai.str[strtai.len+1]:=#0;
  546. inc(strtai.len);
  547. end;
  548. else
  549. internalerror(2014070102);
  550. end;
  551. end;
  552. constructor tai_aggregatetypedconst.create(_adetyp: ttypedconstkind; _fdef: tdef);
  553. begin
  554. inherited;
  555. fisstring:=false;
  556. fvalues:=tfplist.create;
  557. end;
  558. function tai_aggregatetypedconst.getenumerator: tadeenumerator;
  559. begin
  560. result:=tadeenumerator.create(self);
  561. end;
  562. procedure tai_aggregatetypedconst.addvalue(val: tai_abstracttypedconst);
  563. begin
  564. { merge string constants and ordinal constants added in an array of
  565. char, to unify the length and the string data }
  566. if fisstring or
  567. ((val.adetyp=tck_simple) and
  568. (tai_simpletypedconst(val).val.typ=ait_string)) then
  569. begin
  570. if not fisstring and
  571. (fvalues.count>0) then
  572. convert_to_string;
  573. fisstring:=true;
  574. case fvalues.count of
  575. 0: fvalues.add(val);
  576. 1:
  577. begin
  578. add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
  579. val.free
  580. end
  581. else
  582. internalerror(2014070104);
  583. end;
  584. end
  585. else
  586. fvalues.add(val);
  587. end;
  588. function tai_aggregatetypedconst.valuecount: longint;
  589. begin
  590. result:=fvalues.count;
  591. end;
  592. procedure tai_aggregatetypedconst.insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  593. begin
  594. fvalues.insert(pos,val);
  595. end;
  596. procedure tai_aggregatetypedconst.finish;
  597. begin
  598. if fisstring then
  599. begin
  600. { set the def: an array of char with the same length as the string
  601. data }
  602. if fvalues.count<>1 then
  603. internalerror(2014070105);
  604. tai_simpletypedconst(fvalues[0]).fdef:=
  605. carraydef.getreusable(cansichartype,
  606. tai_string(tai_simpletypedconst(fvalues[0]).val).len);
  607. end;
  608. end;
  609. destructor tai_aggregatetypedconst.destroy;
  610. begin
  611. fvalues.free;
  612. inherited destroy;
  613. end;
  614. {*****************************************************************************
  615. ttai_typedconstbuilder
  616. *****************************************************************************}
  617. function ttai_typedconstbuilder.getcurragginfo: taggregateinformation;
  618. begin
  619. if assigned(faggregateinformation) and
  620. (faggregateinformation.count>0) then
  621. result:=taggregateinformation(faggregateinformation[faggregateinformation.count-1])
  622. else
  623. result:=nil;
  624. end;
  625. procedure ttai_typedconstbuilder.set_next_field(AValue: tfieldvarsym);
  626. var
  627. info: taggregateinformation;
  628. begin
  629. info:=curagginfo;
  630. if not assigned(info) then
  631. internalerror(2014091206);
  632. info.nextfield:=AValue;
  633. end;
  634. procedure ttai_typedconstbuilder.set_next_field_name(AValue: TIDString);
  635. var
  636. info: taggregateinformation;
  637. begin
  638. info:=curagginfo;
  639. if not assigned(info) then
  640. internalerror(2015071502);
  641. info.nextfieldname:='$'+AValue;
  642. end;
  643. procedure ttai_typedconstbuilder.pad_next_field(nextfielddef: tdef);
  644. var
  645. fillbytes: asizeint;
  646. begin
  647. fillbytes:=curagginfo.prepare_next_field(nextfielddef);
  648. while fillbytes>0 do
  649. begin
  650. do_emit_tai(tai_const.create_8bit(0),u8inttype);
  651. dec(fillbytes);
  652. end;
  653. end;
  654. function ttai_typedconstbuilder.get_internal_data_section_index(typ: TAsmSectiontype): longint;
  655. begin
  656. { avoid wrong warning by -Oodfa }
  657. result:=-1;
  658. for result:=low(finternal_data_section_info) to high(finternal_data_section_info) do
  659. if finternal_data_section_info[result].sectype=typ then
  660. exit;
  661. result:=-1;
  662. end;
  663. function ttai_typedconstbuilder.get_internal_data_section_start_label: tasmlabel;
  664. begin
  665. { on Darwin, dead code/data stripping happens based on non-temporary
  666. labels (any label that doesn't start with "L" -- it doesn't have
  667. to be global) }
  668. if target_info.system in systems_darwin then
  669. current_asmdata.getstaticdatalabel(result)
  670. else if create_smartlink_library then
  671. current_asmdata.getglobaldatalabel(result)
  672. else
  673. current_asmdata.getlocaldatalabel(result);
  674. end;
  675. function ttai_typedconstbuilder.get_internal_data_section_internal_label: tasmlabel;
  676. begin
  677. if create_smartlink_library then
  678. { all labels need to be global in case they're in another object }
  679. current_asmdata.getglobaldatalabel(result)
  680. else
  681. { no special requirement for the label -> just get a local one }
  682. current_asmdata.getlocaldatalabel(result);
  683. end;
  684. function ttai_typedconstbuilder.aggregate_kind(def: tdef): ttypedconstkind;
  685. begin
  686. if (def.typ in [recorddef,filedef,variantdef]) or
  687. is_object(def) or
  688. ((def.typ=procvardef) and
  689. not tprocvardef(def).is_addressonly) then
  690. result:=tck_record
  691. else if ((def.typ=arraydef) and
  692. not is_dynamic_array(def)) or
  693. ((def.typ=setdef) and
  694. not is_smallset(def)) or
  695. is_shortstring(def) then
  696. result:=tck_array
  697. else
  698. result:=tck_simple;
  699. end;
  700. procedure ttai_typedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  701. var
  702. prelist: tasmlist;
  703. begin
  704. { have we finished all aggregates? }
  705. if (getcurragginfo<>nil) and
  706. { in case of syntax errors, the aggregate may not have been finished }
  707. (ErrorCount=0) then
  708. internalerror(2015072301);
  709. prelist:=tasmlist.create;
  710. { only now add items based on the symbolname, because it may be
  711. modified by the "section" specifier in case of a typed constant }
  712. if tcalo_make_dead_strippable in options then
  713. begin
  714. maybe_new_object_file(prelist);
  715. { we always need a new section here, since if we started a new
  716. object file then we have to say what the section is, and otherwise
  717. we need a new section because that's how the dead stripping works
  718. (except on Darwin, but that will be addressed in a future commit) }
  719. new_section(prelist,section,secname,const_align(alignment));
  720. end
  721. else if tcalo_new_section in options then
  722. new_section(prelist,section,secname,const_align(alignment))
  723. else
  724. prelist.concat(cai_align.Create(const_align(alignment)));
  725. if not(tcalo_is_lab in options) then
  726. if sym.bind=AB_GLOBAL then
  727. prelist.concat(tai_symbol.Create_Global(sym,0))
  728. else
  729. prelist.concat(tai_symbol.Create(sym,0))
  730. else
  731. prelist.concat(tai_label.Create(tasmlabel(sym)));
  732. { insert the symbol information before the data }
  733. fasmlist.insertlist(prelist);
  734. { end of the symbol }
  735. fasmlist.concat(tai_symbol_end.Createname(sym.name));
  736. { free the temporary list }
  737. prelist.free;
  738. end;
  739. procedure ttai_typedconstbuilder.do_emit_tai(p: tai; def: tdef);
  740. begin
  741. { by default we don't care about the type }
  742. fasmlist.concat(p);
  743. end;
  744. function ttai_typedconstbuilder.get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  745. begin
  746. if not fasmlist_finalized then
  747. begin
  748. finalize_asmlist(sym,def,section,secname,alignment,foptions);
  749. fasmlist_finalized:=true;
  750. end;
  751. result:=fasmlist;
  752. end;
  753. class function ttai_typedconstbuilder.get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint;
  754. begin
  755. { darwin's linker does not support negative offsets }
  756. if not(target_info.system in systems_darwin) then
  757. result:=0
  758. else
  759. result:=get_string_header_size(typ,winlikewidestring);
  760. end;
  761. class function ttai_typedconstbuilder.get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  762. const
  763. ansistring_header_size =
  764. { encoding }
  765. 2 +
  766. { elesize }
  767. 2 +
  768. {$ifdef cpu64bitaddr}
  769. { alignment }
  770. 4 +
  771. {$endif cpu64bitaddr}
  772. { reference count }
  773. sizeof(pint) +
  774. { length }
  775. sizeof(pint);
  776. unicodestring_header_size = ansistring_header_size;
  777. begin
  778. case typ of
  779. st_ansistring:
  780. result:=ansistring_header_size;
  781. st_unicodestring:
  782. result:=unicodestring_header_size;
  783. st_widestring:
  784. if winlikewidestring then
  785. result:=0
  786. else
  787. result:=unicodestring_header_size;
  788. else
  789. result:=0;
  790. end;
  791. end;
  792. constructor ttai_typedconstbuilder.create(const options: ttcasmlistoptions);
  793. begin
  794. inherited create;
  795. fasmlist:=tasmlist.create;
  796. foptions:=options;
  797. { queue is empty }
  798. fqueue_offset:=low(fqueue_offset);
  799. finternal_data_current_section:=sec_none;
  800. end;
  801. destructor ttai_typedconstbuilder.destroy;
  802. begin
  803. { the queue should have been flushed if it was used }
  804. if fqueue_offset<>low(fqueue_offset) then
  805. internalerror(2014062901);
  806. faggregateinformation.free;
  807. fasmlist.free;
  808. inherited destroy;
  809. end;
  810. procedure ttai_typedconstbuilder.start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  811. var
  812. options: ttcasmlistoptions;
  813. foundsec: longint;
  814. begin
  815. options:=[tcalo_is_lab];
  816. { Add a section header if the previous one was different. We'll use the
  817. same section name in case multiple items are added to the same kind of
  818. section (rodata, rodata_no_rel, ...), so that everything will still
  819. end up in the same section even if there are multiple section headers }
  820. if finternal_data_current_section<>sectype then
  821. include(options,tcalo_new_section);
  822. finternal_data_current_section:=sectype;
  823. l:=nil;
  824. { did we already create a section of this type for the internal data of
  825. this builder? }
  826. foundsec:=get_internal_data_section_index(sectype);
  827. if foundsec=-1 then
  828. begin
  829. { we only need to start a dead-strippable section of data at the
  830. start of the first subsection of this kind for this block.
  831. exception: if dead stripping happens based on objects/libraries,
  832. then we only have to create a new object file for the first
  833. internal data section of any kind (all the rest will simply be put
  834. in the same object file) }
  835. if create_smartlink then
  836. begin
  837. if not create_smartlink_library or
  838. (length(finternal_data_section_info)=0) then
  839. include(options,tcalo_make_dead_strippable);
  840. { on Darwin, dead code/data stripping happens based on non-
  841. temporary labels (any label that doesn't start with "L" -- it
  842. doesn't have to be global) -> add a non-temporary lobel at the
  843. start of every kind of subsection created in this builder }
  844. if target_info.system in systems_darwin then
  845. l:=get_internal_data_section_start_label;
  846. end;
  847. foundsec:=length(finternal_data_section_info);
  848. setlength(finternal_data_section_info,foundsec+1);
  849. finternal_data_section_info[foundsec].sectype:=sectype;
  850. end;
  851. if not assigned(finternal_data_asmlist) and
  852. (cs_create_smart in current_settings.moduleswitches) then
  853. begin
  854. l:=get_internal_data_section_start_label;
  855. { the internal data list should only be assigned by this routine,
  856. the first time that an internal data block is started }
  857. if not assigned(list) or
  858. assigned(finternal_data_asmlist) then
  859. internalerror(2015032101);
  860. finternal_data_asmlist:=list;
  861. end
  862. { all internal data for this tcb must go to the same list (otherwise all
  863. data we want to add to the dead-strippable block is not guaranteed to
  864. be sequential and e.g. in the same object file in case of library-based
  865. dead stripping) }
  866. else if (assigned(finternal_data_asmlist) and
  867. (list<>finternal_data_asmlist)) or
  868. not assigned(list) then
  869. internalerror(2015032101);
  870. finternal_data_asmlist:=list;
  871. if not assigned(l) then
  872. l:=get_internal_data_section_internal_label;
  873. { first section of this kind -> set name }
  874. if finternal_data_section_info[foundsec].secname='' then
  875. if secname='' then
  876. finternal_data_section_info[foundsec].secname:=l.Name
  877. else
  878. finternal_data_section_info[foundsec].secname:=secname
  879. { if the name is specified multiple times, it must match }
  880. else if (secname<>'') and
  881. (finternal_data_section_info[foundsec].secname<>secname) then
  882. internalerror(2015032401);
  883. tcb:=ttai_typedconstbuilderclass(classtype).create(options);
  884. end;
  885. procedure ttai_typedconstbuilder.finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  886. begin
  887. finternal_data_asmlist.concatList(tcb.get_final_asmlist(l,def,
  888. finternal_data_current_section,
  889. finternal_data_section_info[get_internal_data_section_index(finternal_data_current_section)].secname,
  890. alignment));
  891. tcb.free;
  892. tcb:=nil;
  893. end;
  894. procedure ttai_typedconstbuilder.emit_tai(p: tai; def: tdef);
  895. var
  896. kind: ttypedconstkind;
  897. info: taggregateinformation;
  898. begin
  899. { these elements can be aggregates themselves, e.g. a shortstring can
  900. be emitted as a series of bytes and char arrays }
  901. kind:=aggregate_kind(def);
  902. info:=curagginfo;
  903. if (kind<>tck_simple) and
  904. (not assigned(info) or
  905. (info.typ<>kind)) then
  906. internalerror(2014091001);
  907. { if we're emitting a record, handle the padding bytes, and in case of
  908. an anonymous record also add the next field }
  909. if assigned(info) then
  910. begin
  911. { queue_init already adds padding }
  912. if not queue_is_active and
  913. (is_record(info.def) or
  914. is_object(info.def)) and
  915. { may add support for these later }
  916. not is_packed_record_or_object(info.def) then
  917. pad_next_field(def);
  918. end;
  919. { emit the data }
  920. do_emit_tai(p,def);
  921. end;
  922. procedure ttai_typedconstbuilder.emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef);
  923. begin
  924. { nothing special by default, since we don't care about the type }
  925. emit_tai(p,pvdef);
  926. end;
  927. procedure ttai_typedconstbuilder.maybe_emit_tail_padding(def: tdef);
  928. var
  929. info: taggregateinformation;
  930. fillbytes: asizeint;
  931. begin
  932. info:=curagginfo;
  933. if not assigned(info) then
  934. internalerror(2014091002);
  935. if def<>info.def then
  936. internalerror(2014091205);
  937. if (is_record(def) or
  938. is_object(def)) and
  939. not is_packed_record_or_object(def) then
  940. begin
  941. fillbytes:=def.size-info.curoffset;
  942. while fillbytes>0 do
  943. begin
  944. do_emit_tai(Tai_const.Create_8bit(0),u8inttype);
  945. dec(fillbytes)
  946. end;
  947. end;
  948. end;
  949. function ttai_typedconstbuilder.emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel): tasmlabofs;
  950. var
  951. string_symofs: asizeint;
  952. charptrdef: tdef;
  953. elesize: word;
  954. begin
  955. result.lab:=startlab;
  956. result.ofs:=0;
  957. { pack the data, so that we don't add unnecessary null bytes after the
  958. constant string }
  959. begin_anonymous_record('$'+get_dynstring_rec_name(stringtype,false,len),1,sizeof(TConstPtrUInt),1,1);
  960. string_symofs:=get_string_symofs(stringtype,false);
  961. { encoding }
  962. emit_tai(tai_const.create_16bit(encoding),u16inttype);
  963. inc(result.ofs,2);
  964. { element size }
  965. case stringtype of
  966. st_ansistring:
  967. begin
  968. elesize:=1;
  969. charptrdef:=charpointertype;
  970. end;
  971. st_unicodestring:
  972. begin
  973. elesize:=2;
  974. charptrdef:=widecharpointertype;
  975. end
  976. else
  977. internalerror(2014080401);
  978. end;
  979. emit_tai(tai_const.create_16bit(elesize),u16inttype);
  980. inc(result.ofs,2);
  981. {$ifdef cpu64bitaddr}
  982. { dummy for alignment }
  983. emit_tai(tai_const.create_32bit(0),u32inttype);
  984. inc(result.ofs,4);
  985. {$endif cpu64bitaddr}
  986. emit_tai(tai_const.create_pint(-1),ptrsinttype);
  987. inc(result.ofs,sizeof(pint));
  988. emit_tai(tai_const.create_pint(len),ptrsinttype);
  989. inc(result.ofs,sizeof(pint));
  990. if string_symofs=0 then
  991. begin
  992. { results in slightly more efficient code }
  993. emit_tai(tai_label.create(result.lab),charptrdef);
  994. result.ofs:=0;
  995. { create new label of the same kind (including whether or not the
  996. name starts with target_asm.labelprefix in case it's AB_LOCAL,
  997. so we keep the difference depending on whether the original was
  998. allocated via getstatic/getlocal/getglobal datalabel) }
  999. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1000. end;
  1001. { sanity check }
  1002. if result.ofs<>string_symofs then
  1003. internalerror(2012051701);
  1004. end;
  1005. procedure ttai_typedconstbuilder.begin_aggregate_internal(def: tdef; anonymous: boolean);
  1006. var
  1007. info: taggregateinformation;
  1008. tck: ttypedconstkind;
  1009. begin
  1010. tck:=aggregate_kind(def);
  1011. if tck=tck_simple then
  1012. exit;
  1013. if not assigned(faggregateinformation) then
  1014. faggregateinformation:=tfpobjectlist.create
  1015. { if we're starting an anonymous record, we can't align it yet because
  1016. the alignment depends on the fields that will be added -> we'll do
  1017. it at the end }
  1018. else if not anonymous then
  1019. begin
  1020. { add padding if necessary, and update the current field/offset }
  1021. info:=curagginfo;
  1022. if (is_record(curagginfo.def) or
  1023. is_object(curagginfo.def)) and
  1024. not is_packed_record_or_object(curagginfo.def) then
  1025. begin
  1026. if queue_is_active then
  1027. internalerror(2015073001);
  1028. pad_next_field(def);
  1029. end;
  1030. end
  1031. { if this is the outer record, no padding is required; the alignment
  1032. has to be specified explicitly in that case via get_final_asmlist() }
  1033. else if assigned(curagginfo) and
  1034. (curagginfo.def.typ=recorddef) then
  1035. { mark where we'll have to insert the padding bytes at the end }
  1036. mark_anon_aggregate_alignment;
  1037. info:=caggregateinformation.create(def,aggregate_kind(def));
  1038. faggregateinformation.add(info);
  1039. end;
  1040. procedure ttai_typedconstbuilder.end_aggregate_internal(def: tdef; anonymous: boolean);
  1041. var
  1042. info: taggregateinformation;
  1043. tck: ttypedconstkind;
  1044. begin
  1045. tck:=aggregate_kind(def);
  1046. if tck=tck_simple then
  1047. exit;
  1048. { add tail padding if necessary }
  1049. maybe_emit_tail_padding(def);
  1050. { pop and free the information }
  1051. info:=curagginfo;
  1052. faggregateinformation.count:=faggregateinformation.count-1;
  1053. info.free;
  1054. end;
  1055. class function ttai_typedconstbuilder.get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): string;
  1056. begin
  1057. case typ of
  1058. st_ansistring:
  1059. result:='ansistrrec';
  1060. st_unicodestring,
  1061. st_widestring:
  1062. if (typ=st_unicodestring) or
  1063. not winlike then
  1064. result:='unicodestrrec'
  1065. else
  1066. result:='widestrrec';
  1067. else
  1068. internalerror(2014080402);
  1069. end;
  1070. result:=result+tostr(len);
  1071. end;
  1072. function ttai_typedconstbuilder.emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  1073. var
  1074. s: PChar;
  1075. startlab: tasmlabel;
  1076. ansistrrecdef: trecorddef;
  1077. datadef: tdef;
  1078. datatcb: ttai_typedconstbuilder;
  1079. begin
  1080. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1081. result:=datatcb.emit_string_const_common(st_ansistring,len,encoding,startlab);
  1082. getmem(s,len+1);
  1083. move(data^,s^,len);
  1084. s[len]:=#0;
  1085. { terminating zero included }
  1086. datadef:=carraydef.getreusable(cansichartype,len+1);
  1087. datatcb.maybe_begin_aggregate(datadef);
  1088. datatcb.emit_tai(tai_string.create_pchar(s,len+1),datadef);
  1089. datatcb.maybe_end_aggregate(datadef);
  1090. ansistrrecdef:=datatcb.end_anonymous_record;
  1091. finish_internal_data_builder(datatcb,startlab,ansistrrecdef,const_align(sizeof(pointer)));
  1092. end;
  1093. function ttai_typedconstbuilder.emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  1094. var
  1095. i, strlength: longint;
  1096. string_symofs: asizeint;
  1097. startlab: tasmlabel;
  1098. datadef: tdef;
  1099. uniwidestrrecdef: trecorddef;
  1100. datatcb: ttai_typedconstbuilder;
  1101. begin
  1102. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1103. strlength:=getlengthwidestring(pcompilerwidestring(data));
  1104. if winlike then
  1105. begin
  1106. result.lab:=startlab;
  1107. datatcb.begin_anonymous_record('$'+get_dynstring_rec_name(st_widestring,true,strlength),
  1108. 4,4,
  1109. targetinfos[target_info.system]^.alignment.recordalignmin,
  1110. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1111. datatcb.emit_tai(Tai_const.Create_32bit(strlength*cwidechartype.size),s32inttype);
  1112. { can we optimise by placing the string constant label at the
  1113. required offset? }
  1114. string_symofs:=get_string_symofs(st_widestring,true);
  1115. if string_symofs=0 then
  1116. begin
  1117. { yes }
  1118. datatcb.emit_tai(Tai_label.Create(result.lab),widecharpointertype);
  1119. { allocate a separate label for the start of the data (see
  1120. emit_string_const_common() for explanation) }
  1121. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1122. end
  1123. else
  1124. internalerror(2015031502);
  1125. result.ofs:=string_symofs;
  1126. end
  1127. else
  1128. begin
  1129. result:=datatcb.emit_string_const_common(st_unicodestring,strlength,encoding,startlab);
  1130. end;
  1131. if cwidechartype.size = 2 then
  1132. begin
  1133. datadef:=carraydef.getreusable(cwidechartype,strlength+1);
  1134. datatcb.maybe_begin_aggregate(datadef);
  1135. for i:=0 to strlength-1 do
  1136. datatcb.emit_tai(Tai_const.Create_16bit(pcompilerwidestring(data)^.data[i]),cwidechartype);
  1137. { ending #0 }
  1138. datatcb.emit_tai(Tai_const.Create_16bit(0),cwidechartype);
  1139. datatcb.maybe_end_aggregate(datadef);
  1140. uniwidestrrecdef:=datatcb.end_anonymous_record;
  1141. end
  1142. else
  1143. { code generation for other sizes must be written }
  1144. internalerror(200904271);
  1145. finish_internal_data_builder(datatcb,startlab,datadef,const_align(sizeof(pint)));
  1146. end;
  1147. procedure ttai_typedconstbuilder.emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);
  1148. begin
  1149. emit_tai(Tai_const.Create_sym_offset(ll.lab,ll.ofs),charptrdef);
  1150. end;
  1151. function ttai_typedconstbuilder.emit_shortstring_const(const str: shortstring): tdef;
  1152. begin
  1153. { we use an arraydef instead of a shortstringdef, because we don't have
  1154. functionality in place yet to reuse shortstringdefs of the same length
  1155. and neither the lowlevel nor the llvm typedconst builder cares about
  1156. this difference }
  1157. result:=carraydef.getreusable(cansichartype,length(str)+1);
  1158. maybe_begin_aggregate(result);
  1159. emit_tai(Tai_const.Create_8bit(length(str)),u8inttype);
  1160. if str<>'' then
  1161. emit_tai(Tai_string.Create(str),carraydef.getreusable(cansichartype,length(str)));
  1162. maybe_end_aggregate(result);
  1163. end;
  1164. procedure ttai_typedconstbuilder.emit_guid_const(const guid: tguid);
  1165. var
  1166. i: longint;
  1167. begin
  1168. maybe_begin_aggregate(rec_tguid);
  1169. { variant record -> must specify which fields get initialised }
  1170. next_field:=tfieldvarsym(rec_tguid.symtable.symlist[0]);
  1171. emit_tai(Tai_const.Create_32bit(longint(guid.D1)),u32inttype);
  1172. next_field:=tfieldvarsym(rec_tguid.symtable.symlist[1]);
  1173. emit_tai(Tai_const.Create_16bit(guid.D2),u16inttype);
  1174. next_field:=tfieldvarsym(rec_tguid.symtable.symlist[2]);
  1175. emit_tai(Tai_const.Create_16bit(guid.D3),u16inttype);
  1176. next_field:=tfieldvarsym(rec_tguid.symtable.symlist[3]);
  1177. { the array }
  1178. maybe_begin_aggregate(tfieldvarsym(rec_tguid.symtable.symlist[3]).vardef);
  1179. for i:=Low(guid.D4) to High(guid.D4) do
  1180. emit_tai(Tai_const.Create_8bit(guid.D4[i]),u8inttype);
  1181. maybe_end_aggregate(tfieldvarsym(rec_tguid.symtable.symlist[3]).vardef);
  1182. maybe_end_aggregate(rec_tguid);
  1183. end;
  1184. procedure ttai_typedconstbuilder.emit_procdef_const(pd: tprocdef);
  1185. begin
  1186. emit_tai(Tai_const.Createname(pd.mangledname,AT_FUNCTION,0),cprocvardef.getreusableprocaddr(pd));
  1187. end;
  1188. procedure ttai_typedconstbuilder.emit_ord_const(value: int64; def: tdef);
  1189. begin
  1190. case def.size of
  1191. 1:
  1192. emit_tai(Tai_const.Create_8bit(byte(value)),def);
  1193. 2:
  1194. emit_tai(Tai_const.Create_16bit(word(value)),def);
  1195. 4:
  1196. emit_tai(Tai_const.Create_32bit(longint(value)),def);
  1197. 8:
  1198. emit_tai(Tai_const.Create_64bit(value),def);
  1199. else
  1200. internalerror(2014100501);
  1201. end;
  1202. end;
  1203. procedure ttai_typedconstbuilder.maybe_begin_aggregate(def: tdef);
  1204. begin
  1205. begin_aggregate_internal(def,false);
  1206. end;
  1207. procedure ttai_typedconstbuilder.maybe_end_aggregate(def: tdef);
  1208. begin
  1209. end_aggregate_internal(def,false);
  1210. end;
  1211. function ttai_typedconstbuilder.begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef;
  1212. var
  1213. anonrecorddef: trecorddef;
  1214. typesym: ttypesym;
  1215. begin
  1216. { if the name is specified, we create a typesym with that name in order
  1217. to ensure we can find it again later with that name -> reuse here as
  1218. well if possible (and that also avoids duplicate type name issues) }
  1219. if optionalname<>'' then
  1220. begin
  1221. typesym:=try_search_current_module_type(optionalname);
  1222. if assigned(typesym) then
  1223. begin
  1224. if typesym.typedef.typ<>recorddef then
  1225. internalerror(2015071401);
  1226. result:=trecorddef(typesym.typedef);
  1227. maybe_begin_aggregate(result);
  1228. exit;
  1229. end;
  1230. end;
  1231. { create skeleton def }
  1232. anonrecorddef:=crecorddef.create_global_internal(optionalname,packrecords,recordalignmin,maxcrecordalign);
  1233. trecordsymtable(anonrecorddef.symtable).recordalignment:=recordalign;
  1234. { generic aggregate housekeeping }
  1235. begin_aggregate_internal(anonrecorddef,true);
  1236. { mark as anonymous record }
  1237. curagginfo.anonrecord:=true;
  1238. { in case a descendent wants to do something with the anonrecorddef too }
  1239. result:=anonrecorddef;
  1240. end;
  1241. function ttai_typedconstbuilder.end_anonymous_record: trecorddef;
  1242. var
  1243. info: taggregateinformation;
  1244. anonrecord: boolean;
  1245. begin
  1246. info:=curagginfo;
  1247. if not assigned(info) or
  1248. (info.def.typ<>recorddef) then
  1249. internalerror(2014080201);
  1250. result:=trecorddef(info.def);
  1251. { make a copy, as we need it after info has been freed by
  1252. maybe_end_aggregate(result) }
  1253. anonrecord:=info.anonrecord;
  1254. { finalise the record skeleton (all fields have been added already by
  1255. emit_tai()) -- anonrecord may not be set in case we reused an earlier
  1256. constructed def }
  1257. if anonrecord then
  1258. trecordsymtable(result.symtable).addalignmentpadding;
  1259. end_aggregate_internal(result,true);
  1260. if anonrecord and
  1261. assigned(curagginfo) and
  1262. (curagginfo.def.typ=recorddef) then
  1263. insert_marked_aggregate_alignment(result);
  1264. end;
  1265. procedure ttai_typedconstbuilder.queue_init(todef: tdef);
  1266. var
  1267. info: taggregateinformation;
  1268. begin
  1269. { nested call to init? }
  1270. if fqueue_offset<>low(fqueue_offset) then
  1271. internalerror(2014062101);
  1272. { insert padding bytes before starting the queue, so that the first
  1273. padding byte won't be interpreted as the emitted value for this queue }
  1274. info:=curagginfo;
  1275. if assigned(info) then
  1276. begin
  1277. if ((info.def.typ=recorddef) or
  1278. is_object(info.def)) and
  1279. { may add support for these later }
  1280. not is_packed_record_or_object(info.def) then
  1281. pad_next_field(todef);
  1282. end;
  1283. fqueue_offset:=0;
  1284. fqueued_def:=todef;
  1285. end;
  1286. procedure ttai_typedconstbuilder.queue_vecn(def: tdef; const index: tconstexprint);
  1287. var
  1288. elelen,
  1289. vecbase: asizeint;
  1290. v: tconstexprint;
  1291. begin
  1292. elelen:=1;
  1293. vecbase:=0;
  1294. case def.typ of
  1295. stringdef :
  1296. ;
  1297. arraydef :
  1298. begin
  1299. if not is_packed_array(def) then
  1300. begin
  1301. elelen:=tarraydef(def).elesize;
  1302. vecbase:=tarraydef(def).lowrange;
  1303. end
  1304. else
  1305. Message(parser_e_packed_dynamic_open_array);
  1306. end;
  1307. else
  1308. Message(parser_e_illegal_expression);
  1309. end;
  1310. { Prevent overflow }
  1311. v:=index-vecbase;
  1312. if (v<int64(low(fqueue_offset))) or (v>int64(high(fqueue_offset))) then
  1313. message3(type_e_range_check_error_bounds,tostr(v),tostr(low(fqueue_offset)),tostr(high(fqueue_offset)));
  1314. if high(fqueue_offset)-fqueue_offset div elelen>v then
  1315. inc(fqueue_offset,elelen*v.svalue)
  1316. else
  1317. message3(type_e_range_check_error_bounds,tostr(index),tostr(vecbase),tostr(high(fqueue_offset)-fqueue_offset div elelen+vecbase))
  1318. end;
  1319. procedure ttai_typedconstbuilder.queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym);
  1320. begin
  1321. inc(fqueue_offset,vs.fieldoffset);
  1322. end;
  1323. function ttai_typedconstbuilder.queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  1324. var
  1325. syms,
  1326. parentdefs: tfplist;
  1327. sym: tsym;
  1328. curdef: tdef;
  1329. i: longint;
  1330. begin
  1331. result:=nil;
  1332. if length(fields)=0 then
  1333. internalerror(2015071601);
  1334. syms:=tfplist.Create;
  1335. syms.count:=length(fields);
  1336. parentdefs:=tfplist.create;
  1337. parentdefs.Count:=length(fields);
  1338. curdef:=def;
  1339. for i:=low(fields) to high(fields) do
  1340. begin
  1341. sym:=search_struct_member_no_helper(tabstractrecorddef(curdef),fields[i]);
  1342. if not assigned(sym) or
  1343. (sym.typ<>fieldvarsym) or
  1344. ((i<>high(fields)) and
  1345. not(tfieldvarsym(sym).vardef.typ in [objectdef,recorddef])) then
  1346. internalerror(2015071505);
  1347. syms[i]:=sym;
  1348. parentdefs[i]:=curdef;
  1349. curdef:=tfieldvarsym(sym).vardef;
  1350. result:=curdef;
  1351. end;
  1352. for i:=high(fields) downto low(fields) do
  1353. queue_subscriptn(tabstractrecorddef(parentdefs[i]),tfieldvarsym(syms[i]));
  1354. syms.free;
  1355. parentdefs.free;
  1356. end;
  1357. procedure ttai_typedconstbuilder.queue_typeconvn(fromdef, todef: tdef);
  1358. begin
  1359. { do nothing }
  1360. end;
  1361. procedure ttai_typedconstbuilder.queue_emit_proc(pd: tprocdef);
  1362. begin
  1363. if fqueue_offset<>0 then
  1364. internalerror(2014092101);
  1365. emit_procdef_const(pd);
  1366. fqueue_offset:=low(fqueue_offset);
  1367. end;
  1368. procedure ttai_typedconstbuilder.queue_emit_staticvar(vs: tstaticvarsym);
  1369. begin
  1370. { pointerdef because we are emitting a pointer to the staticvarsym
  1371. data, not the data itself }
  1372. emit_tai(Tai_const.Createname(vs.mangledname,fqueue_offset),cpointerdef.getreusable(vs.vardef));
  1373. fqueue_offset:=low(fqueue_offset);
  1374. end;
  1375. procedure ttai_typedconstbuilder.queue_emit_label(l: tlabelsym);
  1376. begin
  1377. emit_tai(Tai_const.Createname(l.mangledname,fqueue_offset),voidcodepointertype);
  1378. fqueue_offset:=low(fqueue_offset);
  1379. end;
  1380. procedure ttai_typedconstbuilder.queue_emit_const(cs: tconstsym);
  1381. begin
  1382. if cs.consttyp<>constresourcestring then
  1383. internalerror(2014062102);
  1384. if fqueue_offset<>0 then
  1385. internalerror(2014062103);
  1386. { warning: update if/when the type of resource strings changes }
  1387. emit_tai(Tai_const.Createname(make_mangledname('RESSTR',cs.owner,cs.name),AT_DATA,sizeof(pint)),cansistringtype);
  1388. fqueue_offset:=low(fqueue_offset);
  1389. end;
  1390. procedure ttai_typedconstbuilder.queue_emit_asmsym(sym: tasmsymbol; def: tdef);
  1391. begin
  1392. { pointerdef, because "sym" represents the address of whatever the
  1393. data is }
  1394. def:=cpointerdef.getreusable(def);
  1395. emit_tai(Tai_const.Create_sym_offset(sym,fqueue_offset),def);
  1396. fqueue_offset:=low(fqueue_offset);
  1397. end;
  1398. procedure ttai_typedconstbuilder.queue_emit_ordconst(value: int64; def: tdef);
  1399. begin
  1400. emit_ord_const(value,def);
  1401. fqueue_offset:=low(fqueue_offset);
  1402. end;
  1403. function ttai_typedconstbuilder.queue_is_active: boolean;
  1404. begin
  1405. result:=fqueue_offset<>low(fqueue_offset)
  1406. end;
  1407. {****************************************************************************
  1408. tai_abstracttypedconst
  1409. ****************************************************************************}
  1410. class constructor ttai_lowleveltypedconstbuilder.classcreate;
  1411. begin
  1412. caggregateinformation:=tlowlevelaggregateinformation;
  1413. end;
  1414. procedure ttai_lowleveltypedconstbuilder.mark_anon_aggregate_alignment;
  1415. var
  1416. marker: tai_marker;
  1417. begin
  1418. marker:=tai_marker.Create(mark_position);
  1419. fasmlist.concat(marker);
  1420. tlowlevelaggregateinformation(curagginfo).anonrecmarker:=marker;
  1421. end;
  1422. procedure ttai_lowleveltypedconstbuilder.insert_marked_aggregate_alignment(def: tdef);
  1423. var
  1424. info: tlowlevelaggregateinformation;
  1425. fillbytes: asizeint;
  1426. begin
  1427. info:=tlowlevelaggregateinformation(curagginfo);
  1428. if not assigned(info.anonrecmarker) then
  1429. internalerror(2014091401);
  1430. fillbytes:=info.prepare_next_field(def);
  1431. while fillbytes>0 do
  1432. begin
  1433. fasmlist.insertafter(tai_const.create_8bit(0),info.anonrecmarker);
  1434. dec(fillbytes);
  1435. end;
  1436. fasmlist.remove(info.anonrecmarker);
  1437. info.anonrecmarker.free;
  1438. info.anonrecmarker:=nil;
  1439. end;
  1440. begin
  1441. ctai_typedconstbuilder:=ttai_lowleveltypedconstbuilder;
  1442. end.