aasmcnst.pas 65 KB

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