psub.pas 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl, Daniel Mantione
  3. Does the parsing and codegeneration at subroutine level
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit psub;
  18. {$i fpcdefs.inc}
  19. { $define debug_eh}
  20. interface
  21. uses
  22. globals,cclasses,
  23. node,nbas,nutils,
  24. symdef,procinfo,optdfa;
  25. type
  26. tcgprocinfo = class(tprocinfo)
  27. private type
  28. ttempinfo_flags_entry = record
  29. tempinfo : ptempinfo;
  30. flags : ttempinfoflags;
  31. end;
  32. ptempinfo_flags_entry = ^ttempinfo_flags_entry;
  33. private
  34. tempinfo_flags_map : TFPList;
  35. tempflags_swapped : boolean;
  36. procedure swap_tempflags;
  37. function store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  38. procedure CreateInlineInfo;
  39. { returns the node which is the start of the user code, this is needed by the dfa }
  40. function GetUserCode: tnode;
  41. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  42. procedure add_entry_exit_code;
  43. procedure setup_tempgen;
  44. procedure OptimizeNodeTree;
  45. public
  46. { code for the subroutine as tree }
  47. code : tnode;
  48. { positions in the tree for init/final }
  49. entry_asmnode,
  50. loadpara_asmnode,
  51. exitlabel_asmnode,
  52. stackcheck_asmnode,
  53. init_asmnode : tasmnode;
  54. temps_finalized : boolean;
  55. dfabuilder : TDFABuilder;
  56. destructor destroy;override;
  57. function calc_stackframe_size : longint;override;
  58. procedure printproc(pass:string);
  59. procedure generate_code;
  60. procedure generate_code_tree;
  61. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  62. procedure resetprocdef;
  63. procedure add_to_symtablestack;
  64. procedure remove_from_symtablestack;
  65. procedure parse_body;
  66. procedure store_tempflags;
  67. procedure apply_tempflags;
  68. procedure reset_tempflags;
  69. function has_assembler_child : boolean;
  70. procedure set_eh_info; override;
  71. {$ifdef DEBUG_NODE_XML}
  72. procedure XMLPrintProc;
  73. {$endif DEBUG_NODE_XML}
  74. end;
  75. procedure printnode_reset;
  76. {$ifdef DEBUG_NODE_XML}
  77. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  78. procedure XMLFinalizeNodeFile(RootName: shortstring);
  79. {$endif DEBUG_NODE_XML}
  80. { reads the declaration blocks }
  81. procedure read_declarations(islibrary : boolean);
  82. { reads declarations in the interface part of a unit }
  83. procedure read_interface_declarations;
  84. { reads any routine in the implementation, or a non-method routine
  85. declaration in the interface (depending on whether or not parse_only is
  86. true) }
  87. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  88. { parses only the body of a non nested routine; needs a correctly setup pd }
  89. procedure read_proc_body(pd:tprocdef);
  90. procedure import_external_proc(pd:tprocdef);
  91. implementation
  92. uses
  93. sysutils,
  94. { common }
  95. cutils, cmsgs,
  96. { global }
  97. globtype,tokens,verbose,comphook,constexp,
  98. systems,cpubase,aasmbase,aasmtai,aasmdata,
  99. { symtable }
  100. symconst,symbase,symsym,symtype,symtable,defutil,defcmp,symcreat,
  101. paramgr,
  102. fmodule,
  103. { pass 1 }
  104. ngenutil,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  105. pass_1,
  106. {$ifdef state_tracking}
  107. nstate,
  108. {$endif state_tracking}
  109. { pass 2 }
  110. {$ifndef NOPASS2}
  111. pass_2,
  112. {$endif}
  113. { parser }
  114. scanner,gendef,
  115. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,pparautl,
  116. { codegen }
  117. tgobj,cgbase,cgobj,hlcgobj,hlcgcpu,dbgbase,
  118. ncgflw,
  119. ncgutil,
  120. optbase,
  121. opttail,
  122. optcse,
  123. optloop,
  124. optconstprop,
  125. optdeadstore,
  126. optloadmodifystore,
  127. optutils
  128. {$if defined(arm)}
  129. ,cpuinfo
  130. {$endif arm}
  131. {$ifndef NOOPT}
  132. ,aopt
  133. {$endif}
  134. ;
  135. function checknodeinlining(procdef: tprocdef): boolean;
  136. procedure _no_inline(const reason: TMsgStr);
  137. begin
  138. include(procdef.implprocoptions,pio_inline_not_possible);
  139. Message1(parser_n_not_supported_for_inline,reason);
  140. Message(parser_h_inlining_disabled);
  141. end;
  142. var
  143. i : integer;
  144. currpara : tparavarsym;
  145. begin
  146. result := false;
  147. { this code will never be used (only specialisations can be inlined),
  148. and moreover contains references to defs that are not stored in the
  149. ppu file }
  150. if df_generic in current_procinfo.procdef.defoptions then
  151. exit;
  152. if pi_has_assembler_block in current_procinfo.flags then
  153. begin
  154. _no_inline('assembler');
  155. exit;
  156. end;
  157. if (pi_has_global_goto in current_procinfo.flags) or
  158. (pi_has_interproclabel in current_procinfo.flags) then
  159. begin
  160. _no_inline('global goto');
  161. exit;
  162. end;
  163. if pi_has_nested_exit in current_procinfo.flags then
  164. begin
  165. _no_inline('nested exit');
  166. exit;
  167. end;
  168. if pi_calls_c_varargs in current_procinfo.flags then
  169. begin
  170. _no_inline('called C-style varargs functions');
  171. exit;
  172. end;
  173. { the compiler cannot handle inherited in inlined subroutines because
  174. it tries to search for self in the symtable, however, the symtable
  175. is not available }
  176. if pi_has_inherited in current_procinfo.flags then
  177. begin
  178. _no_inline('inherited');
  179. exit;
  180. end;
  181. if pio_nested_access in procdef.implprocoptions then
  182. begin
  183. _no_inline('access to local from nested scope');
  184. exit;
  185. end;
  186. { We can't support inlining for procedures that have nested
  187. procedures because the nested procedures use a fixed offset
  188. for accessing locals in the parent procedure (PFV) }
  189. if current_procinfo.has_nestedprocs then
  190. begin
  191. _no_inline('nested procedures');
  192. exit;
  193. end;
  194. if pi_uses_get_frame in current_procinfo.flags then
  195. begin
  196. _no_inline('get_frame');
  197. { for LLVM: it can inline things that FPC can't, but it mustn't
  198. inline this one }
  199. include(current_procinfo.procdef.implprocoptions,pio_inline_forbidden);
  200. exit;
  201. end;
  202. for i:=0 to procdef.paras.count-1 do
  203. begin
  204. currpara:=tparavarsym(procdef.paras[i]);
  205. case currpara.vardef.typ of
  206. formaldef :
  207. begin
  208. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  209. begin
  210. _no_inline('formal parameter');
  211. exit;
  212. end;
  213. end;
  214. arraydef :
  215. begin
  216. if is_array_of_const(currpara.vardef) or
  217. is_variant_array(currpara.vardef) then
  218. begin
  219. _no_inline('array of const');
  220. exit;
  221. end;
  222. { open arrays might need re-basing of the index, i.e. if you pass
  223. an array[1..10] as open array, you have to add 1 to all index operations
  224. if you directly inline it }
  225. if is_open_array(currpara.vardef) then
  226. begin
  227. _no_inline('open array');
  228. exit;
  229. end;
  230. end;
  231. else
  232. ;
  233. end;
  234. end;
  235. result:=true;
  236. end;
  237. {****************************************************************************
  238. PROCEDURE/FUNCTION BODY PARSING
  239. ****************************************************************************}
  240. procedure initializedefaultvars(p:TObject;arg:pointer);
  241. var
  242. b : tblocknode;
  243. begin
  244. if tsym(p).typ<>localvarsym then
  245. exit;
  246. with tabstractnormalvarsym(p) do
  247. begin
  248. if (vo_is_default_var in varoptions) and (vardef.size>0) then
  249. begin
  250. b:=tblocknode(arg);
  251. b.left:=cstatementnode.create(
  252. ccallnode.createintern('fpc_zeromem',
  253. ccallparanode.create(
  254. cordconstnode.create(vardef.size,sizeuinttype,false),
  255. ccallparanode.create(
  256. caddrnode.create_internal(
  257. cloadnode.create(tsym(p),tsym(p).owner)),
  258. nil
  259. )
  260. )
  261. ),
  262. b.left);
  263. end;
  264. end;
  265. end;
  266. procedure initializevars(p:TObject;arg:pointer);
  267. var
  268. b : tblocknode;
  269. begin
  270. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  271. exit;
  272. with tabstractnormalvarsym(p) do
  273. begin
  274. if assigned(defaultconstsym) then
  275. begin
  276. b:=tblocknode(arg);
  277. b.left:=cstatementnode.create(
  278. cassignmentnode.create(
  279. cloadnode.create(tsym(p),tsym(p).owner),
  280. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  281. b.left);
  282. end
  283. else
  284. initializedefaultvars(p,arg);
  285. end;
  286. end;
  287. procedure check_finalize_paras(p:TObject;arg:pointer);
  288. begin
  289. if (tsym(p).typ=paravarsym) then
  290. begin
  291. if tparavarsym(p).needs_finalization then
  292. begin
  293. include(current_procinfo.flags,pi_needs_implicit_finally);
  294. include(current_procinfo.flags,pi_do_call);
  295. end;
  296. end;
  297. end;
  298. procedure check_finalize_locals(p:TObject;arg:pointer);
  299. begin
  300. { include the result: it needs to be finalized in case an exception }
  301. { occurs }
  302. if (tsym(p).typ=localvarsym) and
  303. (tlocalvarsym(p).refs>0) and
  304. is_managed_type(tlocalvarsym(p).vardef) then
  305. begin
  306. include(current_procinfo.flags,pi_needs_implicit_finally);
  307. include(current_procinfo.flags,pi_do_call);
  308. end;
  309. end;
  310. procedure init_main_block_syms(block: tnode);
  311. var
  312. oldfilepos: tfileposinfo;
  313. begin
  314. { initialized variables }
  315. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  316. begin
  317. { initialization of local variables with their initial
  318. values: part of function entry }
  319. oldfilepos:=current_filepos;
  320. current_filepos:=current_procinfo.entrypos;
  321. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  322. current_filepos:=oldfilepos;
  323. end
  324. else if current_procinfo.procdef.localst.symtabletype=staticsymtable then
  325. begin
  326. { for program and unit initialization code we also need to
  327. initialize the local variables used of Default() }
  328. oldfilepos:=current_filepos;
  329. current_filepos:=current_procinfo.entrypos;
  330. current_procinfo.procdef.localst.SymList.ForEachCall(@initializedefaultvars,block);
  331. current_filepos:=oldfilepos;
  332. end;
  333. if assigned(current_procinfo.procdef.parentfpstruct) then
  334. begin
  335. { we only do this after the code has been parsed because
  336. otherwise for-loop counters moved to the struct cause
  337. errors; we still do it nevertheless to prevent false
  338. "unused" symbols warnings and to assist debug info
  339. generation }
  340. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  341. { finish the parentfpstruct (add padding, ...) }
  342. finish_parentfpstruct(current_procinfo.procdef);
  343. end;
  344. end;
  345. function block(islibrary : boolean) : tnode;
  346. begin
  347. { parse const,types and vars }
  348. read_declarations(islibrary);
  349. { do we have an assembler block without the po_assembler?
  350. we should allow this for Delphi compatibility (PFV) }
  351. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  352. include(current_procinfo.procdef.procoptions,po_assembler);
  353. { Handle assembler block different }
  354. if (po_assembler in current_procinfo.procdef.procoptions) then
  355. begin
  356. block:=assembler_block;
  357. exit;
  358. end;
  359. {Unit initialization?.}
  360. if (
  361. assigned(current_procinfo.procdef.localst) and
  362. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  363. (current_module.is_unit or islibrary)
  364. ) then
  365. begin
  366. if (token=_END) then
  367. begin
  368. consume(_END);
  369. { We need at least a node, else the entry/exit code is not
  370. generated and thus no PASCALMAIN symbol which we need (PFV) }
  371. if islibrary then
  372. block:=cnothingnode.create
  373. else
  374. block:=nil;
  375. end
  376. else
  377. begin
  378. if token=_INITIALIZATION then
  379. begin
  380. { The library init code is already called and does not
  381. need to be in the initfinal table (PFV) }
  382. block:=statement_block(_INITIALIZATION);
  383. end
  384. else if token=_FINALIZATION then
  385. begin
  386. { when a unit has only a finalization section, we can come to this
  387. point when we try to read the nonh existing initalization section
  388. so we've to check if we are really try to parse the finalization }
  389. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  390. block:=statement_block(_FINALIZATION)
  391. else
  392. block:=nil;
  393. end
  394. else
  395. block:=statement_block(_BEGIN);
  396. end;
  397. end
  398. else
  399. begin
  400. { parse routine body }
  401. block:=statement_block(_BEGIN);
  402. init_main_block_syms(block);
  403. end;
  404. end;
  405. {****************************************************************************
  406. PROCEDURE/FUNCTION COMPILING
  407. ****************************************************************************}
  408. procedure printnode_reset;
  409. begin
  410. assign(printnodefile,treelogfilename);
  411. {$push}{$I-}
  412. rewrite(printnodefile);
  413. {$pop}
  414. if ioresult<>0 then
  415. begin
  416. Comment(V_Error,'Error creating '+treelogfilename);
  417. exit;
  418. end;
  419. close(printnodefile);
  420. end;
  421. procedure add_label_init(p:TObject;arg:pointer);
  422. begin
  423. if tstoredsym(p).typ=labelsym then
  424. begin
  425. addstatement(tstatementnode(arg^),
  426. cifnode.create(caddnode.create(equaln,
  427. ccallnode.createintern('fpc_setjmp',
  428. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  429. cordconstnode.create(1,sinttype,true))
  430. ,cgotonode.create(tlabelsym(p)),nil)
  431. );
  432. end;
  433. end;
  434. function generate_bodyentry_block:tnode;
  435. var
  436. srsym : tsym;
  437. para : tcallparanode;
  438. call : tcallnode;
  439. newstatement : tstatementnode;
  440. def : tabstractrecorddef;
  441. begin
  442. result:=internalstatements(newstatement);
  443. if assigned(current_structdef) then
  444. begin
  445. { a constructor needs a help procedure }
  446. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  447. begin
  448. if is_class(current_structdef) or
  449. (
  450. is_objectpascal_helper(current_structdef) and
  451. is_class(tobjectdef(current_structdef).extendeddef)
  452. ) then
  453. begin
  454. if is_objectpascal_helper(current_structdef) then
  455. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  456. else
  457. def:=current_structdef;
  458. srsym:=search_struct_member(def,'NEWINSTANCE');
  459. if assigned(srsym) and
  460. (srsym.typ=procsym) then
  461. begin
  462. { if vmt=1 then newinstance }
  463. addstatement(newstatement,cifnode.create(
  464. caddnode.create_internal(equaln,
  465. ctypeconvnode.create_internal(
  466. load_vmt_pointer_node,
  467. voidpointertype),
  468. cpointerconstnode.create(1,voidpointertype)),
  469. cassignmentnode.create(
  470. ctypeconvnode.create_internal(
  471. load_self_pointer_node,
  472. voidpointertype),
  473. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  474. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  475. [],nil)),
  476. nil));
  477. end
  478. else
  479. internalerror(200305108);
  480. end
  481. else
  482. if is_object(current_structdef) then
  483. begin
  484. { parameter 3 : vmt_offset }
  485. { parameter 2 : address of pointer to vmt,
  486. this is required to allow setting the vmt to -1 to indicate
  487. that memory was allocated }
  488. { parameter 1 : self pointer }
  489. para:=ccallparanode.create(
  490. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  491. ccallparanode.create(
  492. ctypeconvnode.create_internal(
  493. load_vmt_pointer_node,
  494. voidpointertype),
  495. ccallparanode.create(
  496. ctypeconvnode.create_internal(
  497. load_self_pointer_node,
  498. voidpointertype),
  499. nil)));
  500. addstatement(newstatement,cassignmentnode.create(
  501. ctypeconvnode.create_internal(
  502. load_self_pointer_node,
  503. voidpointertype),
  504. ccallnode.createintern('fpc_help_constructor',para)));
  505. end
  506. else
  507. if is_javaclass(current_structdef) or
  508. ((target_info.system in systems_jvm) and
  509. is_record(current_structdef)) then
  510. begin
  511. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  512. not current_procinfo.ConstructorCallingConstructor then
  513. begin
  514. { call inherited constructor }
  515. if is_javaclass(current_structdef) then
  516. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  517. else
  518. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  519. if assigned(srsym) and
  520. (srsym.typ=procsym) then
  521. begin
  522. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  523. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  524. addstatement(newstatement,call);
  525. end
  526. else
  527. internalerror(2011010312);
  528. end;
  529. end
  530. else
  531. if not is_record(current_structdef) and
  532. not (
  533. is_objectpascal_helper(current_structdef) and
  534. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  535. ) then
  536. internalerror(200305103);
  537. { if self=nil then exit
  538. calling fail instead of exit is useless because
  539. there is nothing to dispose (PFV) }
  540. if is_class_or_object(current_structdef) then
  541. addstatement(newstatement,cifnode.create(
  542. caddnode.create(equaln,
  543. load_self_pointer_node,
  544. cnilnode.create),
  545. cexitnode.create(nil),
  546. nil));
  547. end;
  548. { maybe call BeforeDestruction for classes }
  549. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  550. is_class(current_structdef) then
  551. begin
  552. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  553. if assigned(srsym) and
  554. (srsym.typ=procsym) then
  555. begin
  556. { if vmt>0 then beforedestruction }
  557. addstatement(newstatement,cifnode.create(
  558. caddnode.create(gtn,
  559. ctypeconvnode.create_internal(
  560. load_vmt_pointer_node,ptrsinttype),
  561. ctypeconvnode.create_internal(
  562. cnilnode.create,ptrsinttype)),
  563. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  564. nil));
  565. end
  566. else
  567. internalerror(200305104);
  568. end;
  569. end;
  570. if m_non_local_goto in current_settings.modeswitches then
  571. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  572. end;
  573. function generate_bodyexit_block:tnode;
  574. var
  575. srsym : tsym;
  576. para : tcallparanode;
  577. newstatement : tstatementnode;
  578. oldlocalswitches: tlocalswitches;
  579. begin
  580. result:=internalstatements(newstatement);
  581. if assigned(current_structdef) then
  582. begin
  583. { Don't test self and the vmt here. The reason is that }
  584. { a constructor already checks whether these are valid }
  585. { before. Further, in case of TThread the thread may }
  586. { free the class instance right after AfterConstruction }
  587. { has been called, so it may no longer be valid (JM) }
  588. oldlocalswitches:=current_settings.localswitches;
  589. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  590. { a destructor needs a help procedure }
  591. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  592. begin
  593. if is_class(current_structdef) then
  594. begin
  595. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  596. if assigned(srsym) and
  597. (srsym.typ=procsym) then
  598. begin
  599. { if self<>0 and vmt<>0 then freeinstance }
  600. addstatement(newstatement,cifnode.create(
  601. caddnode.create(andn,
  602. caddnode.create(unequaln,
  603. load_self_pointer_node,
  604. cnilnode.create),
  605. caddnode.create(unequaln,
  606. ctypeconvnode.create(
  607. load_vmt_pointer_node,
  608. voidpointertype),
  609. cpointerconstnode.create(0,voidpointertype))),
  610. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  611. nil));
  612. end
  613. else
  614. internalerror(200305108);
  615. end
  616. else
  617. if is_object(current_structdef) then
  618. begin
  619. { finalize object data, but only if not in inherited call }
  620. if is_managed_type(current_structdef) then
  621. begin
  622. addstatement(newstatement,cifnode.create(
  623. caddnode.create(unequaln,
  624. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  625. cnilnode.create),
  626. cnodeutils.finalize_data_node(load_self_node),
  627. nil));
  628. end;
  629. { parameter 3 : vmt_offset }
  630. { parameter 2 : pointer to vmt }
  631. { parameter 1 : self pointer }
  632. para:=ccallparanode.create(
  633. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  634. ccallparanode.create(
  635. ctypeconvnode.create_internal(
  636. load_vmt_pointer_node,
  637. voidpointertype),
  638. ccallparanode.create(
  639. ctypeconvnode.create_internal(
  640. load_self_pointer_node,
  641. voidpointertype),
  642. nil)));
  643. addstatement(newstatement,
  644. ccallnode.createintern('fpc_help_destructor',para));
  645. end
  646. else if is_javaclass(current_structdef) then
  647. begin
  648. { nothing to do }
  649. end
  650. else
  651. internalerror(200305105);
  652. end;
  653. current_settings.localswitches:=oldlocalswitches;
  654. end;
  655. end;
  656. {****************************************************************************
  657. TCGProcInfo
  658. ****************************************************************************}
  659. destructor tcgprocinfo.destroy;
  660. var
  661. i : longint;
  662. begin
  663. if assigned(tempinfo_flags_map) then
  664. begin
  665. for i:=0 to tempinfo_flags_map.count-1 do
  666. dispose(ptempinfo_flags_entry(tempinfo_flags_map[i]));
  667. tempinfo_flags_map.free;
  668. end;
  669. code.free;
  670. inherited destroy;
  671. end;
  672. function tcgprocinfo.calc_stackframe_size:longint;
  673. begin
  674. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  675. end;
  676. procedure tcgprocinfo.printproc(pass:string);
  677. begin
  678. assign(printnodefile,treelogfilename);
  679. {$push}{$I-}
  680. append(printnodefile);
  681. if ioresult<>0 then
  682. rewrite(printnodefile);
  683. {$pop}
  684. if ioresult<>0 then
  685. begin
  686. Comment(V_Error,'Error creating '+treelogfilename);
  687. exit;
  688. end;
  689. writeln(printnodefile);
  690. writeln(printnodefile,'*******************************************************************************');
  691. writeln(printnodefile, pass);
  692. writeln(printnodefile,procdef.fullprocname(false));
  693. writeln(printnodefile,'*******************************************************************************');
  694. printnode(printnodefile,code);
  695. close(printnodefile);
  696. end;
  697. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  698. var
  699. oldlocalswitches: tlocalswitches;
  700. srsym: tsym;
  701. constructionblock,
  702. exceptblock,
  703. newblock: tblocknode;
  704. newstatement: tstatementnode;
  705. pd: tprocdef;
  706. constructionsuccessful: tlocalvarsym;
  707. begin
  708. if assigned(procdef.struct) and
  709. (procdef.proctypeoption=potype_constructor) then
  710. begin
  711. withexceptblock:=
  712. withexceptblock and
  713. not(target_info.system in systems_garbage_collected_managed_types);
  714. { Don't test self and the vmt here. See generate_bodyexit_block }
  715. { why (JM) }
  716. oldlocalswitches:=current_settings.localswitches;
  717. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  718. { call AfterConstruction for classes }
  719. constructionsuccessful:=nil;
  720. if is_class(procdef.struct) then
  721. begin
  722. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[]);
  723. procdef.localst.insert(constructionsuccessful,false);
  724. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  725. if not assigned(srsym) or
  726. (srsym.typ<>procsym) then
  727. internalerror(200305106);
  728. current_filepos:=entrypos;
  729. constructionblock:=internalstatements(newstatement);
  730. { initialise constructionsuccessful with -1, indicating that
  731. the construction was not successful and hence
  732. beforedestruction should not be called if a destructor is
  733. called from the constructor }
  734. addstatement(newstatement,cassignmentnode.create(
  735. cloadnode.create(constructionsuccessful,procdef.localst),
  736. genintconstnode(-1))
  737. );
  738. { first execute all constructor code. If no exception
  739. occurred then we will execute afterconstruction,
  740. otherwise we won't (the exception will jump over us) }
  741. addstatement(newstatement,tocode);
  742. current_filepos:=exitpos;
  743. { if implicit finally node wasn't created, then exit label and
  744. finalization code must be handled here and placed before
  745. afterconstruction }
  746. if not ((pi_needs_implicit_finally in flags) and
  747. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  748. begin
  749. include(tocode.flags,nf_block_with_exit);
  750. if procdef.proctypeoption<>potype_exceptfilter then
  751. addstatement(newstatement,cfinalizetempsnode.create);
  752. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  753. temps_finalized:=true;
  754. end;
  755. { construction successful -> beforedestruction should be called
  756. if an exception happens now }
  757. addstatement(newstatement,cassignmentnode.create(
  758. cloadnode.create(constructionsuccessful,procdef.localst),
  759. genintconstnode(1))
  760. );
  761. { Self can be nil when fail is called }
  762. { if self<>nil and vmt<>nil then afterconstruction }
  763. addstatement(newstatement,cifnode.create(
  764. caddnode.create(andn,
  765. caddnode.create(unequaln,
  766. load_self_node,
  767. cnilnode.create),
  768. caddnode.create(unequaln,
  769. load_vmt_pointer_node,
  770. cnilnode.create)),
  771. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  772. nil));
  773. tocode:=constructionblock;
  774. end;
  775. if withexceptblock and (procdef.struct.typ=objectdef) then
  776. begin
  777. { Generate the implicit "fail" code for a constructor (destroy
  778. in case an exception happened) }
  779. pd:=tobjectdef(procdef.struct).find_destructor;
  780. { this will always be the case for classes, since tobject has
  781. a destructor }
  782. if assigned(pd) or is_object(procdef.struct) then
  783. begin
  784. current_filepos:=exitpos;
  785. exceptblock:=internalstatements(newstatement);
  786. { first free the instance if non-nil }
  787. if assigned(pd) then
  788. { if vmt<>0 then call destructor }
  789. addstatement(newstatement,
  790. cifnode.create(
  791. caddnode.create(unequaln,
  792. load_vmt_pointer_node,
  793. cnilnode.create),
  794. { cnf_create_failed -> don't call BeforeDestruction }
  795. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  796. nil))
  797. else
  798. { object without destructor, call 'fail' helper }
  799. addstatement(newstatement,
  800. ccallnode.createintern('fpc_help_fail',
  801. ccallparanode.create(
  802. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  803. ccallparanode.create(
  804. ctypeconvnode.create_internal(
  805. load_vmt_pointer_node,
  806. voidpointertype),
  807. ccallparanode.create(
  808. ctypeconvnode.create_internal(
  809. load_self_pointer_node,
  810. voidpointertype),
  811. nil))))
  812. );
  813. { then re-raise the exception }
  814. addstatement(newstatement,craisenode.create(nil,nil,nil));
  815. current_filepos:=entrypos;
  816. newblock:=internalstatements(newstatement);
  817. { try
  818. tocode
  819. except
  820. exceptblock
  821. end
  822. }
  823. addstatement(newstatement,ctryexceptnode.create(
  824. tocode,
  825. nil,
  826. exceptblock));
  827. tocode:=newblock;
  828. end;
  829. end;
  830. current_settings.localswitches:=oldlocalswitches;
  831. end;
  832. end;
  833. procedure tcgprocinfo.add_entry_exit_code;
  834. var
  835. finalcode,
  836. bodyentrycode,
  837. bodyexitcode,
  838. wrappedbody,
  839. newblock : tnode;
  840. codestatement,
  841. newstatement : tstatementnode;
  842. oldfilepos : tfileposinfo;
  843. is_constructor: boolean;
  844. begin
  845. is_constructor:=assigned(procdef.struct) and
  846. (procdef.proctypeoption=potype_constructor);
  847. oldfilepos:=current_filepos;
  848. { Generate code/locations used at start of proc }
  849. current_filepos:=entrypos;
  850. entry_asmnode:=casmnode.create_get_position;
  851. loadpara_asmnode:=casmnode.create_get_position;
  852. stackcheck_asmnode:=casmnode.create_get_position;
  853. init_asmnode:=casmnode.create_get_position;
  854. bodyentrycode:=generate_bodyentry_block;
  855. { Generate code/locations used at end of proc }
  856. current_filepos:=exitpos;
  857. exitlabel_asmnode:=casmnode.create_get_position;
  858. temps_finalized:=false;
  859. bodyexitcode:=generate_bodyexit_block;
  860. { Generate procedure by combining init+body+final,
  861. depending on the implicit finally we need to add
  862. an try...finally...end wrapper }
  863. current_filepos:=entrypos;
  864. newblock:=internalstatements(newstatement);
  865. { initialization is common for all cases }
  866. addstatement(newstatement,loadpara_asmnode);
  867. addstatement(newstatement,stackcheck_asmnode);
  868. addstatement(newstatement,entry_asmnode);
  869. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  870. addstatement(newstatement,init_asmnode);
  871. if assigned(procdef.parentfpinitblock) then
  872. begin
  873. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  874. begin
  875. { could be an asmn in case of a pure assembler procedure,
  876. but those shouldn't access nested variables }
  877. addstatement(newstatement,procdef.parentfpinitblock);
  878. end
  879. else
  880. procdef.parentfpinitblock.free;
  881. procdef.parentfpinitblock:=nil;
  882. end;
  883. addstatement(newstatement,bodyentrycode);
  884. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  885. (pi_needs_implicit_finally in flags) and
  886. { but it's useless in init/final code of units }
  887. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  888. not(target_info.system in systems_garbage_collected_managed_types) and
  889. (f_exceptions in features) then
  890. begin
  891. { Any result of managed type must be returned in parameter }
  892. if is_managed_type(procdef.returndef) and
  893. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  894. (not is_class(procdef.returndef)) then
  895. InternalError(2013121301);
  896. { Generate special exception block only needed when
  897. implicit finaly is used }
  898. current_filepos:=exitpos;
  899. { Generate code that will be in the try...finally }
  900. finalcode:=internalstatements(codestatement);
  901. if procdef.proctypeoption<>potype_exceptfilter then
  902. addstatement(codestatement,cfinalizetempsnode.create);
  903. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  904. temps_finalized:=true;
  905. current_filepos:=entrypos;
  906. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  907. { afterconstruction must be called after finalizetemps, because it
  908. has to execute after the temps have been finalised in case of a
  909. refcounted class (afterconstruction decreases the refcount
  910. without freeing the instance if the count becomes nil, while
  911. the finalising of the temps can free the instance) }
  912. maybe_add_constructor_wrapper(wrappedbody,true);
  913. addstatement(newstatement,wrappedbody);
  914. addstatement(newstatement,exitlabel_asmnode);
  915. addstatement(newstatement,bodyexitcode);
  916. { set flag the implicit finally has been generated }
  917. include(flags,pi_has_implicit_finally);
  918. end
  919. else
  920. begin
  921. { constructors need destroy-on-exception code even if they don't
  922. have managed variables/temps }
  923. maybe_add_constructor_wrapper(code,
  924. (cs_implicit_exceptions in current_settings.moduleswitches) and (f_exceptions in features));
  925. current_filepos:=entrypos;
  926. addstatement(newstatement,code);
  927. current_filepos:=exitpos;
  928. if assigned(nestedexitlabel) then
  929. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  930. addstatement(newstatement,exitlabel_asmnode);
  931. addstatement(newstatement,bodyexitcode);
  932. if not is_constructor then
  933. begin
  934. if procdef.proctypeoption<>potype_exceptfilter then
  935. addstatement(newstatement,cfinalizetempsnode.create);
  936. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  937. temps_finalized:=true;
  938. end;
  939. end;
  940. if not temps_finalized then
  941. begin
  942. current_filepos:=exitpos;
  943. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  944. end;
  945. do_firstpass(newblock);
  946. code:=newblock;
  947. current_filepos:=oldfilepos;
  948. end;
  949. procedure clearrefs(p:TObject;arg:pointer);
  950. begin
  951. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  952. if tabstractvarsym(p).refs>1 then
  953. tabstractvarsym(p).refs:=1;
  954. end;
  955. procedure translate_registers(p:TObject;list:pointer);
  956. begin
  957. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  958. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  959. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  960. begin
  961. if not(cs_no_regalloc in current_settings.globalswitches) then
  962. begin
  963. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  964. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  965. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  966. end;
  967. end;
  968. end;
  969. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(riscv32) or defined(riscv64)}
  970. const
  971. exception_flags: array[boolean] of tprocinfoflags = (
  972. [],
  973. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  974. );
  975. {$endif}
  976. procedure tcgprocinfo.setup_tempgen;
  977. begin
  978. tg:=tgobjclass.create;
  979. {$if defined(i386) or defined(x86_64) or defined(arm)}
  980. {$if defined(arm)}
  981. { frame and stack pointer must be always the same on arm thumb so it makes no
  982. sense to fiddle with a frame pointer }
  983. if GenerateThumbCode then
  984. begin
  985. framepointer:=NR_STACK_POINTER_REG;
  986. tg.direction:=1;
  987. end
  988. else
  989. {$endif defined(arm)}
  990. begin
  991. { try to strip the stack frame }
  992. { set the framepointer to esp if:
  993. - no assembler directive, those are handled in assembler_block
  994. in pstatment.pas (for cases not caught by the Delphi
  995. exception below)
  996. - no exceptions are used
  997. - no pushes are used/esp modifications, could be:
  998. * outgoing parameters on the stack on non-fixed stack target
  999. * incoming parameters on the stack
  1000. * open arrays
  1001. - no inline assembler
  1002. or
  1003. - Delphi mode
  1004. - assembler directive
  1005. - no pushes are used/esp modifications, could be:
  1006. * outgoing parameters on the stack
  1007. * incoming parameters on the stack
  1008. * open arrays
  1009. - no local variables
  1010. - stack frame cannot be optimized if using Win64 SEH
  1011. (at least with the current state of our codegenerator).
  1012. }
  1013. if ((po_assembler in procdef.procoptions) and
  1014. (m_delphi in current_settings.modeswitches) and
  1015. { localst at main_program_level is a staticsymtable }
  1016. (procdef.localst.symtablelevel<>main_program_level) and
  1017. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  1018. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  1019. not(cs_generate_stackframes in current_settings.localswitches) and
  1020. not(cs_profile in current_settings.moduleswitches) and
  1021. not(po_assembler in procdef.procoptions) and
  1022. not ((pi_has_stackparameter in flags)
  1023. {$ifndef arm} { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  1024. with fixed stack. On ARM it fails, see bug #25050 }
  1025. and (not paramanager.use_fixed_stack)
  1026. {$endif arm}
  1027. ) and
  1028. ((flags*([pi_has_assembler_block,pi_is_assembler,
  1029. pi_needs_stackframe]+
  1030. exception_flags[((target_info.cpu=cpu_i386) and (not paramanager.use_fixed_stack))
  1031. {$ifndef DISABLE_WIN64_SEH}
  1032. or (target_info.system=system_x86_64_win64)
  1033. {$endif DISABLE_WIN64_SEH}
  1034. ]))=[])
  1035. )
  1036. then
  1037. begin
  1038. { we need the parameter info here to determine if the procedure gets
  1039. parameters on the stack
  1040. calling generate_parameter_info doesn't hurt but it costs time
  1041. (necessary to init para_stack_size)
  1042. }
  1043. generate_parameter_info;
  1044. if not(procdef.stack_tainting_parameter(calleeside)) and
  1045. not(has_assembler_child) {and (para_stack_size=0)} then
  1046. begin
  1047. { Only need to set the framepointer }
  1048. framepointer:=NR_STACK_POINTER_REG;
  1049. tg.direction:=1;
  1050. end
  1051. {$if defined(arm)}
  1052. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1053. in case parameters are passed on the stack.
  1054. However, the draw back is, if the estimation fails, compilation will break later on
  1055. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1056. multipass compilation of subroutines must be supported
  1057. }
  1058. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1059. not(has_assembler_child) then
  1060. begin
  1061. { Only need to set the framepointer }
  1062. framepointer:=NR_STACK_POINTER_REG;
  1063. tg.direction:=1;
  1064. include(flags,pi_estimatestacksize);
  1065. set_first_temp_offset;
  1066. procdef.has_paraloc_info:=callnoside;
  1067. generate_parameter_info;
  1068. exit;
  1069. end;
  1070. {$endif defined(arm)}
  1071. end;
  1072. end;
  1073. {$endif defined(x86) or defined(arm)}
  1074. { set the start offset to the start of the temp area in the stack }
  1075. set_first_temp_offset;
  1076. end;
  1077. procedure tcgprocinfo.OptimizeNodeTree;
  1078. var
  1079. i : integer;
  1080. RedoDFA: Boolean;
  1081. {RedoDFA : boolean;}
  1082. begin
  1083. { do this before adding the entry code else the tail recursion recognition won't work,
  1084. if this causes troubles, it must be if'ed
  1085. }
  1086. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1087. (pi_is_recursive in flags) then
  1088. do_opttail(code,procdef);
  1089. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1090. do_optconstpropagate(code);
  1091. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1092. { creating dfa is not always possible }
  1093. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1094. begin
  1095. dfabuilder:=TDFABuilder.Create;
  1096. dfabuilder.createdfainfo(code);
  1097. include(flags,pi_dfaavailable);
  1098. RedoDFA:=false;
  1099. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1100. { our induction variable strength reduction doesn't like
  1101. for loops with more than one entry }
  1102. and not(pi_has_label in flags) then
  1103. begin
  1104. RedoDFA:=OptimizeInductionVariables(code);
  1105. end;
  1106. if RedoDFA then
  1107. begin
  1108. dfabuilder.resetdfainfo(code);
  1109. dfabuilder.createdfainfo(code);
  1110. include(flags,pi_dfaavailable);
  1111. end;
  1112. RedoDFA:=OptimizeForLoop(code);
  1113. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1114. if RedoDFA then
  1115. begin
  1116. dfabuilder.resetdfainfo(code);
  1117. dfabuilder.createdfainfo(code);
  1118. include(flags,pi_dfaavailable);
  1119. end;
  1120. { when life info is available, we can give more sophisticated warning about uninitialized
  1121. variables ...
  1122. ... but not for the finalization section of a unit, we would need global dfa to handle
  1123. it properly }
  1124. if potype_unitfinalize<>procdef.proctypeoption then
  1125. { iterate through life info of the first node }
  1126. for i:=0 to dfabuilder.nodemap.count-1 do
  1127. begin
  1128. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1129. begin
  1130. { do not warn for certain parameters: }
  1131. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1132. { do not warn about parameters passed by var }
  1133. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1134. { function result is passed by var but it must be initialized }
  1135. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1136. { do not warn about initialized hidden parameters }
  1137. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1138. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1139. end
  1140. else
  1141. begin
  1142. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1143. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1144. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1145. end;
  1146. end;
  1147. end
  1148. else
  1149. begin
  1150. ConvertForLoops(code);
  1151. end;
  1152. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1153. do_optdeadstoreelim(code);
  1154. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1155. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1156. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1157. procdef.isempty:=true;
  1158. end;
  1159. function tcgprocinfo.has_assembler_child : boolean;
  1160. var
  1161. hp : tprocinfo;
  1162. begin
  1163. result:=false;
  1164. hp:=get_first_nestedproc;
  1165. while assigned(hp) do
  1166. begin
  1167. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1168. begin
  1169. result:=true;
  1170. exit;
  1171. end;
  1172. hp:=tprocinfo(hp.next);
  1173. end;
  1174. end;
  1175. procedure tcgprocinfo.set_eh_info;
  1176. begin
  1177. inherited;
  1178. if (tf_use_psabieh in target_info.flags) and
  1179. ((pi_uses_exceptions in flags) or
  1180. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1181. (pi_needs_implicit_finally in flags))) or
  1182. (pi_has_except_table_data in flags) then
  1183. procdef.personality:=search_system_proc('_FPC_PSABIEH_PERSONALITY_V0');
  1184. end;
  1185. function tcgprocinfo.store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  1186. var
  1187. nodeset : THashSet absolute arg;
  1188. entry : ptempinfo_flags_entry;
  1189. i : longint;
  1190. hashsetitem: PHashSetItem;
  1191. begin
  1192. result:=fen_true;
  1193. case n.nodetype of
  1194. tempcreaten:
  1195. begin
  1196. {$ifdef EXTDEBUG}
  1197. comment(V_Debug,'keeping track of new temp node: '+hexstr(ttempbasenode(n).tempinfo));
  1198. {$endif EXTDEBUG}
  1199. nodeset.FindOrAdd(ttempbasenode(n).tempinfo,sizeof(pointer));
  1200. end;
  1201. tempdeleten:
  1202. begin
  1203. {$ifdef EXTDEBUG}
  1204. comment(V_Debug,'got temp delete node: '+hexstr(ttempbasenode(n).tempinfo));
  1205. {$endif EXTDEBUG}
  1206. { don't remove temp nodes so that outside code can know if some temp
  1207. was only created in here }
  1208. (*hashsetitem:=nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer));
  1209. if assigned(hashsetitem) then
  1210. begin
  1211. {$ifdef EXTDEBUG}
  1212. comment(V_Debug,'no longer keeping track of temp node');
  1213. {$endif EXTDEBUG}
  1214. writeln('no longer keeping track of temp node');
  1215. nodeset.Remove(hashsetitem);
  1216. end;*)
  1217. end;
  1218. temprefn:
  1219. begin
  1220. {$ifdef EXTDEBUG}
  1221. comment(V_Debug,'found temp ref node: '+hexstr(ttempbasenode(n).tempinfo));
  1222. {$endif EXTDEBUG}
  1223. if not assigned(nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer))) then
  1224. begin
  1225. for i:=0 to tempinfo_flags_map.count-1 do
  1226. begin
  1227. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1228. {$ifdef EXTDEBUG}
  1229. comment(V_Debug,'comparing with tempinfo: '+hexstr(entry^.tempinfo));
  1230. {$endif EXTDEBUG}
  1231. if entry^.tempinfo=ttempbasenode(n).tempinfo then
  1232. begin
  1233. {$ifdef EXTDEBUG}
  1234. comment(V_Debug,'temp node exists');
  1235. {$endif EXTDEBUG}
  1236. exit;
  1237. end;
  1238. end;
  1239. {$ifdef EXTDEBUG}
  1240. comment(V_Debug,'storing node');
  1241. {$endif EXTDEBUG}
  1242. new(entry);
  1243. entry^.tempinfo:=ttempbasenode(n).tempinfo;
  1244. entry^.flags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1245. tempinfo_flags_map.add(entry);
  1246. end
  1247. else
  1248. begin
  1249. {$ifdef EXTDEBUG}
  1250. comment(V_Debug,'ignoring node');
  1251. {$endif EXTDEBUG}
  1252. end;
  1253. end;
  1254. else
  1255. ;
  1256. end;
  1257. end;
  1258. procedure tcgprocinfo.store_tempflags;
  1259. var
  1260. nodeset : THashSet;
  1261. begin
  1262. if assigned(tempinfo_flags_map) then
  1263. internalerror(2020040601);
  1264. {$ifdef EXTDEBUG}
  1265. comment(V_Debug,'storing temp nodes of '+procdef.mangledname);
  1266. {$endif EXTDEBUG}
  1267. tempinfo_flags_map:=tfplist.create;
  1268. nodeset:=THashSet.Create(32,false,false);
  1269. foreachnode(code,@store_node_tempflags,nodeset);
  1270. nodeset.free;
  1271. end;
  1272. procedure tcgprocinfo.swap_tempflags;
  1273. var
  1274. entry : ptempinfo_flags_entry;
  1275. i : longint;
  1276. tempflags : ttempinfoflags;
  1277. begin
  1278. if not assigned(tempinfo_flags_map) then
  1279. exit;
  1280. for i:=0 to tempinfo_flags_map.count-1 do
  1281. begin
  1282. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1283. tempflags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1284. ttempinfoaccessor.settempinfoflags(entry^.tempinfo,entry^.flags);
  1285. entry^.flags:=tempflags;
  1286. end;
  1287. end;
  1288. procedure tcgprocinfo.apply_tempflags;
  1289. begin
  1290. if tempflags_swapped then
  1291. internalerror(2020040602);
  1292. swap_tempflags;
  1293. tempflags_swapped:=true;
  1294. end;
  1295. procedure tcgprocinfo.reset_tempflags;
  1296. begin
  1297. if not tempflags_swapped then
  1298. internalerror(2020040603);
  1299. swap_tempflags;
  1300. tempflags_swapped:=false;
  1301. end;
  1302. {$ifdef DEBUG_NODE_XML}
  1303. procedure tcgprocinfo.XMLPrintProc;
  1304. var
  1305. T: Text;
  1306. W: Word;
  1307. syssym: tsyssym;
  1308. procedure PrintType(Flag: string);
  1309. begin
  1310. Write(T, ' type="', Flag, '"');
  1311. end;
  1312. procedure PrintOption(Flag: string);
  1313. begin
  1314. WriteLn(T, PrintNodeIndention, '<option>', Flag, '</option>');
  1315. end;
  1316. begin
  1317. if current_module.ppxfilefail then
  1318. Exit;
  1319. Assign(T, current_module.ppxfilename);
  1320. {$push} {$I-}
  1321. Append(T);
  1322. if IOResult <> 0 then
  1323. begin
  1324. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  1325. current_module.ppxfilefail := True;
  1326. Exit;
  1327. end;
  1328. {$pop}
  1329. Write(T, PrintNodeIndention, '<subroutine');
  1330. { Check to see if the procedure is a class or object method }
  1331. if Assigned(procdef.struct) then
  1332. begin
  1333. if Assigned(procdef.struct.objrealname) then
  1334. Write(T, ' struct="', TNode.SanitiseXMLString(procdef.struct.objrealname^), '"')
  1335. else
  1336. Write(T, ' struct="&lt;NULL&gt;"');
  1337. end;
  1338. case procdef.proctypeoption of
  1339. potype_none: { Do nothing };
  1340. potype_procedure,
  1341. potype_function:
  1342. if po_classmethod in procdef.procoptions then
  1343. begin
  1344. if po_staticmethod in procdef.procoptions then
  1345. PrintType('static class method')
  1346. else
  1347. PrintType('class method');
  1348. end;
  1349. { Do nothing otherwise }
  1350. potype_proginit,
  1351. potype_unitinit:
  1352. PrintType('initialization');
  1353. potype_unitfinalize:
  1354. PrintType('finalization');
  1355. potype_constructor:
  1356. PrintType('constructor');
  1357. potype_destructor:
  1358. PrintType('destructor');
  1359. potype_operator:
  1360. PrintType('operator');
  1361. potype_class_constructor:
  1362. PrintType('class constructor');
  1363. potype_class_destructor:
  1364. PrintType('class destructor');
  1365. potype_propgetter:
  1366. PrintType('dispinterface getter');
  1367. potype_propsetter:
  1368. PrintType('dispinterface setter');
  1369. potype_exceptfilter:
  1370. PrintType('except filter');
  1371. potype_mainstub:
  1372. PrintType('main stub');
  1373. potype_libmainstub:
  1374. PrintType('library main stub');
  1375. potype_pkgstub:
  1376. PrintType('package stub');
  1377. end;
  1378. Write(T, ' name="', TNode.SanitiseXMLString(procdef.customprocname([pno_showhidden, pno_noclassmarker])), '"');
  1379. if po_hascallingconvention in procdef.procoptions then
  1380. Write(T, ' convention="', proccalloptionStr[procdef.proccalloption], '"');
  1381. WriteLn(T, '>');
  1382. PrintNodeIndent;
  1383. if Assigned(procdef.returndef) and not is_void(procdef.returndef) then
  1384. WriteLn(T, PrintNodeIndention, '<returndef>', TNode.SanitiseXMLString(procdef.returndef.typesymbolprettyname), '</returndef>');
  1385. if po_reintroduce in procdef.procoptions then
  1386. PrintOption('reintroduce');
  1387. if po_virtualmethod in procdef.procoptions then
  1388. PrintOption('virtual');
  1389. if po_finalmethod in procdef.procoptions then
  1390. PrintOption('final');
  1391. if po_overridingmethod in procdef.procoptions then
  1392. PrintOption('override');
  1393. if po_overload in procdef.procoptions then
  1394. PrintOption('overload');
  1395. if po_compilerproc in procdef.procoptions then
  1396. PrintOption('compilerproc');
  1397. if po_assembler in procdef.procoptions then
  1398. PrintOption('assembler');
  1399. if po_nostackframe in procdef.procoptions then
  1400. PrintOption('nostackframe');
  1401. if po_inline in procdef.procoptions then
  1402. PrintOption('inline');
  1403. if po_noreturn in procdef.procoptions then
  1404. PrintOption('noreturn');
  1405. if po_noinline in procdef.procoptions then
  1406. PrintOption('noinline');
  1407. if Assigned(Code) then
  1408. begin
  1409. WriteLn(T, PrintNodeIndention, '<code>');
  1410. PrintNodeIndent;
  1411. XMLPrintNode(T, Code);
  1412. PrintNodeUnindent;
  1413. WriteLn(T, PrintNodeIndention, '</code>');
  1414. end
  1415. else
  1416. WriteLn(T, PrintNodeIndention, '<code />');
  1417. PrintNodeUnindent;
  1418. WriteLn(T, PrintNodeIndention, '</subroutine>');
  1419. WriteLn(T); { Line for spacing }
  1420. Close(T);
  1421. end;
  1422. {$endif DEBUG_NODE_XML}
  1423. procedure tcgprocinfo.generate_code_tree;
  1424. var
  1425. hpi : tcgprocinfo;
  1426. begin
  1427. { generate code for this procedure }
  1428. generate_code;
  1429. { process nested procedures }
  1430. hpi:=tcgprocinfo(get_first_nestedproc);
  1431. while assigned(hpi) do
  1432. begin
  1433. hpi.generate_code_tree;
  1434. hpi:=tcgprocinfo(hpi.next);
  1435. end;
  1436. resetprocdef;
  1437. end;
  1438. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1439. which can be called by OS during stack unwind. This resembles nested procedures,
  1440. but finalizer procedures do not have their own local variables and work directly
  1441. with the stack frame of parent. In particular, the tempgen must be shared, so
  1442. 1) finalizer procedure is able to finalize temps of the parent,
  1443. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1444. allocated in stack frame of parent, so second-level finalizer procedures are
  1445. not needed.
  1446. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1447. procedure (after the parent) and have to do it inline.
  1448. This is called by platform-specific tryfinallynodes during pass2.
  1449. Here we put away the codegen (which carries the register allocator state), process
  1450. the 'nested' procedure, then restore previous cg and continue processing the parent
  1451. procedure. generate_code() will create another cg, but not another tempgen because
  1452. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1453. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1454. var
  1455. saved_cg: tcg;
  1456. saved_hlcg: thlcgobj;
  1457. {$ifdef cpu64bitalu}
  1458. saved_cg128 : tcg128;
  1459. {$else cpu64bitalu}
  1460. saved_cg64 : tcg64;
  1461. {$endif cpu64bitalu}
  1462. begin
  1463. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1464. InternalError(201201141);
  1465. { flush code generated this far }
  1466. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1467. { save the codegen }
  1468. saved_cg:=cg;
  1469. saved_hlcg:=hlcg;
  1470. cg:=nil;
  1471. hlcg:=nil;
  1472. {$ifdef cpu64bitalu}
  1473. saved_cg128:=cg128;
  1474. cg128:=nil;
  1475. {$else cpu64bitalu}
  1476. saved_cg64:=cg64;
  1477. cg64:=nil;
  1478. {$endif cpu64bitalu}
  1479. nestedpi.generate_code;
  1480. { prevents generating code the second time when processing nested procedures }
  1481. nestedpi.resetprocdef;
  1482. cg:=saved_cg;
  1483. hlcg:=saved_hlcg;
  1484. {$ifdef cpu64bitalu}
  1485. cg128:=saved_cg128;
  1486. {$else cpu64bitalu}
  1487. cg64:=saved_cg64;
  1488. {$endif cpu64bitalu}
  1489. add_reg_instruction_hook:[email protected]_reg_instruction;
  1490. end;
  1491. procedure TCGProcinfo.CreateInlineInfo;
  1492. begin
  1493. new(procdef.inlininginfo);
  1494. procdef.inlininginfo^.code:=code.getcopy;
  1495. procdef.inlininginfo^.flags:=flags;
  1496. { The blocknode needs to set an exit label }
  1497. if procdef.inlininginfo^.code.nodetype=blockn then
  1498. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1499. procdef.has_inlininginfo:=true;
  1500. export_local_ref_syms;
  1501. export_local_ref_defs;
  1502. end;
  1503. procedure searchthreadvar(p: TObject; arg: pointer);
  1504. var
  1505. i : longint;
  1506. pd : tprocdef;
  1507. begin
  1508. case tsym(p).typ of
  1509. staticvarsym :
  1510. begin
  1511. { local (procedure or unit) variables only need finalization
  1512. if they are used
  1513. }
  1514. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1515. ((tstaticvarsym(p).refs>0) or
  1516. { global (unit) variables always need finalization, since
  1517. they may also be used in another unit
  1518. }
  1519. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1520. (
  1521. (tstaticvarsym(p).varspez<>vs_const) or
  1522. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1523. ) and
  1524. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1525. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1526. is_managed_type(tstaticvarsym(p).vardef) then
  1527. include(current_procinfo.flags,pi_uses_threadvar);
  1528. end;
  1529. procsym :
  1530. begin
  1531. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1532. begin
  1533. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1534. if assigned(pd.localst) and
  1535. (pd.procsym=tprocsym(p)) and
  1536. (pd.localst.symtabletype<>staticsymtable) then
  1537. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1538. end;
  1539. end;
  1540. else
  1541. ;
  1542. end;
  1543. end;
  1544. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1545. begin
  1546. if nf_usercode_entry in n.flags then
  1547. begin
  1548. pnode(arg)^:=n;
  1549. result:=fen_norecurse_true
  1550. end
  1551. else
  1552. result:=fen_false;
  1553. end;
  1554. function TCGProcinfo.GetUserCode : tnode;
  1555. var
  1556. n : tnode;
  1557. begin
  1558. n:=nil;
  1559. foreachnodestatic(code,@searchusercode,@n);
  1560. if not(assigned(n)) then
  1561. internalerror(2013111004);
  1562. result:=n;
  1563. end;
  1564. procedure tcgprocinfo.generate_code;
  1565. procedure check_for_threadvars_in_initfinal;
  1566. begin
  1567. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1568. begin
  1569. { this is also used for initialization of variables in a
  1570. program which does not have a globalsymtable }
  1571. if assigned(current_module.globalsymtable) then
  1572. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1573. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1574. end;
  1575. end;
  1576. var
  1577. old_current_procinfo : tprocinfo;
  1578. oldmaxfpuregisters : longint;
  1579. oldfilepos : tfileposinfo;
  1580. old_current_structdef : tabstractrecorddef;
  1581. oldswitches : tlocalswitches;
  1582. templist : TAsmList;
  1583. headertai : tai;
  1584. procedure delete_marker(anode: tasmnode);
  1585. var
  1586. ai: tai;
  1587. begin
  1588. if assigned(anode) then
  1589. begin
  1590. ai:=anode.currenttai;
  1591. if assigned(ai) then
  1592. begin
  1593. aktproccode.remove(ai);
  1594. ai.free;
  1595. anode.currenttai:=nil;
  1596. end;
  1597. end;
  1598. end;
  1599. begin
  1600. { the initialization procedure can be empty, then we
  1601. don't need to generate anything. When it was an empty
  1602. procedure there would be at least a blocknode }
  1603. if not assigned(code) then
  1604. exit;
  1605. { We need valid code }
  1606. if Errorcount<>0 then
  1607. exit;
  1608. { No code can be generated for generic template }
  1609. if (df_generic in procdef.defoptions) then
  1610. internalerror(200511152);
  1611. { For regular procedures the RA and Tempgen shall not be available yet,
  1612. but exception filters reuse Tempgen of parent }
  1613. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1614. internalerror(200309201);
  1615. old_current_procinfo:=current_procinfo;
  1616. oldfilepos:=current_filepos;
  1617. old_current_structdef:=current_structdef;
  1618. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1619. current_procinfo:=self;
  1620. current_filepos:=entrypos;
  1621. current_structdef:=procdef.struct;
  1622. { store start of user code, it must be a block node, it will be used later one to
  1623. check variable lifeness }
  1624. include(code.flags,nf_usercode_entry);
  1625. { add wrapping code if necessary (initialization of typed constants on
  1626. some platforms, initing of local variables and out parameters with
  1627. trashing values, ...) }
  1628. { init/final code must be wrapped later (after code for main proc body
  1629. has been generated) }
  1630. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1631. code:=cnodeutils.wrap_proc_body(procdef,code);
  1632. { automatic inlining? }
  1633. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1634. { inlining not turned off? }
  1635. (cs_do_inline in current_settings.localswitches) and
  1636. not(po_noinline in procdef.procoptions) and
  1637. { no inlining yet? }
  1638. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1639. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1640. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1641. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1642. (not(procdef.proccalloption in [pocall_safecall])) and
  1643. { rough approximation if we should auto inline }
  1644. (node_count(code)<=10) then
  1645. begin
  1646. { Can we inline this procedure? }
  1647. if checknodeinlining(procdef) then
  1648. begin
  1649. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1650. include(procdef.procoptions,po_inline);
  1651. CreateInlineInfo;
  1652. end;
  1653. end;
  1654. templist:=TAsmList.create;
  1655. { add parast/localst to symtablestack }
  1656. add_to_symtablestack;
  1657. { clear register count }
  1658. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1659. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1660. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1661. if (procdef.localst.symtablelevel=main_program_level) and
  1662. (not current_module.is_unit) then
  1663. begin
  1664. include(flags,pi_do_call);
  1665. { the main program never returns due to the do_exit call }
  1666. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1667. include(procdef.procoptions,po_noreturn);
  1668. end;
  1669. { set implicit_finally flag when there are locals/paras to be finalized }
  1670. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1671. begin
  1672. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1673. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1674. end;
  1675. {$ifdef SUPPORT_SAFECALL}
  1676. { set implicit_finally flag for if procedure is safecall }
  1677. if (tf_safecall_exceptions in target_info.flags) and
  1678. (procdef.proccalloption=pocall_safecall) then
  1679. include(flags, pi_needs_implicit_finally);
  1680. {$endif}
  1681. { firstpass everything }
  1682. flowcontrol:=[];
  1683. do_firstpass(code);
  1684. {$if defined(i386) or defined(i8086)}
  1685. if node_resources_fpu(code)>0 then
  1686. include(flags,pi_uses_fpu);
  1687. {$endif i386 or i8086}
  1688. { Print the node to tree.log }
  1689. if paraprintnodetree <> 0 then
  1690. printproc( 'after the firstpass');
  1691. OptimizeNodeTree;
  1692. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1693. require a tls register, so check for such variables }
  1694. check_for_threadvars_in_initfinal;
  1695. { add implicit entry and exit code }
  1696. add_entry_exit_code;
  1697. if cs_opt_nodecse in current_settings.optimizerswitches then
  1698. do_optcse(code);
  1699. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1700. do_optloadmodifystore(code);
  1701. { only do secondpass if there are no errors }
  1702. if (ErrorCount=0) then
  1703. begin
  1704. create_hlcodegen;
  1705. setup_eh;
  1706. if (procdef.proctypeoption<>potype_exceptfilter) then
  1707. setup_tempgen;
  1708. { Create register allocator, must come after framepointer is known }
  1709. hlcg.init_register_allocators;
  1710. generate_parameter_info;
  1711. { allocate got register if needed }
  1712. allocate_got_register(aktproccode);
  1713. { allocate got register if needed }
  1714. allocate_tls_register(aktproccode);
  1715. { Allocate space in temp/registers for parast and localst }
  1716. current_filepos:=entrypos;
  1717. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1718. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1719. { Store temp offset for information about 'real' temps }
  1720. tempstart:=tg.lasttemp;
  1721. { Generate code to load register parameters in temps and insert local
  1722. copies for values parameters. This must be done before the code for the
  1723. body is generated because the localloc is updated.
  1724. Note: The generated code will be inserted after the code generation of
  1725. the body is finished, because only then the position is known }
  1726. {$ifdef oldregvars}
  1727. assign_regvars(code);
  1728. {$endif oldreg}
  1729. current_filepos:=entrypos;
  1730. hlcg.gen_load_para_value(templist);
  1731. { caller paraloc info is also necessary in the stackframe_entry
  1732. code of the ppc (and possibly other processors) }
  1733. procdef.init_paraloc_info(callerside);
  1734. CalcExecutionWeights(code);
  1735. { Print the node to tree.log }
  1736. if paraprintnodetree <> 0 then
  1737. printproc( 'right before code generation');
  1738. { generate code for the node tree }
  1739. do_secondpass(code);
  1740. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1741. { The position of the loadpara_asmnode is now known }
  1742. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1743. oldswitches:=current_settings.localswitches;
  1744. { first generate entry and initialize code with the correct
  1745. position and switches }
  1746. current_filepos:=entrypos;
  1747. current_settings.localswitches:=entryswitches;
  1748. cg.set_regalloc_live_range_direction(rad_backwards);
  1749. hlcg.gen_entry_code(templist);
  1750. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1751. hlcg.gen_initialize_code(templist);
  1752. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1753. { now generate finalize and exit code with the correct position
  1754. and switches }
  1755. current_filepos:=exitpos;
  1756. current_settings.localswitches:=exitswitches;
  1757. cg.set_regalloc_live_range_direction(rad_forward);
  1758. if assigned(finalize_procinfo) then
  1759. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1760. else if not temps_finalized then
  1761. begin
  1762. hlcg.gen_finalize_code(templist);
  1763. { the finalcode must be concated if there was no position available,
  1764. using insertlistafter will result in an insert at the start
  1765. when currentai=nil }
  1766. aktproccode.concatlist(templist);
  1767. end;
  1768. { insert exit label at the correct position }
  1769. hlcg.a_label(templist,CurrExitLabel);
  1770. if assigned(exitlabel_asmnode.currenttai) then
  1771. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1772. else
  1773. aktproccode.concatlist(templist);
  1774. { exit code }
  1775. hlcg.gen_exit_code(templist);
  1776. aktproccode.concatlist(templist);
  1777. { reset switches }
  1778. current_settings.localswitches:=oldswitches;
  1779. {$ifdef OLDREGVARS}
  1780. { note: this must be done only after as much code as possible has }
  1781. { been generated. The result is that when you ungetregister() a }
  1782. { regvar, it will actually free the regvar (and alse free the }
  1783. { the regvars at the same time). Doing this too early will }
  1784. { confuse the register allocator, as the regvars will still be }
  1785. { used. It should be done before loading the result regs (so }
  1786. { they don't conflict with the regvars) and before }
  1787. { gen_entry_code (that one has to be able to allocate the }
  1788. { regvars again) (JM) }
  1789. free_regvars(aktproccode);
  1790. {$endif OLDREGVARS}
  1791. { generate symbol and save end of header position }
  1792. current_filepos:=entrypos;
  1793. hlcg.gen_proc_symbol(templist);
  1794. headertai:=tai(templist.last);
  1795. { insert symbol }
  1796. aktproccode.insertlist(templist);
  1797. { Free space in temp/registers for parast and localst, must be
  1798. done after gen_entry_code }
  1799. current_filepos:=exitpos;
  1800. { make sure the got/pic register doesn't get freed in the }
  1801. { middle of a loop }
  1802. if (tf_pic_uses_got in target_info.flags) and
  1803. (pi_needs_got in flags) and
  1804. (got<>NR_NO) then
  1805. cg.a_reg_sync(aktproccode,got);
  1806. if (pi_needs_tls in flags) and
  1807. (tlsoffset<>NR_NO) then
  1808. cg.a_reg_sync(aktproccode,tlsoffset);
  1809. gen_free_symtable(aktproccode,procdef.localst);
  1810. gen_free_symtable(aktproccode,procdef.parast);
  1811. { add code that will load the return value, this is not done
  1812. for assembler routines when they didn't reference the result
  1813. variable }
  1814. hlcg.gen_load_return_value(templist);
  1815. aktproccode.concatlist(templist);
  1816. { Already reserve all registers for stack checking code and
  1817. generate the call to the helper function }
  1818. if not(tf_no_generic_stackcheck in target_info.flags) and
  1819. (cs_check_stack in entryswitches) and
  1820. not(po_assembler in procdef.procoptions) and
  1821. (procdef.proctypeoption<>potype_proginit) then
  1822. begin
  1823. current_filepos:=entrypos;
  1824. hlcg.gen_stack_check_call(templist);
  1825. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1826. end;
  1827. { this code (got loading) comes before everything which has }
  1828. { already been generated, so reset the info about already }
  1829. { backwards extended registers (so their live range can be }
  1830. { extended backwards even further if needed) }
  1831. { This code must be }
  1832. { a) generated after do_secondpass has been called }
  1833. { (because pi_needs_got may be set there) }
  1834. { b) generated before register allocation, because the }
  1835. { got/pic register can be a virtual one }
  1836. { c) inserted before the entry code, because the entry }
  1837. { code may need global symbols such as init rtti }
  1838. { d) inserted after the stackframe allocation, because }
  1839. { this register may have to be spilled }
  1840. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1841. current_filepos:=entrypos;
  1842. { load got if necessary }
  1843. cg.g_maybe_got_init(templist);
  1844. aktproccode.insertlistafter(headertai,templist);
  1845. { init tls if needed }
  1846. cg.g_maybe_tls_init(templist);
  1847. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1848. { re-enable if more code at the end is ever generated here
  1849. cg.set_regalloc_live_range_direction(rad_forward);
  1850. }
  1851. {$ifndef NoOpt}
  1852. {$ifndef i386}
  1853. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1854. { do not optimize pure assembler procedures }
  1855. not(pi_is_assembler in flags) then
  1856. preregallocschedule(aktproccode);
  1857. {$endif i386}
  1858. {$endif NoOpt}
  1859. { The procedure body is finished, we can now
  1860. allocate the registers }
  1861. cg.do_register_allocation(aktproccode,headertai);
  1862. { translate imag. register to their real counter parts
  1863. this is necessary for debuginfo and verbose assembler output
  1864. when SSA will be implented, this will be more complicated because we've to
  1865. maintain location lists }
  1866. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1867. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1868. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1869. not(cs_no_regalloc in current_settings.globalswitches) and
  1870. (got<>NR_NO) then
  1871. cg.translate_register(got);
  1872. { Add save and restore of used registers }
  1873. current_filepos:=entrypos;
  1874. gen_save_used_regs(templist);
  1875. { Remember the last instruction of register saving block
  1876. (may be =nil for e.g. assembler procedures) }
  1877. endprologue_ai:=templist.last;
  1878. aktproccode.insertlistafter(headertai,templist);
  1879. current_filepos:=exitpos;
  1880. gen_restore_used_regs(aktproccode);
  1881. { We know the size of the stack, now we can generate the
  1882. parameter that is passed to the stack checking code }
  1883. if not(tf_no_generic_stackcheck in target_info.flags) and
  1884. (cs_check_stack in entryswitches) and
  1885. not(po_assembler in procdef.procoptions) and
  1886. (procdef.proctypeoption<>potype_proginit) then
  1887. begin
  1888. current_filepos:=entrypos;
  1889. hlcg.gen_stack_check_size_para(templist);
  1890. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1891. end;
  1892. current_procinfo.set_eh_info;
  1893. { Add entry code (stack allocation) after header }
  1894. current_filepos:=entrypos;
  1895. gen_proc_entry_code(templist);
  1896. aktproccode.insertlistafter(headertai,templist);
  1897. {$ifdef SUPPORT_SAFECALL}
  1898. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1899. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1900. (tf_safecall_exceptions in target_info.flags) and
  1901. (procdef.proccalloption=pocall_safecall) then
  1902. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1903. {$endif}
  1904. { Add exit code at the end }
  1905. current_filepos:=exitpos;
  1906. gen_proc_exit_code(templist);
  1907. aktproccode.concatlist(templist);
  1908. { check if the implicit finally has been generated. The flag
  1909. should already be set in pass1 }
  1910. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1911. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1912. (pi_needs_implicit_finally in flags) and
  1913. not(pi_has_implicit_finally in flags) and
  1914. not(target_info.system in systems_garbage_collected_managed_types) then
  1915. internalerror(200405231);
  1916. { sanity check }
  1917. if not(assigned(current_procinfo.procdef.personality)) and
  1918. (tf_use_psabieh in target_info.flags) and
  1919. ((pi_uses_exceptions in flags) or
  1920. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1921. (pi_needs_implicit_finally in flags))) then
  1922. Internalerror(2019021005);
  1923. { Position markers are only used to insert additional code after the secondpass
  1924. and before this point. They are of no use in optimizer. Instead of checking and
  1925. ignoring all over the optimizer, just remove them here. }
  1926. delete_marker(entry_asmnode);
  1927. delete_marker(loadpara_asmnode);
  1928. delete_marker(exitlabel_asmnode);
  1929. delete_marker(stackcheck_asmnode);
  1930. delete_marker(init_asmnode);
  1931. {$ifndef NoOpt}
  1932. if not(cs_no_regalloc in current_settings.globalswitches) then
  1933. begin
  1934. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1935. { do not optimize pure assembler procedures }
  1936. not(pi_is_assembler in flags) then
  1937. optimize(aktproccode);
  1938. {$ifndef i386}
  1939. { schedule after assembler optimization, it could have brought up
  1940. new schedule possibilities }
  1941. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1942. { do not optimize pure assembler procedures }
  1943. not(pi_is_assembler in flags) then
  1944. preregallocschedule(aktproccode);
  1945. {$endif i386}
  1946. end;
  1947. {$endif NoOpt}
  1948. { Perform target-specific processing if necessary }
  1949. postprocess_code;
  1950. { Add end symbol and debug info }
  1951. { this must be done after the pcrelativedata is appended else the distance calculation of
  1952. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1953. so it should be inserted before the end symbol (FK)
  1954. }
  1955. current_filepos:=exitpos;
  1956. hlcg.gen_proc_symbol_end(templist);
  1957. aktproccode.concatlist(templist);
  1958. { insert line debuginfo }
  1959. if (cs_debuginfo in current_settings.moduleswitches) or
  1960. (cs_use_lineinfo in current_settings.globalswitches) then
  1961. current_debuginfo.insertlineinfo(aktproccode);
  1962. finish_eh;
  1963. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1964. { only now we can remove the temps }
  1965. if (procdef.proctypeoption<>potype_exceptfilter) then
  1966. begin
  1967. tg.resettempgen;
  1968. tg.free;
  1969. tg:=nil;
  1970. end;
  1971. { stop tempgen and ra }
  1972. hlcg.done_register_allocators;
  1973. destroy_hlcodegen;
  1974. end;
  1975. dfabuilder.free;
  1976. { restore symtablestack }
  1977. remove_from_symtablestack;
  1978. { restore }
  1979. templist.free;
  1980. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1981. current_filepos:=oldfilepos;
  1982. current_structdef:=old_current_structdef;
  1983. current_procinfo:=old_current_procinfo;
  1984. end;
  1985. procedure tcgprocinfo.add_to_symtablestack;
  1986. begin
  1987. { insert symtables for the class, but only if it is no nested function }
  1988. if assigned(procdef.struct) and
  1989. not(assigned(parent) and
  1990. assigned(parent.procdef) and
  1991. assigned(parent.procdef.struct)) then
  1992. push_nested_hierarchy(procdef.struct);
  1993. { insert parasymtable in symtablestack when parsing
  1994. a function }
  1995. if procdef.parast.symtablelevel>=normal_function_level then
  1996. symtablestack.push(procdef.parast);
  1997. { insert localsymtable, except for the main procedure
  1998. (in that case the localst is the unit's static symtable,
  1999. which is already on the stack) }
  2000. if procdef.localst.symtablelevel>=normal_function_level then
  2001. symtablestack.push(procdef.localst);
  2002. end;
  2003. procedure tcgprocinfo.remove_from_symtablestack;
  2004. begin
  2005. { remove localsymtable }
  2006. if procdef.localst.symtablelevel>=normal_function_level then
  2007. symtablestack.pop(procdef.localst);
  2008. { remove parasymtable }
  2009. if procdef.parast.symtablelevel>=normal_function_level then
  2010. symtablestack.pop(procdef.parast);
  2011. { remove symtables for the class, but only if it is no nested function }
  2012. if assigned(procdef.struct) and
  2013. not(assigned(parent) and
  2014. assigned(parent.procdef) and
  2015. assigned(parent.procdef.struct)) then
  2016. pop_nested_hierarchy(procdef.struct);
  2017. end;
  2018. procedure tcgprocinfo.resetprocdef;
  2019. begin
  2020. { remove code tree, if not inline procedure }
  2021. if assigned(code) then
  2022. begin
  2023. { the inline procedure has already got a copy of the tree
  2024. stored in procdef.inlininginfo }
  2025. code.free;
  2026. code:=nil;
  2027. end;
  2028. end;
  2029. procedure tcgprocinfo.parse_body;
  2030. var
  2031. old_current_procinfo : tprocinfo;
  2032. old_block_type : tblock_type;
  2033. st : TSymtable;
  2034. old_current_structdef: tabstractrecorddef;
  2035. old_current_genericdef,
  2036. old_current_specializedef: tstoreddef;
  2037. parentfpinitblock: tnode;
  2038. old_parse_generic: boolean;
  2039. recordtokens : boolean;
  2040. begin
  2041. old_current_procinfo:=current_procinfo;
  2042. old_block_type:=block_type;
  2043. old_current_structdef:=current_structdef;
  2044. old_current_genericdef:=current_genericdef;
  2045. old_current_specializedef:=current_specializedef;
  2046. old_parse_generic:=parse_generic;
  2047. current_procinfo:=self;
  2048. current_structdef:=procdef.struct;
  2049. { check if the definitions of certain types are available which might not be available in older rtls and
  2050. which are assigned "on the fly" in types_dec }
  2051. {$ifndef jvm}
  2052. if not assigned(rec_exceptaddr) then
  2053. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  2054. if not assigned(rec_tguid) then
  2055. Message1(cg_f_internal_type_not_found,'TGUID');
  2056. if not assigned(rec_jmp_buf) then
  2057. Message1(cg_f_internal_type_not_found,'TJMPBUF');
  2058. {$endif}
  2059. { if the procdef is truly a generic (thus takes parameters itself) then
  2060. /that/ is our genericdef, not the - potentially - generic struct }
  2061. if procdef.is_generic then
  2062. begin
  2063. current_genericdef:=procdef;
  2064. parse_generic:=true;
  2065. end
  2066. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  2067. begin
  2068. current_genericdef:=current_structdef;
  2069. parse_generic:=true;
  2070. end;
  2071. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  2072. current_specializedef:=current_structdef;
  2073. { calculate the lexical level }
  2074. if procdef.parast.symtablelevel>maxnesting then
  2075. Message(parser_e_too_much_lexlevel);
  2076. block_type:=bt_body;
  2077. {$ifdef state_tracking}
  2078. { aktstate:=Tstate_storage.create;}
  2079. {$endif state_tracking}
  2080. { allocate the symbol for this procedure }
  2081. alloc_proc_symbol(procdef);
  2082. { add parast/localst to symtablestack }
  2083. add_to_symtablestack;
  2084. { save entry info }
  2085. entrypos:=current_filepos;
  2086. entryswitches:=current_settings.localswitches;
  2087. recordtokens:=procdef.is_generic or
  2088. (
  2089. assigned(procdef.struct) and
  2090. (df_generic in procdef.struct.defoptions) and
  2091. assigned(procdef.owner) and
  2092. (procdef.owner.defowner=procdef.struct)
  2093. );
  2094. if recordtokens then
  2095. begin
  2096. { start token recorder for generic template }
  2097. procdef.initgeneric;
  2098. current_scanner.startrecordtokens(procdef.generictokenbuf);
  2099. end;
  2100. { parse the code ... }
  2101. code:=block(current_module.islibrary);
  2102. if recordtokens then
  2103. begin
  2104. { stop token recorder for generic template }
  2105. current_scanner.stoprecordtokens;
  2106. { Give an error for accesses in the static symtable that aren't visible
  2107. outside the current unit }
  2108. st:=procdef.owner;
  2109. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  2110. st:=st.defowner.owner;
  2111. if (pi_uses_static_symtable in flags) and
  2112. (st.symtabletype<>staticsymtable) then
  2113. Message(parser_e_global_generic_references_static);
  2114. end;
  2115. { save exit info }
  2116. exitswitches:=current_settings.localswitches;
  2117. exitpos:=last_endtoken_filepos;
  2118. { the procedure is now defined }
  2119. procdef.forwarddef:=false;
  2120. if assigned(code) then
  2121. begin
  2122. { get a better entry point }
  2123. entrypos:=code.fileinfo;
  2124. { Finish type checking pass }
  2125. do_typecheckpass(code);
  2126. if assigned(procdef.parentfpinitblock) then
  2127. begin
  2128. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  2129. begin
  2130. parentfpinitblock:=procdef.parentfpinitblock;
  2131. do_typecheckpass(parentfpinitblock);
  2132. procdef.parentfpinitblock:=parentfpinitblock;
  2133. end
  2134. end;
  2135. end;
  2136. { Check for unused labels, forwards, symbols for procedures. Static
  2137. symtable is checked in pmodules.
  2138. The check must be done after the typecheckpass }
  2139. if (Errorcount=0) and
  2140. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  2141. begin
  2142. { check if forwards are resolved }
  2143. tstoredsymtable(procdef.localst).check_forwards;
  2144. { check if all labels are used }
  2145. tstoredsymtable(procdef.localst).checklabels;
  2146. { check for unused symbols, but only if there is no asm block }
  2147. if not(pi_has_assembler_block in flags) then
  2148. begin
  2149. tstoredsymtable(procdef.localst).allsymbolsused;
  2150. tstoredsymtable(procdef.parast).allsymbolsused;
  2151. end;
  2152. end;
  2153. if (po_inline in procdef.procoptions) and
  2154. { Can we inline this procedure? }
  2155. checknodeinlining(procdef) then
  2156. CreateInlineInfo;
  2157. { Print the node to tree.log }
  2158. if paraprintnodetree <> 0 then
  2159. printproc( 'after parsing');
  2160. {$ifdef DEBUG_NODE_XML}
  2161. printnodeindention := printnodespacing;
  2162. XMLPrintProc;
  2163. {$endif DEBUG_NODE_XML}
  2164. { ... remove symbol tables }
  2165. remove_from_symtablestack;
  2166. {$ifdef state_tracking}
  2167. { aktstate.destroy;}
  2168. {$endif state_tracking}
  2169. current_structdef:=old_current_structdef;
  2170. current_genericdef:=old_current_genericdef;
  2171. current_specializedef:=old_current_specializedef;
  2172. current_procinfo:=old_current_procinfo;
  2173. parse_generic:=old_parse_generic;
  2174. { Restore old state }
  2175. block_type:=old_block_type;
  2176. end;
  2177. {****************************************************************************
  2178. PROCEDURE/FUNCTION PARSING
  2179. ****************************************************************************}
  2180. procedure check_init_paras(p:TObject;arg:pointer);
  2181. begin
  2182. if tsym(p).typ<>paravarsym then
  2183. exit;
  2184. with tparavarsym(p) do
  2185. if (is_managed_type(vardef) and
  2186. (varspez in [vs_value,vs_out])) or
  2187. (is_shortstring(vardef) and
  2188. (varspez=vs_value)) then
  2189. include(current_procinfo.flags,pi_do_call);
  2190. end;
  2191. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2192. {
  2193. Parses the procedure directives, then parses the procedure body, then
  2194. generates the code for it
  2195. }
  2196. var
  2197. oldfailtokenmode : tmodeswitches;
  2198. isnestedproc : boolean;
  2199. begin
  2200. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2201. oldfailtokenmode:=[];
  2202. { create a new procedure }
  2203. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2204. current_module.procinfo:=current_procinfo;
  2205. current_procinfo.procdef:=pd;
  2206. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2207. { Insert mangledname }
  2208. pd.aliasnames.insert(pd.mangledname);
  2209. { Handle Export of this procedure }
  2210. if (po_exports in pd.procoptions) and
  2211. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2212. begin
  2213. pd.aliasnames.insert(pd.procsym.realname);
  2214. if cs_link_deffile in current_settings.globalswitches then
  2215. deffile.AddExport(pd.mangledname);
  2216. end;
  2217. { Insert result variables in the localst }
  2218. insert_funcret_local(pd);
  2219. { check if there are para's which require initing -> set }
  2220. { pi_do_call (if not yet set) }
  2221. if not(pi_do_call in current_procinfo.flags) then
  2222. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2223. { set _FAIL as keyword if constructor }
  2224. if (pd.proctypeoption=potype_constructor) then
  2225. begin
  2226. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2227. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2228. end;
  2229. tcgprocinfo(current_procinfo).parse_body;
  2230. { reset _FAIL as _SELF normal }
  2231. if (pd.proctypeoption=potype_constructor) then
  2232. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2233. { When it's a nested procedure then defer the code generation,
  2234. when back at normal function level then generate the code
  2235. for all defered nested procedures and the current procedure }
  2236. if not isnestedproc then
  2237. begin
  2238. if not(df_generic in current_procinfo.procdef.defoptions) then
  2239. begin
  2240. { also generate the bodies for all previously done
  2241. specializations so that we might inline them }
  2242. generate_specialization_procs;
  2243. tcgprocinfo(current_procinfo).generate_code_tree;
  2244. end;
  2245. end;
  2246. { release procinfo }
  2247. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2248. internalerror(200304274);
  2249. current_module.procinfo:=current_procinfo.parent;
  2250. { For specialization we didn't record the last semicolon. Moving this parsing
  2251. into the parse_body routine is not done because of having better file position
  2252. information available }
  2253. if not current_procinfo.procdef.is_specialization and
  2254. (
  2255. not assigned(current_procinfo.procdef.struct) or
  2256. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2257. or not (
  2258. assigned(current_procinfo.procdef.owner) and
  2259. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2260. )
  2261. ) then
  2262. consume(_SEMICOLON);
  2263. if not isnestedproc then
  2264. { current_procinfo is checked for nil later on }
  2265. freeandnil(current_procinfo);
  2266. end;
  2267. procedure read_proc_body(pd:tprocdef);
  2268. var
  2269. old_module_procinfo : tobject;
  2270. old_current_procinfo : tprocinfo;
  2271. begin
  2272. old_current_procinfo:=current_procinfo;
  2273. old_module_procinfo:=current_module.procinfo;
  2274. current_procinfo:=nil;
  2275. current_module.procinfo:=nil;
  2276. read_proc_body(nil,pd);
  2277. current_procinfo:=old_current_procinfo;
  2278. current_module.procinfo:=old_module_procinfo;
  2279. end;
  2280. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  2281. {
  2282. Parses the procedure directives, then parses the procedure body, then
  2283. generates the code for it
  2284. }
  2285. var
  2286. old_current_procinfo : tprocinfo;
  2287. old_current_structdef: tabstractrecorddef;
  2288. old_current_genericdef,
  2289. old_current_specializedef: tstoreddef;
  2290. pdflags : tpdflags;
  2291. pd,firstpd : tprocdef;
  2292. {$ifdef genericdef_for_nested}
  2293. def : tprocdef;
  2294. srsym : tsym;
  2295. i : longint;
  2296. {$endif genericdef_for_nested}
  2297. begin
  2298. { save old state }
  2299. old_current_procinfo:=current_procinfo;
  2300. old_current_structdef:=current_structdef;
  2301. old_current_genericdef:=current_genericdef;
  2302. old_current_specializedef:=current_specializedef;
  2303. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2304. to another procdef }
  2305. current_procinfo:=nil;
  2306. current_structdef:=nil;
  2307. current_genericdef:=nil;
  2308. current_specializedef:=nil;
  2309. if not assigned(usefwpd) then
  2310. { parse procedure declaration }
  2311. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  2312. else
  2313. pd:=usefwpd;
  2314. { set the default function options }
  2315. if parse_only then
  2316. begin
  2317. pd.forwarddef:=true;
  2318. { set also the interface flag, for better error message when the
  2319. implementation doesn't match this header }
  2320. pd.interfacedef:=true;
  2321. include(pd.procoptions,po_global);
  2322. pdflags:=[pd_interface];
  2323. end
  2324. else
  2325. begin
  2326. pdflags:=[pd_body];
  2327. if (not current_module.in_interface) then
  2328. include(pdflags,pd_implemen);
  2329. if (not current_module.is_unit) or
  2330. create_smartlink_library then
  2331. include(pd.procoptions,po_global);
  2332. pd.forwarddef:=false;
  2333. end;
  2334. if not assigned(usefwpd) then
  2335. begin
  2336. { parse the directives that may follow }
  2337. parse_proc_directives(pd,pdflags);
  2338. { hint directives, these can be separated by semicolons here,
  2339. that needs to be handled here with a loop (PFV) }
  2340. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2341. Consume(_SEMICOLON);
  2342. { Set calling convention }
  2343. if parse_only then
  2344. handle_calling_convention(pd,hcc_default_actions_intf)
  2345. else
  2346. handle_calling_convention(pd,hcc_default_actions_impl)
  2347. end;
  2348. { search for forward declarations }
  2349. if not proc_add_definition(pd) then
  2350. begin
  2351. { One may not implement a method of a type declared in a different unit }
  2352. if assigned(pd.struct) and
  2353. (pd.struct.symtable.moduleid<>current_module.moduleid) and
  2354. not pd.is_specialization then
  2355. begin
  2356. MessagePos1(pd.fileinfo,parser_e_method_for_type_in_other_unit,pd.struct.typesymbolprettyname);
  2357. end
  2358. { A method must be forward defined (in the object declaration) }
  2359. else if assigned(pd.struct) and
  2360. (not assigned(old_current_structdef)) then
  2361. begin
  2362. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2363. tprocsym(pd.procsym).write_parameter_lists(pd);
  2364. end
  2365. else
  2366. begin
  2367. { Give a better error if there is a forward def in the interface and only
  2368. a single implementation }
  2369. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2370. if (not pd.forwarddef) and
  2371. (not pd.interfacedef) and
  2372. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2373. firstpd.forwarddef and
  2374. firstpd.interfacedef and
  2375. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2376. { don't give an error if it may be an overload }
  2377. not(m_fpc in current_settings.modeswitches) and
  2378. (not(po_overload in pd.procoptions) or
  2379. not(po_overload in firstpd.procoptions)) then
  2380. begin
  2381. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2382. tprocsym(pd.procsym).write_parameter_lists(pd);
  2383. end
  2384. else
  2385. begin
  2386. if pd.is_generic and not assigned(pd.struct) then
  2387. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2388. end;
  2389. end;
  2390. end;
  2391. { Set mangled name }
  2392. proc_set_mangledname(pd);
  2393. { inherit generic flags from parent routine }
  2394. if assigned(old_current_procinfo) and
  2395. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2396. begin
  2397. if df_generic in old_current_procinfo.procdef.defoptions then
  2398. include(pd.defoptions,df_generic);
  2399. if df_specialization in old_current_procinfo.procdef.defoptions then
  2400. begin
  2401. include(pd.defoptions,df_specialization);
  2402. { the procdefs encountered here are nested procdefs of which
  2403. their complete definition also resides inside the current token
  2404. stream, thus access to their genericdef is not required }
  2405. {$ifdef genericdef_for_nested}
  2406. { find the corresponding routine in the generic routine }
  2407. if not assigned(old_current_procinfo.procdef.genericdef) then
  2408. internalerror(2016121701);
  2409. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2410. if not assigned(srsym) or (srsym.typ<>procsym) then
  2411. internalerror(2016121702);
  2412. { in practice the generic procdef should be at the same index
  2413. as the index of the current procdef, but as there *might* be
  2414. differences between the amount of defs generated for the
  2415. specialization and the generic search for the def using
  2416. parameter comparison }
  2417. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2418. begin
  2419. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2420. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2421. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2422. begin
  2423. pd.genericdef:=def;
  2424. break;
  2425. end;
  2426. end;
  2427. if not assigned(pd.genericdef) then
  2428. internalerror(2016121703);
  2429. {$endif}
  2430. end;
  2431. end;
  2432. { compile procedure when a body is needed }
  2433. if (pd_body in pdflags) then
  2434. begin
  2435. read_proc_body(old_current_procinfo,pd);
  2436. end
  2437. else
  2438. begin
  2439. { Handle imports }
  2440. if (po_external in pd.procoptions) then
  2441. begin
  2442. import_external_proc(pd);
  2443. {$ifdef cpuhighleveltarget}
  2444. { it's hard to factor this out in a virtual method, because the
  2445. generic version (the one inside this ifdef) doesn't fit in
  2446. hlcgobj but in symcreat or here, while the other version
  2447. doesn't fit in symcreat (since it uses the code generator).
  2448. Maybe we need another class for this kind of code that could
  2449. either be symcreat- or hlcgobj-based
  2450. }
  2451. if (not pd.forwarddef) and
  2452. (pd.hasforward) and
  2453. (proc_get_importname(pd)<>'') then
  2454. begin
  2455. { we cannot handle the callee-side of variadic functions (and
  2456. even if we could, e.g. LLVM cannot call through to something
  2457. else in that case) }
  2458. if is_c_variadic(pd) then
  2459. Message1(parser_e_callthrough_varargs,pd.fullprocname(false));
  2460. call_through_new_name(pd,proc_get_importname(pd));
  2461. include(pd.implprocoptions,pio_thunk);
  2462. end
  2463. else
  2464. {$endif cpuhighleveltarget}
  2465. begin
  2466. create_hlcodegen;
  2467. hlcg.handle_external_proc(
  2468. current_asmdata.asmlists[al_procedures],
  2469. pd,
  2470. proc_get_importname(pd));
  2471. destroy_hlcodegen;
  2472. end
  2473. end;
  2474. end;
  2475. { always register public functions that are only declared in the
  2476. implementation section as they might be called using an external
  2477. declaration from another unit }
  2478. if (po_global in pd.procoptions) and
  2479. not pd.interfacedef and
  2480. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2481. begin
  2482. pd.register_def;
  2483. pd.procsym.register_sym;
  2484. end;
  2485. { make sure that references to forward-declared functions are not }
  2486. { treated as references to external symbols, needed for darwin. }
  2487. { make sure we don't change the binding of real external symbols }
  2488. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2489. current_asmdata.DefineProcAsmSymbol(pd,pd.mangledname,pd.needsglobalasmsym);
  2490. current_structdef:=old_current_structdef;
  2491. current_genericdef:=old_current_genericdef;
  2492. current_specializedef:=old_current_specializedef;
  2493. current_procinfo:=old_current_procinfo;
  2494. end;
  2495. procedure import_external_proc(pd:tprocdef);
  2496. var
  2497. name : string;
  2498. begin
  2499. if not (po_external in pd.procoptions) then
  2500. internalerror(2015121101);
  2501. { Import DLL specified? }
  2502. if assigned(pd.import_dll) then
  2503. begin
  2504. if assigned (pd.import_name) then
  2505. current_module.AddExternalImport(pd.import_dll^,
  2506. pd.import_name^,proc_get_importname(pd),
  2507. pd.import_nr,false,false)
  2508. else
  2509. current_module.AddExternalImport(pd.import_dll^,
  2510. proc_get_importname(pd),proc_get_importname(pd),
  2511. pd.import_nr,false,true);
  2512. end
  2513. else
  2514. begin
  2515. name:=proc_get_importname(pd);
  2516. { add import name to external list for DLL scanning }
  2517. if tf_has_dllscanner in target_info.flags then
  2518. current_module.dllscannerinputlist.Add(name,pd);
  2519. { needed for units that use functions in packages this way }
  2520. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2521. end;
  2522. end;
  2523. {****************************************************************************
  2524. DECLARATION PARSING
  2525. ****************************************************************************}
  2526. { search in symtablestack for not complete classes }
  2527. procedure check_forward_class(p:TObject;arg:pointer);
  2528. begin
  2529. if (tsym(p).typ=typesym) and
  2530. (ttypesym(p).typedef.typ=objectdef) and
  2531. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2532. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2533. end;
  2534. {$ifdef DEBUG_NODE_XML}
  2535. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2536. var
  2537. T: Text;
  2538. begin
  2539. Assign(T, current_module.ppxfilename);
  2540. {$push} {$I-}
  2541. Rewrite(T);
  2542. if IOResult<>0 then
  2543. begin
  2544. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2545. current_module.ppxfilefail := True;
  2546. Exit;
  2547. end;
  2548. {$pop}
  2549. { Mark the node dump file as available for writing }
  2550. current_module.ppxfilefail := False;
  2551. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2552. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2553. Close(T);
  2554. end;
  2555. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2556. var
  2557. T: Text;
  2558. begin
  2559. if current_module.ppxfilefail then
  2560. Exit;
  2561. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2562. Assign(T, current_module.ppxfilename);
  2563. {$push} {$I-}
  2564. Append(T);
  2565. if IOResult<>0 then
  2566. begin
  2567. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2568. Exit;
  2569. end;
  2570. {$pop}
  2571. WriteLn(T, '</', RootName, '>');
  2572. Close(T);
  2573. end;
  2574. {$endif DEBUG_NODE_XML}
  2575. procedure read_declarations(islibrary : boolean);
  2576. var
  2577. hadgeneric : boolean;
  2578. procedure handle_unexpected_had_generic;
  2579. begin
  2580. if hadgeneric then
  2581. begin
  2582. Message(parser_e_procedure_or_function_expected);
  2583. hadgeneric:=false;
  2584. end;
  2585. end;
  2586. var
  2587. is_classdef:boolean;
  2588. begin
  2589. is_classdef:=false;
  2590. hadgeneric:=false;
  2591. repeat
  2592. if not assigned(current_procinfo) then
  2593. internalerror(200304251);
  2594. case token of
  2595. _LABEL:
  2596. begin
  2597. handle_unexpected_had_generic;
  2598. label_dec;
  2599. end;
  2600. _CONST:
  2601. begin
  2602. handle_unexpected_had_generic;
  2603. const_dec(hadgeneric);
  2604. end;
  2605. _TYPE:
  2606. begin
  2607. handle_unexpected_had_generic;
  2608. type_dec(hadgeneric);
  2609. end;
  2610. _VAR:
  2611. begin
  2612. handle_unexpected_had_generic;
  2613. var_dec(hadgeneric);
  2614. end;
  2615. _THREADVAR:
  2616. begin
  2617. handle_unexpected_had_generic;
  2618. threadvar_dec(hadgeneric);
  2619. end;
  2620. _CLASS:
  2621. begin
  2622. is_classdef:=false;
  2623. if try_to_consume(_CLASS) then
  2624. begin
  2625. { class modifier is only allowed for procedures, functions, }
  2626. { constructors, destructors }
  2627. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2628. not((token=_ID) and (idtoken=_OPERATOR)) then
  2629. Message(parser_e_procedure_or_function_expected);
  2630. if is_interface(current_structdef) then
  2631. Message(parser_e_no_static_method_in_interfaces)
  2632. else
  2633. { class methods are also allowed for Objective-C protocols }
  2634. is_classdef:=true;
  2635. end;
  2636. end;
  2637. _CONSTRUCTOR,
  2638. _DESTRUCTOR,
  2639. _FUNCTION,
  2640. _PROCEDURE,
  2641. _OPERATOR:
  2642. begin
  2643. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2644. begin
  2645. Message(parser_e_procedure_or_function_expected);
  2646. hadgeneric:=false;
  2647. end;
  2648. read_proc(is_classdef,nil,hadgeneric);
  2649. is_classdef:=false;
  2650. hadgeneric:=false;
  2651. end;
  2652. _EXPORTS:
  2653. begin
  2654. handle_unexpected_had_generic;
  2655. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2656. begin
  2657. Message(parser_e_syntax_error);
  2658. consume_all_until(_SEMICOLON);
  2659. end
  2660. else if islibrary or
  2661. (target_info.system in systems_unit_program_exports) then
  2662. read_exports
  2663. else
  2664. begin
  2665. Message(parser_w_unsupported_feature);
  2666. consume(_BEGIN);
  2667. end;
  2668. end;
  2669. _PROPERTY:
  2670. begin
  2671. handle_unexpected_had_generic;
  2672. if (m_fpc in current_settings.modeswitches) then
  2673. property_dec
  2674. else
  2675. break;
  2676. end;
  2677. else
  2678. begin
  2679. case idtoken of
  2680. _RESOURCESTRING:
  2681. begin
  2682. handle_unexpected_had_generic;
  2683. { m_class is needed, because the resourcestring
  2684. loading is in the ObjPas unit }
  2685. { if (m_class in current_settings.modeswitches) then}
  2686. resourcestring_dec(hadgeneric)
  2687. { else
  2688. break;}
  2689. end;
  2690. _OPERATOR:
  2691. begin
  2692. handle_unexpected_had_generic;
  2693. if is_classdef then
  2694. begin
  2695. read_proc(is_classdef,nil,false);
  2696. is_classdef:=false;
  2697. end
  2698. else
  2699. break;
  2700. end;
  2701. _GENERIC:
  2702. begin
  2703. handle_unexpected_had_generic;
  2704. if not (m_delphi in current_settings.modeswitches) then
  2705. begin
  2706. consume(_ID);
  2707. hadgeneric:=true;
  2708. end
  2709. else
  2710. break;
  2711. end
  2712. else
  2713. break;
  2714. end;
  2715. end;
  2716. end;
  2717. until false;
  2718. { add implementations for synthetic method declarations added by
  2719. the compiler (not for unit/program init functions, their localst
  2720. is the staticst -> would duplicate the work done in pmodules) }
  2721. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2722. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2723. { check for incomplete class definitions, this is only required
  2724. for fpc modes }
  2725. if (m_fpc in current_settings.modeswitches) then
  2726. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2727. end;
  2728. procedure read_interface_declarations;
  2729. var
  2730. hadgeneric : boolean;
  2731. procedure handle_unexpected_had_generic;
  2732. begin
  2733. if hadgeneric then
  2734. begin
  2735. Message(parser_e_procedure_or_function_expected);
  2736. hadgeneric:=false;
  2737. end;
  2738. end;
  2739. begin
  2740. hadgeneric:=false;
  2741. repeat
  2742. case token of
  2743. _CONST :
  2744. begin
  2745. handle_unexpected_had_generic;
  2746. const_dec(hadgeneric);
  2747. end;
  2748. _TYPE :
  2749. begin
  2750. handle_unexpected_had_generic;
  2751. type_dec(hadgeneric);
  2752. end;
  2753. _VAR :
  2754. begin
  2755. handle_unexpected_had_generic;
  2756. var_dec(hadgeneric);
  2757. end;
  2758. _THREADVAR :
  2759. begin
  2760. handle_unexpected_had_generic;
  2761. threadvar_dec(hadgeneric);
  2762. end;
  2763. _FUNCTION,
  2764. _PROCEDURE,
  2765. _OPERATOR :
  2766. begin
  2767. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2768. begin
  2769. message(parser_e_procedure_or_function_expected);
  2770. hadgeneric:=false;
  2771. end;
  2772. read_proc(false,nil,hadgeneric);
  2773. hadgeneric:=false;
  2774. end;
  2775. else
  2776. begin
  2777. case idtoken of
  2778. _RESOURCESTRING :
  2779. begin
  2780. handle_unexpected_had_generic;
  2781. resourcestring_dec(hadgeneric);
  2782. end;
  2783. _PROPERTY:
  2784. begin
  2785. handle_unexpected_had_generic;
  2786. if (m_fpc in current_settings.modeswitches) then
  2787. property_dec
  2788. else
  2789. break;
  2790. end;
  2791. _GENERIC:
  2792. begin
  2793. handle_unexpected_had_generic;
  2794. if not (m_delphi in current_settings.modeswitches) then
  2795. begin
  2796. hadgeneric:=true;
  2797. consume(_ID);
  2798. end
  2799. else
  2800. break;
  2801. end
  2802. else
  2803. break;
  2804. end;
  2805. end;
  2806. end;
  2807. until false;
  2808. { check for incomplete class definitions, this is only required
  2809. for fpc modes }
  2810. if (m_fpc in current_settings.modeswitches) then
  2811. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2812. end;
  2813. end.