psub.pas 64 KB

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