psub.pas 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  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. cclasses,globals,
  22. node,nbas,
  23. symdef,procinfo;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure add_entry_exit_code;
  28. public
  29. { code for the subroutine as tree }
  30. code : tnode;
  31. { positions in the tree for init/final }
  32. entry_asmnode,
  33. loadpara_asmnode,
  34. exitlabel_asmnode,
  35. stackcheck_asmnode,
  36. init_asmnode,
  37. final_asmnode : tasmnode;
  38. { list to store the procinfo's of the nested procedures }
  39. nestedprocs : tlinkedlist;
  40. constructor create(aparent:tprocinfo);override;
  41. destructor destroy;override;
  42. procedure printproc;
  43. procedure generate_code;
  44. procedure resetprocdef;
  45. procedure add_to_symtablestack;
  46. procedure remove_from_symtablestack;
  47. procedure parse_body;
  48. function stack_tainting_parameter : boolean;
  49. function has_assembler_child : boolean;
  50. end;
  51. procedure printnode_reset;
  52. { reads the declaration blocks }
  53. procedure read_declarations(islibrary : boolean);
  54. { reads declarations in the interface part of a unit }
  55. procedure read_interface_declarations;
  56. procedure generate_specialization_procs;
  57. implementation
  58. uses
  59. sysutils,
  60. { common }
  61. cutils,
  62. { global }
  63. globtype,tokens,verbose,comphook,
  64. systems,
  65. { aasm }
  66. cpubase,aasmbase,aasmtai,aasmdata,
  67. { symtable }
  68. symconst,symbase,symsym,symtype,symtable,defutil,
  69. paramgr,
  70. ppu,fmodule,
  71. { pass 1 }
  72. nutils,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  73. pass_1,
  74. {$ifdef state_tracking}
  75. nstate,
  76. {$endif state_tracking}
  77. { pass 2 }
  78. {$ifndef NOPASS2}
  79. pass_2,
  80. {$endif}
  81. { parser }
  82. scanner,import,gendef,
  83. pbase,pstatmnt,pdecl,pdecsub,pexports,
  84. { codegen }
  85. tgobj,cgbase,cgobj,dbgbase,
  86. ncgutil,regvars,
  87. opttail
  88. {$if defined(arm) or defined(powerpc) or defined(powerpc64)}
  89. ,aasmcpu
  90. {$endif arm}
  91. {$ifndef NOOPT}
  92. {$ifdef i386}
  93. ,aopt386
  94. {$else i386}
  95. ,aopt
  96. {$endif i386}
  97. {$endif}
  98. ;
  99. {****************************************************************************
  100. PROCEDURE/FUNCTION BODY PARSING
  101. ****************************************************************************}
  102. procedure initializevars(p:TObject;arg:pointer);
  103. var
  104. b : tblocknode;
  105. begin
  106. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  107. exit;
  108. with tabstractnormalvarsym(p) do
  109. begin
  110. if assigned(defaultconstsym) then
  111. begin
  112. b:=tblocknode(arg);
  113. b.left:=cstatementnode.create(
  114. cassignmentnode.create(
  115. cloadnode.create(tsym(p),tsym(p).owner),
  116. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  117. b.left);
  118. end;
  119. end;
  120. end;
  121. procedure check_finalize_paras(p:TObject;arg:pointer);
  122. begin
  123. if (tsym(p).typ=paravarsym) and
  124. (tparavarsym(p).varspez=vs_value) and
  125. not is_class(tparavarsym(p).vardef) and
  126. tparavarsym(p).vardef.needs_inittable then
  127. include(current_procinfo.flags,pi_needs_implicit_finally);
  128. end;
  129. procedure check_finalize_locals(p:TObject;arg:pointer);
  130. begin
  131. if (tsym(p).typ=localvarsym) and
  132. (tlocalvarsym(p).refs>0) and
  133. not(vo_is_funcret in tlocalvarsym(p).varoptions) and
  134. not(is_class(tlocalvarsym(p).vardef)) and
  135. tlocalvarsym(p).vardef.needs_inittable then
  136. include(current_procinfo.flags,pi_needs_implicit_finally);
  137. end;
  138. function block(islibrary : boolean) : tnode;
  139. begin
  140. { parse const,types and vars }
  141. read_declarations(islibrary);
  142. { do we have an assembler block without the po_assembler?
  143. we should allow this for Delphi compatibility (PFV) }
  144. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  145. include(current_procinfo.procdef.procoptions,po_assembler);
  146. { Handle assembler block different }
  147. if (po_assembler in current_procinfo.procdef.procoptions) then
  148. begin
  149. block:=assembler_block;
  150. exit;
  151. end;
  152. {Unit initialization?.}
  153. if (
  154. assigned(current_procinfo.procdef.localst) and
  155. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  156. (current_module.is_unit)
  157. ) or
  158. islibrary then
  159. begin
  160. if (token=_END) then
  161. begin
  162. consume(_END);
  163. { We need at least a node, else the entry/exit code is not
  164. generated and thus no PASCALMAIN symbol which we need (PFV) }
  165. if islibrary then
  166. block:=cnothingnode.create
  167. else
  168. block:=nil;
  169. end
  170. else
  171. begin
  172. if token=_INITIALIZATION then
  173. begin
  174. { The library init code is already called and does not
  175. need to be in the initfinal table (PFV) }
  176. if not islibrary then
  177. current_module.flags:=current_module.flags or uf_init;
  178. block:=statement_block(_INITIALIZATION);
  179. end
  180. else if (token=_FINALIZATION) then
  181. begin
  182. if (current_module.flags and uf_finalize)<>0 then
  183. block:=statement_block(_FINALIZATION)
  184. else
  185. begin
  186. { can we allow no INITIALIZATION for DLL ??
  187. I think it should work PM }
  188. block:=nil;
  189. exit;
  190. end;
  191. end
  192. else
  193. begin
  194. { The library init code is already called and does not
  195. need to be in the initfinal table (PFV) }
  196. if not islibrary then
  197. current_module.flags:=current_module.flags or uf_init;
  198. block:=statement_block(_BEGIN);
  199. end;
  200. end;
  201. end
  202. else
  203. begin
  204. block:=statement_block(_BEGIN);
  205. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  206. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  207. end;
  208. end;
  209. {****************************************************************************
  210. PROCEDURE/FUNCTION COMPILING
  211. ****************************************************************************}
  212. procedure printnode_reset;
  213. begin
  214. assign(printnodefile,treelogfilename);
  215. {$I-}
  216. rewrite(printnodefile);
  217. {$I+}
  218. if ioresult<>0 then
  219. begin
  220. Comment(V_Error,'Error creating '+treelogfilename);
  221. exit;
  222. end;
  223. close(printnodefile);
  224. end;
  225. function generate_bodyentry_block:tnode;
  226. var
  227. srsym : tsym;
  228. para : tcallparanode;
  229. newstatement : tstatementnode;
  230. hdef : tdef;
  231. begin
  232. result:=internalstatements(newstatement);
  233. if assigned(current_procinfo.procdef._class) then
  234. begin
  235. { a constructor needs a help procedure }
  236. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  237. begin
  238. if is_class(current_procinfo.procdef._class) then
  239. begin
  240. include(current_procinfo.flags,pi_needs_implicit_finally);
  241. srsym:=search_class_member(current_procinfo.procdef._class,'NEWINSTANCE');
  242. if assigned(srsym) and
  243. (srsym.typ=procsym) then
  244. begin
  245. { if vmt>1 then newinstance }
  246. addstatement(newstatement,cifnode.create(
  247. caddnode.create(gtn,
  248. ctypeconvnode.create_internal(
  249. load_vmt_pointer_node,
  250. voidpointertype),
  251. cpointerconstnode.create(1,voidpointertype)),
  252. cassignmentnode.create(
  253. ctypeconvnode.create_internal(
  254. load_self_pointer_node,
  255. voidpointertype),
  256. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  257. nil));
  258. end
  259. else
  260. internalerror(200305108);
  261. end
  262. else
  263. if is_object(current_procinfo.procdef._class) then
  264. begin
  265. hdef:=current_procinfo.procdef._class;
  266. hdef:=tpointerdef.create(hdef);
  267. { parameter 3 : vmt_offset }
  268. { parameter 2 : address of pointer to vmt,
  269. this is required to allow setting the vmt to -1 to indicate
  270. that memory was allocated }
  271. { parameter 1 : self pointer }
  272. para:=ccallparanode.create(
  273. cordconstnode.create(current_procinfo.procdef._class.vmt_offset,s32inttype,false),
  274. ccallparanode.create(
  275. ctypeconvnode.create_internal(
  276. load_vmt_pointer_node,
  277. voidpointertype),
  278. ccallparanode.create(
  279. ctypeconvnode.create_internal(
  280. load_self_pointer_node,
  281. voidpointertype),
  282. nil)));
  283. addstatement(newstatement,cassignmentnode.create(
  284. ctypeconvnode.create_internal(
  285. load_self_pointer_node,
  286. voidpointertype),
  287. ccallnode.createintern('fpc_help_constructor',para)));
  288. end
  289. else
  290. internalerror(200305103);
  291. { if self=nil then exit
  292. calling fail instead of exit is useless because
  293. there is nothing to dispose (PFV) }
  294. addstatement(newstatement,cifnode.create(
  295. caddnode.create(equaln,
  296. load_self_pointer_node,
  297. cnilnode.create),
  298. cexitnode.create(nil),
  299. nil));
  300. end;
  301. { maybe call BeforeDestruction for classes }
  302. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  303. is_class(current_procinfo.procdef._class) then
  304. begin
  305. srsym:=search_class_member(current_procinfo.procdef._class,'BEFOREDESTRUCTION');
  306. if assigned(srsym) and
  307. (srsym.typ=procsym) then
  308. begin
  309. { if vmt<>0 then beforedestruction }
  310. addstatement(newstatement,cifnode.create(
  311. caddnode.create(unequaln,
  312. load_vmt_pointer_node,
  313. cnilnode.create),
  314. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  315. nil));
  316. end
  317. else
  318. internalerror(200305104);
  319. end;
  320. end;
  321. end;
  322. function generate_bodyexit_block:tnode;
  323. var
  324. srsym : tsym;
  325. para : tcallparanode;
  326. newstatement : tstatementnode;
  327. oldlocalswitches: tlocalswitches;
  328. begin
  329. result:=internalstatements(newstatement);
  330. if assigned(current_procinfo.procdef._class) then
  331. begin
  332. { Don't test self and the vmt here. The reason is that }
  333. { a constructor already checks whether these are valid }
  334. { before. Further, in case of TThread the thread may }
  335. { free the class instance right after AfterConstruction }
  336. { has been called, so it may no longer be valid (JM) }
  337. oldlocalswitches:=current_settings.localswitches;
  338. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  339. { maybe call AfterConstruction for classes }
  340. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  341. is_class(current_procinfo.procdef._class) then
  342. begin
  343. srsym:=search_class_member(current_procinfo.procdef._class,'AFTERCONSTRUCTION');
  344. if assigned(srsym) and
  345. (srsym.typ=procsym) then
  346. begin
  347. { Self can be nil when fail is called }
  348. { if self<>nil and vmt<>nil then afterconstruction }
  349. addstatement(newstatement,cifnode.create(
  350. caddnode.create(andn,
  351. caddnode.create(unequaln,
  352. load_self_pointer_node,
  353. cnilnode.create),
  354. caddnode.create(unequaln,
  355. load_vmt_pointer_node,
  356. cnilnode.create)),
  357. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  358. nil));
  359. end
  360. else
  361. internalerror(200305106);
  362. end;
  363. { a destructor needs a help procedure }
  364. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  365. begin
  366. if is_class(current_procinfo.procdef._class) then
  367. begin
  368. srsym:=search_class_member(current_procinfo.procdef._class,'FREEINSTANCE');
  369. if assigned(srsym) and
  370. (srsym.typ=procsym) then
  371. begin
  372. { if self<>0 and vmt=1 then freeinstance }
  373. addstatement(newstatement,cifnode.create(
  374. caddnode.create(andn,
  375. caddnode.create(unequaln,
  376. load_self_pointer_node,
  377. cnilnode.create),
  378. caddnode.create(equaln,
  379. ctypeconvnode.create(
  380. load_vmt_pointer_node,
  381. voidpointertype),
  382. cpointerconstnode.create(1,voidpointertype))),
  383. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  384. nil));
  385. end
  386. else
  387. internalerror(200305108);
  388. end
  389. else
  390. if is_object(current_procinfo.procdef._class) then
  391. begin
  392. { finalize object data }
  393. if current_procinfo.procdef._class.needs_inittable then
  394. addstatement(newstatement,finalize_data_node(load_self_node));
  395. { parameter 3 : vmt_offset }
  396. { parameter 2 : pointer to vmt }
  397. { parameter 1 : self pointer }
  398. para:=ccallparanode.create(
  399. cordconstnode.create(current_procinfo.procdef._class.vmt_offset,s32inttype,false),
  400. ccallparanode.create(
  401. ctypeconvnode.create_internal(
  402. load_vmt_pointer_node,
  403. voidpointertype),
  404. ccallparanode.create(
  405. ctypeconvnode.create_internal(
  406. load_self_pointer_node,
  407. voidpointertype),
  408. nil)));
  409. addstatement(newstatement,
  410. ccallnode.createintern('fpc_help_destructor',para));
  411. end
  412. else
  413. internalerror(200305105);
  414. end;
  415. current_settings.localswitches:=oldlocalswitches;
  416. end;
  417. end;
  418. function generate_except_block:tnode;
  419. var
  420. pd : tprocdef;
  421. newstatement : tstatementnode;
  422. oldlocalswitches: tlocalswitches;
  423. begin
  424. generate_except_block:=internalstatements(newstatement);
  425. { a constructor needs call destructor (if available) when it
  426. is not inherited }
  427. if assigned(current_procinfo.procdef._class) and
  428. (current_procinfo.procdef.proctypeoption=potype_constructor) then
  429. begin
  430. { Don't test self and the vmt here. See generate_bodyexit_block }
  431. { why (JM) }
  432. oldlocalswitches:=current_settings.localswitches;
  433. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  434. pd:=current_procinfo.procdef._class.Finddestructor;
  435. if assigned(pd) then
  436. begin
  437. { if vmt<>0 then call destructor }
  438. addstatement(newstatement,cifnode.create(
  439. caddnode.create(unequaln,
  440. load_vmt_pointer_node,
  441. cnilnode.create),
  442. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[]),
  443. nil));
  444. end;
  445. current_settings.localswitches:=oldlocalswitches;
  446. end
  447. else
  448. begin
  449. { no constructor }
  450. { must be the return value finalized before reraising the exception? }
  451. if (not is_void(current_procinfo.procdef.returndef)) and
  452. (current_procinfo.procdef.returndef.needs_inittable) and
  453. (not is_class(current_procinfo.procdef.returndef)) then
  454. addstatement(newstatement,finalize_data_node(load_result_node));
  455. end;
  456. end;
  457. {****************************************************************************
  458. TCGProcInfo
  459. ****************************************************************************}
  460. constructor tcgprocinfo.create(aparent:tprocinfo);
  461. begin
  462. inherited Create(aparent);
  463. nestedprocs:=tlinkedlist.create;
  464. end;
  465. destructor tcgprocinfo.destroy;
  466. begin
  467. nestedprocs.free;
  468. if assigned(code) then
  469. code.free;
  470. inherited destroy;
  471. end;
  472. procedure tcgprocinfo.printproc;
  473. begin
  474. assign(printnodefile,treelogfilename);
  475. {$I-}
  476. append(printnodefile);
  477. if ioresult<>0 then
  478. rewrite(printnodefile);
  479. {$I+}
  480. if ioresult<>0 then
  481. begin
  482. Comment(V_Error,'Error creating '+treelogfilename);
  483. exit;
  484. end;
  485. writeln(printnodefile);
  486. writeln(printnodefile,'*******************************************************************************');
  487. writeln(printnodefile,procdef.fullprocname(false));
  488. writeln(printnodefile,'*******************************************************************************');
  489. printnode(printnodefile,code);
  490. close(printnodefile);
  491. end;
  492. procedure tcgprocinfo.add_entry_exit_code;
  493. var
  494. finalcode,
  495. bodyentrycode,
  496. bodyexitcode,
  497. exceptcode : tnode;
  498. newblock : tblocknode;
  499. codestatement,
  500. newstatement : tstatementnode;
  501. oldfilepos : tfileposinfo;
  502. begin
  503. oldfilepos:=current_filepos;
  504. { Generate code/locations used at start of proc }
  505. current_filepos:=entrypos;
  506. entry_asmnode:=casmnode.create_get_position;
  507. loadpara_asmnode:=casmnode.create_get_position;
  508. stackcheck_asmnode:=casmnode.create_get_position;
  509. init_asmnode:=casmnode.create_get_position;
  510. bodyentrycode:=generate_bodyentry_block;
  511. { Generate code/locations used at end of proc }
  512. current_filepos:=exitpos;
  513. exitlabel_asmnode:=casmnode.create_get_position;
  514. final_asmnode:=casmnode.create_get_position;
  515. bodyexitcode:=generate_bodyexit_block;
  516. { Generate procedure by combining init+body+final,
  517. depending on the implicit finally we need to add
  518. an try...finally...end wrapper }
  519. newblock:=internalstatements(newstatement);
  520. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  521. (pi_needs_implicit_finally in flags) and
  522. { but it's useless in init/final code of units }
  523. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) then
  524. begin
  525. { Generate special exception block only needed when
  526. implicit finaly is used }
  527. current_filepos:=exitpos;
  528. exceptcode:=generate_except_block;
  529. { Generate code that will be in the try...finally }
  530. finalcode:=internalstatements(codestatement);
  531. addstatement(codestatement,bodyexitcode);
  532. addstatement(codestatement,final_asmnode);
  533. { Initialize before try...finally...end frame }
  534. addstatement(newstatement,loadpara_asmnode);
  535. addstatement(newstatement,stackcheck_asmnode);
  536. addstatement(newstatement,entry_asmnode);
  537. addstatement(newstatement,init_asmnode);
  538. addstatement(newstatement,bodyentrycode);
  539. current_filepos:=entrypos;
  540. addstatement(newstatement,ctryfinallynode.create_implicit(
  541. code,
  542. finalcode,
  543. exceptcode));
  544. addstatement(newstatement,exitlabel_asmnode);
  545. { set flag the implicit finally has been generated }
  546. include(flags,pi_has_implicit_finally);
  547. end
  548. else
  549. begin
  550. addstatement(newstatement,loadpara_asmnode);
  551. addstatement(newstatement,stackcheck_asmnode);
  552. addstatement(newstatement,entry_asmnode);
  553. addstatement(newstatement,init_asmnode);
  554. addstatement(newstatement,bodyentrycode);
  555. addstatement(newstatement,code);
  556. addstatement(newstatement,exitlabel_asmnode);
  557. addstatement(newstatement,bodyexitcode);
  558. addstatement(newstatement,final_asmnode);
  559. end;
  560. do_firstpass(newblock);
  561. code:=newblock;
  562. current_filepos:=oldfilepos;
  563. end;
  564. procedure clearrefs(p:TObject;arg:pointer);
  565. begin
  566. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  567. if tabstractvarsym(p).refs>1 then
  568. tabstractvarsym(p).refs:=1;
  569. end;
  570. procedure translate_registers(p:TObject;list:pointer);
  571. begin
  572. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  573. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  574. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  575. begin
  576. if not(cs_no_regalloc in current_settings.globalswitches) then
  577. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  578. if cs_asm_source in current_settings.globalswitches then
  579. TAsmList(list).concat(Tai_comment.Create(strpnew('Var '+tabstractnormalvarsym(p).realname+' located in register '+
  580. std_regname(tabstractnormalvarsym(p).localloc.register))))
  581. end;
  582. end;
  583. procedure check_for_stack(p:TObject;arg:pointer);
  584. begin
  585. if tsym(p).typ=paravarsym then
  586. begin
  587. { check if there no parameter of the current procedure is stack dependend }
  588. if is_open_array(tparavarsym(p).vardef) or
  589. is_array_of_const(tparavarsym(p).vardef) then
  590. pboolean(arg)^:=true;
  591. if assigned(p) and
  592. assigned(tparavarsym(p).paraloc[calleeside].location) and
  593. (tparavarsym(p).paraloc[calleeside].location^.loc=LOC_REFERENCE) then
  594. pboolean(arg)^:=true;
  595. end;
  596. end;
  597. function tcgprocinfo.stack_tainting_parameter : boolean;
  598. begin
  599. result:=false;
  600. procdef.parast.SymList.ForEachCall(@check_for_stack,@result);
  601. end;
  602. function tcgprocinfo.has_assembler_child : boolean;
  603. var
  604. hp : tcgprocinfo;
  605. begin
  606. result:=false;
  607. hp:=tcgprocinfo(nestedprocs.first);
  608. while assigned(hp) do
  609. begin
  610. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  611. begin
  612. result:=true;
  613. exit;
  614. end;
  615. hp:=tcgprocinfo(hp.next);
  616. end;
  617. end;
  618. procedure tcgprocinfo.generate_code;
  619. var
  620. oldprocinfo : tprocinfo;
  621. oldmaxfpuregisters : longint;
  622. oldfilepos : tfileposinfo;
  623. templist : TAsmList;
  624. headertai : tai;
  625. begin
  626. { the initialization procedure can be empty, then we
  627. don't need to generate anything. When it was an empty
  628. procedure there would be at least a blocknode }
  629. if not assigned(code) then
  630. exit;
  631. { We need valid code }
  632. if Errorcount<>0 then
  633. exit;
  634. { No code can be generated for generic template }
  635. if (df_generic in procdef.defoptions) then
  636. internalerror(200511152);
  637. { The RA and Tempgen shall not be available yet }
  638. if assigned(tg) then
  639. internalerror(200309201);
  640. oldprocinfo:=current_procinfo;
  641. oldfilepos:=current_filepos;
  642. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  643. current_procinfo:=self;
  644. current_filepos:=entrypos;
  645. templist:=TAsmList.create;
  646. { add parast/localst to symtablestack }
  647. add_to_symtablestack;
  648. { when size optimization only count occurrence }
  649. if cs_opt_size in current_settings.optimizerswitches then
  650. cg.t_times:=1
  651. else
  652. { reference for repetition is 100 }
  653. cg.t_times:=100;
  654. { clear register count }
  655. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  656. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  657. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  658. if (procdef.localst.symtablelevel=main_program_level) and
  659. (not current_module.is_unit) then
  660. include(flags,pi_do_call);
  661. { set implicit_finally flag when there are locals/paras to be finalized }
  662. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  663. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  664. { firstpass everything }
  665. flowcontrol:=[];
  666. do_firstpass(code);
  667. if code.registersfpu>0 then
  668. include(flags,pi_uses_fpu);
  669. { do this before adding the entry code else the tail recursion recognition won't work,
  670. if this causes troubles, it must be if'ed
  671. }
  672. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  673. (pi_is_recursive in flags) then
  674. do_opttail(code,procdef);
  675. { add implicit entry and exit code }
  676. add_entry_exit_code;
  677. { only do secondpass if there are no errors }
  678. if (ErrorCount=0) then
  679. begin
  680. { set the start offset to the start of the temp area in the stack }
  681. tg:=ttgobj.create;
  682. {$if defined(x86) or defined(arm)}
  683. { try to strip the stack frame }
  684. { set the framepointer to esp if:
  685. - no assembler directive, those are handled in assembler_block
  686. in pstatment.pas (for cases not caught by the Delphi
  687. exception below)
  688. - no exceptions are used
  689. - no debug info
  690. - no pushes are used/esp modifications, could be:
  691. * outgoing parameters on the stack
  692. * incoming parameters on the stack
  693. * open arrays
  694. - no inline assembler
  695. or
  696. - Delphi mode
  697. - assembler directive
  698. - no pushes are used/esp modifications, could be:
  699. * outgoing parameters on the stack
  700. * incoming parameters on the stack
  701. * open arrays
  702. - no local variables
  703. }
  704. if ((po_assembler in procdef.procoptions) and
  705. (m_delphi in current_settings.modeswitches) and
  706. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  707. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  708. not(cs_generate_stackframes in current_settings.localswitches) and
  709. not(po_assembler in procdef.procoptions) and
  710. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  711. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  712. pi_needs_stackframe])=[])
  713. {$ifdef arm}
  714. and ((cs_fp_emulation in current_settings.moduleswitches) or not (pi_uses_fpu in flags))
  715. {$endif arm}
  716. )
  717. then
  718. begin
  719. { we need the parameter info here to determine if the procedure gets
  720. parameters on the stack
  721. calling generate_parameter_info doesn't hurt but it costs time
  722. }
  723. generate_parameter_info;
  724. if not(stack_tainting_parameter) and
  725. not(has_assembler_child) and (para_stack_size=0) then
  726. begin
  727. { Only need to set the framepointer }
  728. framepointer:=NR_STACK_POINTER_REG;
  729. tg.direction:=1;
  730. end;
  731. end;
  732. {$endif}
  733. { Create register allocator }
  734. cg.init_register_allocators;
  735. set_first_temp_offset;
  736. generate_parameter_info;
  737. { Allocate space in temp/registers for parast and localst }
  738. current_filepos:=entrypos;
  739. gen_alloc_symtable(aktproccode,procdef.parast);
  740. gen_alloc_symtable(aktproccode,procdef.localst);
  741. { Store temp offset for information about 'real' temps }
  742. tempstart:=tg.lasttemp;
  743. { Generate code to load register parameters in temps and insert local
  744. copies for values parameters. This must be done before the code for the
  745. body is generated because the localloc is updated.
  746. Note: The generated code will be inserted after the code generation of
  747. the body is finished, because only then the position is known }
  748. {$ifdef oldregvars}
  749. assign_regvars(code);
  750. {$endif oldreg}
  751. current_filepos:=entrypos;
  752. { record which registers are allocated here, since all code }
  753. { allocating registers comes after it }
  754. cg.set_regalloc_extend_backwards(true);
  755. gen_load_para_value(templist);
  756. cg.set_regalloc_extend_backwards(false);
  757. { caller paraloc info is also necessary in the stackframe_entry
  758. code of the ppc (and possibly other processors) }
  759. if not procdef.has_paraloc_info then
  760. begin
  761. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  762. procdef.has_paraloc_info:=true;
  763. end;
  764. { generate code for the node tree }
  765. do_secondpass(code);
  766. aktproccode.concatlist(current_asmdata.CurrAsmList);
  767. {$ifdef i386}
  768. procdef.fpu_used:=code.registersfpu;
  769. {$endif i386}
  770. { The position of the loadpara_asmnode is now known }
  771. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  772. { first generate entry and initialize code with the correct
  773. position and switches }
  774. current_filepos:=entrypos;
  775. current_settings.localswitches:=entryswitches;
  776. cg.set_regalloc_extend_backwards(true);
  777. gen_entry_code(templist);
  778. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  779. gen_initialize_code(templist);
  780. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  781. { now generate finalize and exit code with the correct position
  782. and switches }
  783. current_filepos:=exitpos;
  784. current_settings.localswitches:=exitswitches;
  785. cg.set_regalloc_extend_backwards(false);
  786. gen_finalize_code(templist);
  787. { the finalcode must be concated if there was no position available,
  788. using insertlistafter will result in an insert at the start
  789. when currentai=nil }
  790. if assigned(final_asmnode.currenttai) then
  791. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  792. else
  793. aktproccode.concatlist(templist);
  794. { insert exit label at the correct position }
  795. cg.a_label(templist,CurrExitLabel);
  796. if assigned(exitlabel_asmnode.currenttai) then
  797. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  798. else
  799. aktproccode.concatlist(templist);
  800. { exit code }
  801. gen_exit_code(templist);
  802. aktproccode.concatlist(templist);
  803. {$ifdef OLDREGVARS}
  804. { note: this must be done only after as much code as possible has }
  805. { been generated. The result is that when you ungetregister() a }
  806. { regvar, it will actually free the regvar (and alse free the }
  807. { the regvars at the same time). Doing this too early will }
  808. { confuse the register allocator, as the regvars will still be }
  809. { used. It should be done before loading the result regs (so }
  810. { they don't conflict with the regvars) and before }
  811. { gen_entry_code (that one has to be able to allocate the }
  812. { regvars again) (JM) }
  813. free_regvars(aktproccode);
  814. {$endif OLDREGVARS}
  815. { generate symbol and save end of header position }
  816. current_filepos:=entrypos;
  817. gen_proc_symbol(templist);
  818. headertai:=tai(templist.last);
  819. { insert symbol }
  820. aktproccode.insertlist(templist);
  821. { Free space in temp/registers for parast and localst, must be
  822. done after gen_entry_code }
  823. current_filepos:=exitpos;
  824. gen_free_symtable(aktproccode,procdef.localst);
  825. gen_free_symtable(aktproccode,procdef.parast);
  826. { add code that will load the return value, this is not done
  827. for assembler routines when they didn't reference the result
  828. variable }
  829. gen_load_return_value(templist);
  830. aktproccode.concatlist(templist);
  831. { Already reserve all registers for stack checking code and
  832. generate the call to the helper function }
  833. if (cs_check_stack in entryswitches) and
  834. not(po_assembler in procdef.procoptions) and
  835. (procdef.proctypeoption<>potype_proginit) then
  836. begin
  837. current_filepos:=entrypos;
  838. gen_stack_check_call(templist);
  839. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  840. end;
  841. { load got if necessary }
  842. cg.set_regalloc_extend_backwards(true);
  843. current_filepos:=entrypos;
  844. gen_got_load(templist);
  845. aktproccode.insertlistafter(headertai,templist);
  846. cg.set_regalloc_extend_backwards(false);
  847. { The procedure body is finished, we can now
  848. allocate the registers }
  849. cg.do_register_allocation(aktproccode,headertai);
  850. { translate imag. register to their real counter parts
  851. this is necessary for debuginfo and verbose assembler output
  852. when SSA will be implented, this will be more complicated because we've to
  853. maintain location lists }
  854. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  855. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  856. { Add save and restore of used registers }
  857. current_filepos:=entrypos;
  858. gen_save_used_regs(templist);
  859. aktproccode.insertlistafter(headertai,templist);
  860. current_filepos:=exitpos;
  861. gen_restore_used_regs(aktproccode);
  862. { We know the size of the stack, now we can generate the
  863. parameter that is passed to the stack checking code }
  864. if (cs_check_stack in entryswitches) and
  865. not(po_assembler in procdef.procoptions) and
  866. (procdef.proctypeoption<>potype_proginit) then
  867. begin
  868. current_filepos:=entrypos;
  869. gen_stack_check_size_para(templist);
  870. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  871. end;
  872. { Add entry code (stack allocation) after header }
  873. current_filepos:=entrypos;
  874. gen_proc_entry_code(templist);
  875. aktproccode.insertlistafter(headertai,templist);
  876. { Add exit code at the end }
  877. current_filepos:=exitpos;
  878. gen_proc_exit_code(templist);
  879. aktproccode.concatlist(templist);
  880. { check if the implicit finally has been generated. The flag
  881. should already be set in pass1 }
  882. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  883. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  884. (pi_needs_implicit_finally in flags) and
  885. not(pi_has_implicit_finally in flags) then
  886. internalerror(200405231);
  887. {$ifndef NoOpt}
  888. if not(cs_no_regalloc in current_settings.globalswitches) then
  889. begin
  890. if (cs_opt_level1 in current_settings.optimizerswitches) and
  891. { do not optimize pure assembler procedures }
  892. not(pi_is_assembler in flags) then
  893. optimize(aktproccode);
  894. end;
  895. {$endif NoOpt}
  896. {$ifdef ARM}
  897. { because of the limited constant size of the arm, all data access is done pc relative }
  898. insertpcrelativedata(aktproccode,aktlocaldata);
  899. {$endif ARM}
  900. { Add end symbol and debug info }
  901. { this must be done after the pcrelativedata is appended else the distance calculation of
  902. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  903. so it should be inserted before the end symbol (FK)
  904. }
  905. current_filepos:=exitpos;
  906. gen_proc_symbol_end(templist);
  907. aktproccode.concatlist(templist);
  908. {$ifdef POWERPC}
  909. fixup_jmps(aktproccode);
  910. {$endif POWERPC}
  911. {$ifdef POWERPC64}
  912. fixup_jmps(aktproccode);
  913. {$endif POWERPC64}
  914. { insert line debuginfo }
  915. if (cs_debuginfo in current_settings.moduleswitches) or
  916. (cs_use_lineinfo in current_settings.globalswitches) then
  917. debuginfo.insertlineinfo(aktproccode);
  918. { add the procedure to the al_procedures }
  919. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  920. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  921. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  922. { save local data (casetable) also in the same file }
  923. if assigned(aktlocaldata) and
  924. (not aktlocaldata.empty) then
  925. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  926. { only now we can remove the temps }
  927. tg.resettempgen;
  928. { stop tempgen and ra }
  929. tg.free;
  930. cg.done_register_allocators;
  931. tg:=nil;
  932. end;
  933. { restore symtablestack }
  934. remove_from_symtablestack;
  935. { restore }
  936. templist.free;
  937. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  938. current_filepos:=oldfilepos;
  939. current_procinfo:=oldprocinfo;
  940. end;
  941. procedure tcgprocinfo.add_to_symtablestack;
  942. var
  943. _class,hp : tobjectdef;
  944. begin
  945. { insert symtables for the class, but only if it is no nested function }
  946. if assigned(procdef._class) and
  947. not(assigned(parent) and
  948. assigned(parent.procdef) and
  949. assigned(parent.procdef._class)) then
  950. begin
  951. { insert them in the reverse order }
  952. hp:=nil;
  953. repeat
  954. _class:=procdef._class;
  955. while _class.childof<>hp do
  956. _class:=_class.childof;
  957. hp:=_class;
  958. symtablestack.push(_class.symtable);
  959. until hp=procdef._class;
  960. end;
  961. { insert parasymtable in symtablestack when parsing
  962. a function }
  963. if procdef.parast.symtablelevel>=normal_function_level then
  964. symtablestack.push(procdef.parast);
  965. { insert localsymtable }
  966. symtablestack.push(procdef.localst);
  967. end;
  968. procedure tcgprocinfo.remove_from_symtablestack;
  969. var
  970. _class : tobjectdef;
  971. begin
  972. { remove localsymtable }
  973. symtablestack.pop(procdef.localst);
  974. { remove parasymtable }
  975. if procdef.parast.symtablelevel>=normal_function_level then
  976. symtablestack.pop(procdef.parast);
  977. { remove symtables for the class, but only if it is no nested function }
  978. if assigned(procdef._class) and
  979. not(assigned(parent) and
  980. assigned(parent.procdef) and
  981. assigned(parent.procdef._class)) then
  982. begin
  983. _class:=procdef._class;
  984. while assigned(_class) do
  985. begin
  986. symtablestack.pop(_class.symtable);
  987. _class:=_class.childof;
  988. end;
  989. end;
  990. end;
  991. procedure tcgprocinfo.resetprocdef;
  992. begin
  993. { remove code tree, if not inline procedure }
  994. if assigned(code) then
  995. begin
  996. { the inline procedure has already got a copy of the tree
  997. stored in procdef.inlininginfo }
  998. code.free;
  999. code:=nil;
  1000. end;
  1001. end;
  1002. function checknodeinlining(procdef: tprocdef): boolean;
  1003. var
  1004. i : integer;
  1005. currpara : tparavarsym;
  1006. begin
  1007. result := false;
  1008. if (pi_has_assembler_block in current_procinfo.flags) then
  1009. exit;
  1010. for i:=0 to procdef.paras.count-1 do
  1011. begin
  1012. currpara:=tparavarsym(procdef.paras[i]);
  1013. { we can't handle formaldefs and special arrays (the latter may need a }
  1014. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  1015. { you have to add 1 to all index operations if you directly inline it }
  1016. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  1017. (currpara.vardef.typ=formaldef)) or
  1018. is_special_array(currpara.vardef) then
  1019. exit;
  1020. end;
  1021. result:=true;
  1022. end;
  1023. procedure tcgprocinfo.parse_body;
  1024. var
  1025. oldprocinfo : tprocinfo;
  1026. oldblock_type : tblock_type;
  1027. st : TSymtable;
  1028. begin
  1029. oldprocinfo:=current_procinfo;
  1030. oldblock_type:=block_type;
  1031. { reset break and continue labels }
  1032. block_type:=bt_body;
  1033. current_procinfo:=self;
  1034. { calculate the lexical level }
  1035. if procdef.parast.symtablelevel>maxnesting then
  1036. Message(parser_e_too_much_lexlevel);
  1037. { static is also important for local procedures !! }
  1038. if (po_staticmethod in procdef.procoptions) then
  1039. allow_only_static:=true
  1040. else if (procdef.parast.symtablelevel=normal_function_level) then
  1041. allow_only_static:=false;
  1042. {$ifdef state_tracking}
  1043. { aktstate:=Tstate_storage.create;}
  1044. {$endif state_tracking}
  1045. { allocate the symbol for this procedure }
  1046. alloc_proc_symbol(procdef);
  1047. { add parast/localst to symtablestack }
  1048. add_to_symtablestack;
  1049. { save entry info }
  1050. entrypos:=current_filepos;
  1051. entryswitches:=current_settings.localswitches;
  1052. if (df_generic in procdef.defoptions) then
  1053. begin
  1054. { start token recorder for generic template }
  1055. procdef.initgeneric;
  1056. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1057. end;
  1058. { parse the code ... }
  1059. code:=block(current_module.islibrary);
  1060. if (df_generic in procdef.defoptions) then
  1061. begin
  1062. { stop token recorder for generic template }
  1063. current_scanner.stoprecordtokens;
  1064. { Give a warning for accesses in the static symtable that aren't visible
  1065. outside the current unit }
  1066. st:=procdef.owner;
  1067. while (st.symtabletype=ObjectSymtable) do
  1068. st:=st.defowner.owner;
  1069. if (pi_uses_static_symtable in flags) and
  1070. (st.symtabletype<>staticsymtable) then
  1071. Comment(V_Warning,'Global Generic template references static symtable');
  1072. end;
  1073. { save exit info }
  1074. exitswitches:=current_settings.localswitches;
  1075. exitpos:=last_endtoken_filepos;
  1076. { the procedure is now defined }
  1077. procdef.forwarddef:=false;
  1078. if assigned(code) then
  1079. begin
  1080. { get a better entry point }
  1081. entrypos:=code.fileinfo;
  1082. { Finish type checking pass }
  1083. do_typecheckpass(code);
  1084. end;
  1085. { Check for unused labels, forwards, symbols for procedures. Static
  1086. symtable is checked in pmodules.
  1087. The check must be done after the typecheckpass }
  1088. if (Errorcount=0) and
  1089. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1090. begin
  1091. { check if forwards are resolved }
  1092. tstoredsymtable(procdef.localst).check_forwards;
  1093. { check if all labels are used }
  1094. tstoredsymtable(procdef.localst).checklabels;
  1095. { remove cross unit overloads }
  1096. tstoredsymtable(procdef.localst).unchain_overloaded;
  1097. { check for unused symbols, but only if there is no asm block }
  1098. if not(pi_has_assembler_block in flags) then
  1099. begin
  1100. tstoredsymtable(procdef.localst).allsymbolsused;
  1101. tstoredsymtable(procdef.parast).allsymbolsused;
  1102. end;
  1103. end;
  1104. if (po_inline in procdef.procoptions) then
  1105. begin
  1106. { Can we inline this procedure? }
  1107. if checknodeinlining(procdef) then
  1108. begin
  1109. new(procdef.inlininginfo);
  1110. include(procdef.procoptions,po_has_inlininginfo);
  1111. procdef.inlininginfo^.code:=code.getcopy;
  1112. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1113. { The blocknode needs to set an exit label }
  1114. if procdef.inlininginfo^.code.nodetype=blockn then
  1115. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1116. end;
  1117. end;
  1118. { Print the node to tree.log }
  1119. if paraprintnodetree=1 then
  1120. printproc;
  1121. { ... remove symbol tables }
  1122. remove_from_symtablestack;
  1123. {$ifdef state_tracking}
  1124. { aktstate.destroy;}
  1125. {$endif state_tracking}
  1126. { reset to normal non static function }
  1127. if (procdef.parast.symtablelevel=normal_function_level) then
  1128. allow_only_static:=false;
  1129. current_procinfo:=oldprocinfo;
  1130. { Restore old state }
  1131. block_type:=oldblock_type;
  1132. end;
  1133. {****************************************************************************
  1134. PROCEDURE/FUNCTION PARSING
  1135. ****************************************************************************}
  1136. procedure check_init_paras(p:TObject;arg:pointer);
  1137. begin
  1138. if tsym(p).typ<>paravarsym then
  1139. exit;
  1140. with tparavarsym(p) do
  1141. if (not is_class(vardef) and
  1142. vardef.needs_inittable and
  1143. (varspez in [vs_value,vs_out])) then
  1144. include(current_procinfo.flags,pi_do_call);
  1145. end;
  1146. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1147. {
  1148. Parses the procedure directives, then parses the procedure body, then
  1149. generates the code for it
  1150. }
  1151. procedure do_generate_code(pi:tcgprocinfo);
  1152. var
  1153. hpi : tcgprocinfo;
  1154. begin
  1155. { generate code for this procedure }
  1156. pi.generate_code;
  1157. { process nested procs }
  1158. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1159. while assigned(hpi) do
  1160. begin
  1161. do_generate_code(hpi);
  1162. hpi:=tcgprocinfo(hpi.next);
  1163. end;
  1164. pi.resetprocdef;
  1165. end;
  1166. var
  1167. oldfailtokenmode : tmodeswitch;
  1168. isnestedproc : boolean;
  1169. begin
  1170. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1171. { create a new procedure }
  1172. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1173. current_module.procinfo:=current_procinfo;
  1174. current_procinfo.procdef:=pd;
  1175. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1176. { Insert mangledname }
  1177. pd.aliasnames.insert(pd.mangledname);
  1178. { Handle Export of this procedure }
  1179. if (po_exports in pd.procoptions) and
  1180. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1181. begin
  1182. pd.aliasnames.insert(pd.procsym.realname);
  1183. if cs_link_deffile in current_settings.globalswitches then
  1184. deffile.AddExport(pd.mangledname);
  1185. end;
  1186. { Insert result variables in the localst }
  1187. insert_funcret_local(pd);
  1188. { check if there are para's which require initing -> set }
  1189. { pi_do_call (if not yet set) }
  1190. if not(pi_do_call in current_procinfo.flags) then
  1191. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1192. { set _FAIL as keyword if constructor }
  1193. if (pd.proctypeoption=potype_constructor) then
  1194. begin
  1195. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1196. tokeninfo^[_FAIL].keyword:=m_all;
  1197. end;
  1198. tcgprocinfo(current_procinfo).parse_body;
  1199. { When it's a nested procedure then defer the code generation,
  1200. when back at normal function level then generate the code
  1201. for all defered nested procedures and the current procedure }
  1202. if isnestedproc then
  1203. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1204. else
  1205. begin
  1206. { We can't support inlining for procedures that have nested
  1207. procedures because the nested procedures use a fixed offset
  1208. for accessing locals in the parent procedure (PFV) }
  1209. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1210. begin
  1211. if (df_generic in current_procinfo.procdef.defoptions) then
  1212. {$warning TODO Add error message for nested procs in generics}
  1213. internalerror(200511151)
  1214. else if (po_inline in current_procinfo.procdef.procoptions) then
  1215. begin
  1216. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1217. Message(parser_w_inlining_disabled);
  1218. current_procinfo.procdef.proccalloption:=pocall_default;
  1219. end;
  1220. end;
  1221. if not(df_generic in current_procinfo.procdef.defoptions) then
  1222. do_generate_code(tcgprocinfo(current_procinfo));
  1223. end;
  1224. { reset _FAIL as _SELF normal }
  1225. if (pd.proctypeoption=potype_constructor) then
  1226. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1227. { release procinfo }
  1228. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1229. internalerror(200304274);
  1230. current_module.procinfo:=current_procinfo.parent;
  1231. { For specialization we didn't record the last semicolon. Moving this parsing
  1232. into the parse_body routine is not done because of having better file position
  1233. information available }
  1234. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1235. consume(_SEMICOLON);
  1236. if not isnestedproc then
  1237. { current_procinfo is checked for nil later on }
  1238. freeandnil(current_procinfo);
  1239. end;
  1240. procedure read_proc;
  1241. {
  1242. Parses the procedure directives, then parses the procedure body, then
  1243. generates the code for it
  1244. }
  1245. procedure do_generate_code(pi:tcgprocinfo);
  1246. var
  1247. hpi : tcgprocinfo;
  1248. begin
  1249. { generate code for this procedure }
  1250. pi.generate_code;
  1251. { process nested procs }
  1252. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1253. while assigned(hpi) do
  1254. begin
  1255. do_generate_code(hpi);
  1256. hpi:=tcgprocinfo(hpi.next);
  1257. end;
  1258. pi.resetprocdef;
  1259. end;
  1260. var
  1261. old_current_procinfo : tprocinfo;
  1262. pdflags : tpdflags;
  1263. pd,firstpd : tprocdef;
  1264. s : string;
  1265. begin
  1266. { save old state }
  1267. old_current_procinfo:=current_procinfo;
  1268. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1269. to an other procdef }
  1270. current_procinfo:=nil;
  1271. { parse procedure declaration }
  1272. if assigned(old_current_procinfo) and
  1273. assigned(old_current_procinfo.procdef) then
  1274. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1275. else
  1276. pd:=parse_proc_dec(nil);
  1277. { set the default function options }
  1278. if parse_only then
  1279. begin
  1280. pd.forwarddef:=true;
  1281. { set also the interface flag, for better error message when the
  1282. implementation doesn't much this header }
  1283. pd.interfacedef:=true;
  1284. include(pd.procoptions,po_global);
  1285. pdflags:=[pd_interface];
  1286. end
  1287. else
  1288. begin
  1289. pdflags:=[pd_body];
  1290. if (not current_module.in_interface) then
  1291. include(pdflags,pd_implemen);
  1292. if (not current_module.is_unit) or
  1293. maybe_smartlink_symbol or
  1294. {
  1295. taking addresses of static procedures goes wrong
  1296. if they aren't global when pic is used (FK)
  1297. }
  1298. (cs_create_pic in current_settings.moduleswitches) then
  1299. include(pd.procoptions,po_global);
  1300. pd.forwarddef:=false;
  1301. end;
  1302. { parse the directives that may follow }
  1303. parse_proc_directives(pd,pdflags);
  1304. { hint directives, these can be separated by semicolons here,
  1305. that needs to be handled here with a loop (PFV) }
  1306. while try_consume_hintdirective(pd.symoptions) do
  1307. Consume(_SEMICOLON);
  1308. { Set calling convention }
  1309. handle_calling_convention(pd);
  1310. { search for forward declarations }
  1311. if not proc_add_definition(pd) then
  1312. begin
  1313. { A method must be forward defined (in the object declaration) }
  1314. if assigned(pd._class) and
  1315. (not assigned(old_current_procinfo.procdef._class)) then
  1316. begin
  1317. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1318. tprocsym(pd.procsym).write_parameter_lists(pd);
  1319. end
  1320. else
  1321. begin
  1322. { Give a better error if there is a forward def in the interface and only
  1323. a single implementation }
  1324. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1325. if (not pd.forwarddef) and
  1326. (not pd.interfacedef) and
  1327. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1328. firstpd.forwarddef and
  1329. firstpd.interfacedef and
  1330. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1331. { don't give an error if it may be an overload }
  1332. not(m_fpc in current_settings.modeswitches) and
  1333. (not(po_overload in pd.procoptions) or
  1334. not(po_overload in firstpd.procoptions)) then
  1335. begin
  1336. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1337. tprocsym(pd.procsym).write_parameter_lists(pd);
  1338. end;
  1339. end;
  1340. end;
  1341. { Set mangled name }
  1342. proc_set_mangledname(pd);
  1343. { compile procedure when a body is needed }
  1344. if (pd_body in pdflags) then
  1345. begin
  1346. read_proc_body(old_current_procinfo,pd);
  1347. end
  1348. else
  1349. begin
  1350. { Handle imports }
  1351. if (po_external in pd.procoptions) then
  1352. begin
  1353. { External declared in implementation, and there was already a
  1354. forward (or interface) declaration then we need to generate
  1355. a stub that calls the external routine }
  1356. if (not pd.forwarddef) and
  1357. (pd.hasforward) and
  1358. not(
  1359. assigned(pd.import_dll) and
  1360. (target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1361. system_arm_wince,system_i386_wince])
  1362. ) then
  1363. begin
  1364. s:=proc_get_importname(pd);
  1365. if s<>'' then
  1366. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1367. end;
  1368. { Import DLL specified? }
  1369. if assigned(pd.import_dll) then
  1370. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1371. else
  1372. begin
  1373. { add import name to external list for DLL scanning }
  1374. if tf_has_dllscanner in target_info.flags then
  1375. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1376. end;
  1377. end;
  1378. end;
  1379. { make sure that references to forward-declared functions are not }
  1380. { treated as references to external symbols, needed for darwin. }
  1381. { make sure we don't change the binding of real external symbols }
  1382. if not(po_external in pd.procoptions) then
  1383. begin
  1384. if (po_global in pd.procoptions) or
  1385. (cs_profile in current_settings.moduleswitches) then
  1386. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1387. else
  1388. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1389. end;
  1390. current_procinfo:=old_current_procinfo;
  1391. end;
  1392. {****************************************************************************
  1393. DECLARATION PARSING
  1394. ****************************************************************************}
  1395. { search in symtablestack for not complete classes }
  1396. procedure check_forward_class(p:TObject;arg:pointer);
  1397. begin
  1398. if (tsym(p).typ=typesym) and
  1399. (ttypesym(p).typedef.typ=objectdef) and
  1400. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1401. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1402. end;
  1403. procedure read_declarations(islibrary : boolean);
  1404. begin
  1405. repeat
  1406. if not assigned(current_procinfo) then
  1407. internalerror(200304251);
  1408. case token of
  1409. _LABEL:
  1410. label_dec;
  1411. _CONST:
  1412. const_dec;
  1413. _TYPE:
  1414. type_dec;
  1415. _VAR:
  1416. var_dec;
  1417. _THREADVAR:
  1418. threadvar_dec;
  1419. _CONSTRUCTOR,
  1420. _DESTRUCTOR,
  1421. _FUNCTION,
  1422. _PROCEDURE,
  1423. _OPERATOR,
  1424. _CLASS:
  1425. read_proc;
  1426. _EXPORTS:
  1427. begin
  1428. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1429. begin
  1430. Message(parser_e_syntax_error);
  1431. consume_all_until(_SEMICOLON);
  1432. end
  1433. else if islibrary or
  1434. (target_info.system in system_unit_program_exports) then
  1435. read_exports
  1436. else
  1437. begin
  1438. Message(parser_w_unsupported_feature);
  1439. consume(_BEGIN);
  1440. end;
  1441. end
  1442. else
  1443. begin
  1444. case idtoken of
  1445. _RESOURCESTRING :
  1446. begin
  1447. { m_class is needed, because the resourcestring
  1448. loading is in the ObjPas unit }
  1449. { if (m_class in current_settings.modeswitches) then}
  1450. resourcestring_dec
  1451. { else
  1452. break;}
  1453. end;
  1454. _PROPERTY:
  1455. begin
  1456. if (m_fpc in current_settings.modeswitches) then
  1457. property_dec
  1458. else
  1459. break;
  1460. end;
  1461. else
  1462. break;
  1463. end;
  1464. end;
  1465. end;
  1466. until false;
  1467. { check for incomplete class definitions, this is only required
  1468. for fpc modes }
  1469. if (m_fpc in current_settings.modeswitches) then
  1470. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1471. end;
  1472. procedure read_interface_declarations;
  1473. begin
  1474. repeat
  1475. case token of
  1476. _CONST :
  1477. const_dec;
  1478. _TYPE :
  1479. type_dec;
  1480. _VAR :
  1481. var_dec;
  1482. _THREADVAR :
  1483. threadvar_dec;
  1484. _FUNCTION,
  1485. _PROCEDURE,
  1486. _OPERATOR :
  1487. read_proc;
  1488. else
  1489. begin
  1490. case idtoken of
  1491. _RESOURCESTRING :
  1492. resourcestring_dec;
  1493. _PROPERTY:
  1494. begin
  1495. if (m_fpc in current_settings.modeswitches) then
  1496. property_dec
  1497. else
  1498. break;
  1499. end;
  1500. else
  1501. break;
  1502. end;
  1503. end;
  1504. end;
  1505. until false;
  1506. { check for incomplete class definitions, this is only required
  1507. for fpc modes }
  1508. if (m_fpc in current_settings.modeswitches) then
  1509. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1510. end;
  1511. {****************************************************************************
  1512. SPECIALIZATION BODY GENERATION
  1513. ****************************************************************************}
  1514. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1515. var
  1516. i : longint;
  1517. hp : tdef;
  1518. oldcurrent_filepos : tfileposinfo;
  1519. begin
  1520. if not((tsym(p).typ=typesym) and
  1521. (ttypesym(p).typedef.typ=objectdef) and
  1522. (df_specialization in ttypesym(p).typedef.defoptions)
  1523. ) then
  1524. exit;
  1525. { definitions }
  1526. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1527. begin
  1528. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1529. if hp.typ=procdef then
  1530. begin
  1531. if assigned(tprocdef(hp).genericdef) and
  1532. (tprocdef(hp).genericdef.typ=procdef) and
  1533. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1534. begin
  1535. oldcurrent_filepos:=current_filepos;
  1536. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1537. current_tokenpos:=current_filepos;
  1538. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1539. read_proc_body(nil,tprocdef(hp));
  1540. current_filepos:=oldcurrent_filepos;
  1541. end
  1542. else
  1543. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1544. end;
  1545. end;
  1546. end;
  1547. procedure generate_specialization_procs;
  1548. begin
  1549. if assigned(current_module.globalsymtable) then
  1550. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1551. if assigned(current_module.localsymtable) then
  1552. begin
  1553. symtablestack.push(current_module.localsymtable);
  1554. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1555. symtablestack.pop(current_module.localsymtable);
  1556. end;
  1557. end;
  1558. end.