psub.pas 67 KB

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