psub.pas 70 KB

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