psub.pas 105 KB

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