psub.pas 109 KB

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