psub.pas 63 KB

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