psub.pas 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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. {$if defined(x86) or defined(arm)}
  668. { set implicit_finally flag for if procedure is safecall }
  669. if procdef.proccalloption=pocall_safecall then
  670. include(flags, pi_needs_implicit_finally);
  671. {$endif}
  672. { firstpass everything }
  673. flowcontrol:=[];
  674. do_firstpass(code);
  675. if code.registersfpu>0 then
  676. include(flags,pi_uses_fpu);
  677. { do this before adding the entry code else the tail recursion recognition won't work,
  678. if this causes troubles, it must be if'ed
  679. }
  680. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  681. (pi_is_recursive in flags) then
  682. do_opttail(code,procdef);
  683. { add implicit entry and exit code }
  684. add_entry_exit_code;
  685. { only do secondpass if there are no errors }
  686. if (ErrorCount=0) then
  687. begin
  688. { set the start offset to the start of the temp area in the stack }
  689. tg:=ttgobj.create;
  690. {$if defined(x86) or defined(arm)}
  691. { try to strip the stack frame }
  692. { set the framepointer to esp if:
  693. - no assembler directive, those are handled in assembler_block
  694. in pstatment.pas (for cases not caught by the Delphi
  695. exception below)
  696. - no exceptions are used
  697. - no debug info
  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 space in temp/registers for parast and localst }
  745. current_filepos:=entrypos;
  746. gen_alloc_symtable(aktproccode,procdef.parast);
  747. gen_alloc_symtable(aktproccode,procdef.localst);
  748. { Store temp offset for information about 'real' temps }
  749. tempstart:=tg.lasttemp;
  750. { Generate code to load register parameters in temps and insert local
  751. copies for values parameters. This must be done before the code for the
  752. body is generated because the localloc is updated.
  753. Note: The generated code will be inserted after the code generation of
  754. the body is finished, because only then the position is known }
  755. {$ifdef oldregvars}
  756. assign_regvars(code);
  757. {$endif oldreg}
  758. current_filepos:=entrypos;
  759. { record which registers are allocated here, since all code }
  760. { allocating registers comes after it }
  761. cg.set_regalloc_extend_backwards(true);
  762. gen_load_para_value(templist);
  763. cg.set_regalloc_extend_backwards(false);
  764. { caller paraloc info is also necessary in the stackframe_entry
  765. code of the ppc (and possibly other processors) }
  766. if not procdef.has_paraloc_info then
  767. begin
  768. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  769. procdef.has_paraloc_info:=true;
  770. end;
  771. { generate code for the node tree }
  772. do_secondpass(code);
  773. aktproccode.concatlist(current_asmdata.CurrAsmList);
  774. {$ifdef i386}
  775. procdef.fpu_used:=code.registersfpu;
  776. {$endif i386}
  777. { The position of the loadpara_asmnode is now known }
  778. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  779. { first generate entry and initialize code with the correct
  780. position and switches }
  781. current_filepos:=entrypos;
  782. current_settings.localswitches:=entryswitches;
  783. cg.set_regalloc_extend_backwards(true);
  784. gen_entry_code(templist);
  785. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  786. gen_initialize_code(templist);
  787. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  788. { now generate finalize and exit code with the correct position
  789. and switches }
  790. current_filepos:=exitpos;
  791. current_settings.localswitches:=exitswitches;
  792. cg.set_regalloc_extend_backwards(false);
  793. gen_finalize_code(templist);
  794. { the finalcode must be concated if there was no position available,
  795. using insertlistafter will result in an insert at the start
  796. when currentai=nil }
  797. if assigned(final_asmnode.currenttai) then
  798. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  799. else
  800. aktproccode.concatlist(templist);
  801. { insert exit label at the correct position }
  802. cg.a_label(templist,CurrExitLabel);
  803. if assigned(exitlabel_asmnode.currenttai) then
  804. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  805. else
  806. aktproccode.concatlist(templist);
  807. { exit code }
  808. gen_exit_code(templist);
  809. aktproccode.concatlist(templist);
  810. {$ifdef OLDREGVARS}
  811. { note: this must be done only after as much code as possible has }
  812. { been generated. The result is that when you ungetregister() a }
  813. { regvar, it will actually free the regvar (and alse free the }
  814. { the regvars at the same time). Doing this too early will }
  815. { confuse the register allocator, as the regvars will still be }
  816. { used. It should be done before loading the result regs (so }
  817. { they don't conflict with the regvars) and before }
  818. { gen_entry_code (that one has to be able to allocate the }
  819. { regvars again) (JM) }
  820. free_regvars(aktproccode);
  821. {$endif OLDREGVARS}
  822. { generate symbol and save end of header position }
  823. current_filepos:=entrypos;
  824. gen_proc_symbol(templist);
  825. headertai:=tai(templist.last);
  826. { insert symbol }
  827. aktproccode.insertlist(templist);
  828. { Free space in temp/registers for parast and localst, must be
  829. done after gen_entry_code }
  830. current_filepos:=exitpos;
  831. gen_free_symtable(aktproccode,procdef.localst);
  832. gen_free_symtable(aktproccode,procdef.parast);
  833. { add code that will load the return value, this is not done
  834. for assembler routines when they didn't reference the result
  835. variable }
  836. gen_load_return_value(templist);
  837. aktproccode.concatlist(templist);
  838. { Already reserve all registers for stack checking code and
  839. generate the call to the helper function }
  840. if (cs_check_stack in entryswitches) and
  841. not(po_assembler in procdef.procoptions) and
  842. (procdef.proctypeoption<>potype_proginit) then
  843. begin
  844. current_filepos:=entrypos;
  845. gen_stack_check_call(templist);
  846. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  847. end;
  848. { load got if necessary }
  849. cg.set_regalloc_extend_backwards(true);
  850. current_filepos:=entrypos;
  851. gen_got_load(templist);
  852. aktproccode.insertlistafter(headertai,templist);
  853. cg.set_regalloc_extend_backwards(false);
  854. { The procedure body is finished, we can now
  855. allocate the registers }
  856. cg.do_register_allocation(aktproccode,headertai);
  857. { translate imag. register to their real counter parts
  858. this is necessary for debuginfo and verbose assembler output
  859. when SSA will be implented, this will be more complicated because we've to
  860. maintain location lists }
  861. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  862. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  863. { Add save and restore of used registers }
  864. current_filepos:=entrypos;
  865. gen_save_used_regs(templist);
  866. aktproccode.insertlistafter(headertai,templist);
  867. current_filepos:=exitpos;
  868. gen_restore_used_regs(aktproccode);
  869. { We know the size of the stack, now we can generate the
  870. parameter that is passed to the stack checking code }
  871. if (cs_check_stack in entryswitches) and
  872. not(po_assembler in procdef.procoptions) and
  873. (procdef.proctypeoption<>potype_proginit) then
  874. begin
  875. current_filepos:=entrypos;
  876. gen_stack_check_size_para(templist);
  877. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  878. end;
  879. { Add entry code (stack allocation) after header }
  880. current_filepos:=entrypos;
  881. gen_proc_entry_code(templist);
  882. aktproccode.insertlistafter(headertai,templist);
  883. {$if defined(x86) or defined(arm)}
  884. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  885. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  886. (procdef.proccalloption=pocall_safecall) then
  887. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  888. {$endif}
  889. { Add exit code at the end }
  890. current_filepos:=exitpos;
  891. gen_proc_exit_code(templist);
  892. aktproccode.concatlist(templist);
  893. { check if the implicit finally has been generated. The flag
  894. should already be set in pass1 }
  895. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  896. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  897. (pi_needs_implicit_finally in flags) and
  898. not(pi_has_implicit_finally in flags) then
  899. internalerror(200405231);
  900. {$ifndef NoOpt}
  901. if not(cs_no_regalloc in current_settings.globalswitches) then
  902. begin
  903. if (cs_opt_level1 in current_settings.optimizerswitches) and
  904. { do not optimize pure assembler procedures }
  905. not(pi_is_assembler in flags) then
  906. optimize(aktproccode);
  907. end;
  908. {$endif NoOpt}
  909. {$ifdef ARM}
  910. { because of the limited constant size of the arm, all data access is done pc relative }
  911. insertpcrelativedata(aktproccode,aktlocaldata);
  912. {$endif ARM}
  913. { Add end symbol and debug info }
  914. { this must be done after the pcrelativedata is appended else the distance calculation of
  915. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  916. so it should be inserted before the end symbol (FK)
  917. }
  918. current_filepos:=exitpos;
  919. gen_proc_symbol_end(templist);
  920. aktproccode.concatlist(templist);
  921. {$if defined(POWERPC) or defined(POWERPC64)}
  922. fixup_jmps(aktproccode);
  923. {$endif}
  924. { insert line debuginfo }
  925. if (cs_debuginfo in current_settings.moduleswitches) or
  926. (cs_use_lineinfo in current_settings.globalswitches) then
  927. debuginfo.insertlineinfo(aktproccode);
  928. { add the procedure to the al_procedures }
  929. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  930. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  931. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  932. { save local data (casetable) also in the same file }
  933. if assigned(aktlocaldata) and
  934. (not aktlocaldata.empty) then
  935. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  936. { only now we can remove the temps }
  937. tg.resettempgen;
  938. { stop tempgen and ra }
  939. tg.free;
  940. cg.done_register_allocators;
  941. tg:=nil;
  942. end;
  943. { restore symtablestack }
  944. remove_from_symtablestack;
  945. { restore }
  946. templist.free;
  947. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  948. current_filepos:=oldfilepos;
  949. current_procinfo:=oldprocinfo;
  950. end;
  951. procedure tcgprocinfo.add_to_symtablestack;
  952. var
  953. _class,hp : tobjectdef;
  954. begin
  955. { insert symtables for the class, but only if it is no nested function }
  956. if assigned(procdef._class) and
  957. not(assigned(parent) and
  958. assigned(parent.procdef) and
  959. assigned(parent.procdef._class)) then
  960. begin
  961. { insert them in the reverse order }
  962. hp:=nil;
  963. repeat
  964. _class:=procdef._class;
  965. while _class.childof<>hp do
  966. _class:=_class.childof;
  967. hp:=_class;
  968. symtablestack.push(_class.symtable);
  969. until hp=procdef._class;
  970. end;
  971. { insert parasymtable in symtablestack when parsing
  972. a function }
  973. if procdef.parast.symtablelevel>=normal_function_level then
  974. symtablestack.push(procdef.parast);
  975. { insert localsymtable }
  976. symtablestack.push(procdef.localst);
  977. end;
  978. procedure tcgprocinfo.remove_from_symtablestack;
  979. var
  980. _class : tobjectdef;
  981. begin
  982. { remove localsymtable }
  983. symtablestack.pop(procdef.localst);
  984. { remove parasymtable }
  985. if procdef.parast.symtablelevel>=normal_function_level then
  986. symtablestack.pop(procdef.parast);
  987. { remove symtables for the class, but only if it is no nested function }
  988. if assigned(procdef._class) and
  989. not(assigned(parent) and
  990. assigned(parent.procdef) and
  991. assigned(parent.procdef._class)) then
  992. begin
  993. _class:=procdef._class;
  994. while assigned(_class) do
  995. begin
  996. symtablestack.pop(_class.symtable);
  997. _class:=_class.childof;
  998. end;
  999. end;
  1000. end;
  1001. procedure tcgprocinfo.resetprocdef;
  1002. begin
  1003. { remove code tree, if not inline procedure }
  1004. if assigned(code) then
  1005. begin
  1006. { the inline procedure has already got a copy of the tree
  1007. stored in procdef.inlininginfo }
  1008. code.free;
  1009. code:=nil;
  1010. end;
  1011. end;
  1012. function checknodeinlining(procdef: tprocdef): boolean;
  1013. var
  1014. i : integer;
  1015. currpara : tparavarsym;
  1016. begin
  1017. result := false;
  1018. if (pi_has_assembler_block in current_procinfo.flags) then
  1019. exit;
  1020. for i:=0 to procdef.paras.count-1 do
  1021. begin
  1022. currpara:=tparavarsym(procdef.paras[i]);
  1023. { we can't handle formaldefs and special arrays (the latter may need a }
  1024. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  1025. { you have to add 1 to all index operations if you directly inline it }
  1026. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  1027. (currpara.vardef.typ=formaldef)) or
  1028. is_special_array(currpara.vardef) then
  1029. exit;
  1030. end;
  1031. result:=true;
  1032. end;
  1033. procedure tcgprocinfo.parse_body;
  1034. var
  1035. oldprocinfo : tprocinfo;
  1036. oldblock_type : tblock_type;
  1037. st : TSymtable;
  1038. begin
  1039. oldprocinfo:=current_procinfo;
  1040. oldblock_type:=block_type;
  1041. { reset break and continue labels }
  1042. block_type:=bt_body;
  1043. current_procinfo:=self;
  1044. { calculate the lexical level }
  1045. if procdef.parast.symtablelevel>maxnesting then
  1046. Message(parser_e_too_much_lexlevel);
  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. current_procinfo:=oldprocinfo;
  1132. { Restore old state }
  1133. block_type:=oldblock_type;
  1134. end;
  1135. {****************************************************************************
  1136. PROCEDURE/FUNCTION PARSING
  1137. ****************************************************************************}
  1138. procedure check_init_paras(p:TObject;arg:pointer);
  1139. begin
  1140. if tsym(p).typ<>paravarsym then
  1141. exit;
  1142. with tparavarsym(p) do
  1143. if (not is_class(vardef) and
  1144. vardef.needs_inittable and
  1145. (varspez in [vs_value,vs_out])) then
  1146. include(current_procinfo.flags,pi_do_call);
  1147. end;
  1148. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1149. {
  1150. Parses the procedure directives, then parses the procedure body, then
  1151. generates the code for it
  1152. }
  1153. procedure do_generate_code(pi:tcgprocinfo);
  1154. var
  1155. hpi : tcgprocinfo;
  1156. begin
  1157. { generate code for this procedure }
  1158. pi.generate_code;
  1159. { process nested procs }
  1160. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1161. while assigned(hpi) do
  1162. begin
  1163. do_generate_code(hpi);
  1164. hpi:=tcgprocinfo(hpi.next);
  1165. end;
  1166. pi.resetprocdef;
  1167. end;
  1168. var
  1169. oldfailtokenmode : tmodeswitch;
  1170. isnestedproc : boolean;
  1171. begin
  1172. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1173. { create a new procedure }
  1174. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1175. current_module.procinfo:=current_procinfo;
  1176. current_procinfo.procdef:=pd;
  1177. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1178. { Insert mangledname }
  1179. pd.aliasnames.insert(pd.mangledname);
  1180. { Handle Export of this procedure }
  1181. if (po_exports in pd.procoptions) and
  1182. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1183. begin
  1184. pd.aliasnames.insert(pd.procsym.realname);
  1185. if cs_link_deffile in current_settings.globalswitches then
  1186. deffile.AddExport(pd.mangledname);
  1187. end;
  1188. { Insert result variables in the localst }
  1189. insert_funcret_local(pd);
  1190. { check if there are para's which require initing -> set }
  1191. { pi_do_call (if not yet set) }
  1192. if not(pi_do_call in current_procinfo.flags) then
  1193. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1194. { set _FAIL as keyword if constructor }
  1195. if (pd.proctypeoption=potype_constructor) then
  1196. begin
  1197. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1198. tokeninfo^[_FAIL].keyword:=m_all;
  1199. end;
  1200. tcgprocinfo(current_procinfo).parse_body;
  1201. { When it's a nested procedure then defer the code generation,
  1202. when back at normal function level then generate the code
  1203. for all defered nested procedures and the current procedure }
  1204. if isnestedproc then
  1205. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1206. else
  1207. begin
  1208. { We can't support inlining for procedures that have nested
  1209. procedures because the nested procedures use a fixed offset
  1210. for accessing locals in the parent procedure (PFV) }
  1211. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1212. begin
  1213. if (df_generic in current_procinfo.procdef.defoptions) then
  1214. Comment(V_Error,'Generic methods cannot have nested procedures')
  1215. else
  1216. if (po_inline in current_procinfo.procdef.procoptions) then
  1217. begin
  1218. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1219. Message(parser_w_inlining_disabled);
  1220. current_procinfo.procdef.proccalloption:=pocall_default;
  1221. end;
  1222. end;
  1223. if not(df_generic in current_procinfo.procdef.defoptions) then
  1224. do_generate_code(tcgprocinfo(current_procinfo));
  1225. end;
  1226. { reset _FAIL as _SELF normal }
  1227. if (pd.proctypeoption=potype_constructor) then
  1228. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1229. { release procinfo }
  1230. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1231. internalerror(200304274);
  1232. current_module.procinfo:=current_procinfo.parent;
  1233. { For specialization we didn't record the last semicolon. Moving this parsing
  1234. into the parse_body routine is not done because of having better file position
  1235. information available }
  1236. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1237. consume(_SEMICOLON);
  1238. if not isnestedproc then
  1239. { current_procinfo is checked for nil later on }
  1240. freeandnil(current_procinfo);
  1241. end;
  1242. procedure read_proc;
  1243. {
  1244. Parses the procedure directives, then parses the procedure body, then
  1245. generates the code for it
  1246. }
  1247. procedure do_generate_code(pi:tcgprocinfo);
  1248. var
  1249. hpi : tcgprocinfo;
  1250. begin
  1251. { generate code for this procedure }
  1252. pi.generate_code;
  1253. { process nested procs }
  1254. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1255. while assigned(hpi) do
  1256. begin
  1257. do_generate_code(hpi);
  1258. hpi:=tcgprocinfo(hpi.next);
  1259. end;
  1260. pi.resetprocdef;
  1261. end;
  1262. var
  1263. old_current_procinfo : tprocinfo;
  1264. pdflags : tpdflags;
  1265. pd,firstpd : tprocdef;
  1266. s : string;
  1267. begin
  1268. { save old state }
  1269. old_current_procinfo:=current_procinfo;
  1270. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1271. to an other procdef }
  1272. current_procinfo:=nil;
  1273. { parse procedure declaration }
  1274. if assigned(old_current_procinfo) and
  1275. assigned(old_current_procinfo.procdef) then
  1276. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1277. else
  1278. pd:=parse_proc_dec(nil);
  1279. { set the default function options }
  1280. if parse_only then
  1281. begin
  1282. pd.forwarddef:=true;
  1283. { set also the interface flag, for better error message when the
  1284. implementation doesn't much this header }
  1285. pd.interfacedef:=true;
  1286. include(pd.procoptions,po_global);
  1287. pdflags:=[pd_interface];
  1288. end
  1289. else
  1290. begin
  1291. pdflags:=[pd_body];
  1292. if (not current_module.in_interface) then
  1293. include(pdflags,pd_implemen);
  1294. if (not current_module.is_unit) or
  1295. maybe_smartlink_symbol or
  1296. {
  1297. taking addresses of static procedures goes wrong
  1298. if they aren't global when pic is used (FK)
  1299. }
  1300. (cs_create_pic in current_settings.moduleswitches) then
  1301. include(pd.procoptions,po_global);
  1302. pd.forwarddef:=false;
  1303. end;
  1304. { parse the directives that may follow }
  1305. parse_proc_directives(pd,pdflags);
  1306. { hint directives, these can be separated by semicolons here,
  1307. that needs to be handled here with a loop (PFV) }
  1308. while try_consume_hintdirective(pd.symoptions) do
  1309. Consume(_SEMICOLON);
  1310. { Set calling convention }
  1311. handle_calling_convention(pd);
  1312. { search for forward declarations }
  1313. if not proc_add_definition(pd) then
  1314. begin
  1315. { A method must be forward defined (in the object declaration) }
  1316. if assigned(pd._class) and
  1317. (not assigned(old_current_procinfo.procdef._class)) then
  1318. begin
  1319. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1320. tprocsym(pd.procsym).write_parameter_lists(pd);
  1321. end
  1322. else
  1323. begin
  1324. { Give a better error if there is a forward def in the interface and only
  1325. a single implementation }
  1326. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1327. if (not pd.forwarddef) and
  1328. (not pd.interfacedef) and
  1329. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1330. firstpd.forwarddef and
  1331. firstpd.interfacedef and
  1332. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1333. { don't give an error if it may be an overload }
  1334. not(m_fpc in current_settings.modeswitches) and
  1335. (not(po_overload in pd.procoptions) or
  1336. not(po_overload in firstpd.procoptions)) then
  1337. begin
  1338. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1339. tprocsym(pd.procsym).write_parameter_lists(pd);
  1340. end;
  1341. end;
  1342. end;
  1343. { Set mangled name }
  1344. proc_set_mangledname(pd);
  1345. { compile procedure when a body is needed }
  1346. if (pd_body in pdflags) then
  1347. begin
  1348. read_proc_body(old_current_procinfo,pd);
  1349. end
  1350. else
  1351. begin
  1352. { Handle imports }
  1353. if (po_external in pd.procoptions) then
  1354. begin
  1355. { External declared in implementation, and there was already a
  1356. forward (or interface) declaration then we need to generate
  1357. a stub that calls the external routine }
  1358. if (not pd.forwarddef) and
  1359. (pd.hasforward) and
  1360. not(
  1361. assigned(pd.import_dll) and
  1362. (target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1363. system_arm_wince,system_i386_wince])
  1364. ) then
  1365. begin
  1366. s:=proc_get_importname(pd);
  1367. if s<>'' then
  1368. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1369. end;
  1370. { Import DLL specified? }
  1371. if assigned(pd.import_dll) then
  1372. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1373. else
  1374. begin
  1375. { add import name to external list for DLL scanning }
  1376. if tf_has_dllscanner in target_info.flags then
  1377. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1378. end;
  1379. end;
  1380. end;
  1381. { make sure that references to forward-declared functions are not }
  1382. { treated as references to external symbols, needed for darwin. }
  1383. { make sure we don't change the binding of real external symbols }
  1384. if not(po_external in pd.procoptions) then
  1385. begin
  1386. if (po_global in pd.procoptions) or
  1387. (cs_profile in current_settings.moduleswitches) then
  1388. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1389. else
  1390. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1391. end;
  1392. current_procinfo:=old_current_procinfo;
  1393. end;
  1394. {****************************************************************************
  1395. DECLARATION PARSING
  1396. ****************************************************************************}
  1397. { search in symtablestack for not complete classes }
  1398. procedure check_forward_class(p:TObject;arg:pointer);
  1399. begin
  1400. if (tsym(p).typ=typesym) and
  1401. (ttypesym(p).typedef.typ=objectdef) and
  1402. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1403. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1404. end;
  1405. procedure read_declarations(islibrary : boolean);
  1406. begin
  1407. repeat
  1408. if not assigned(current_procinfo) then
  1409. internalerror(200304251);
  1410. case token of
  1411. _LABEL:
  1412. label_dec;
  1413. _CONST:
  1414. const_dec;
  1415. _TYPE:
  1416. type_dec;
  1417. _VAR:
  1418. var_dec;
  1419. _THREADVAR:
  1420. threadvar_dec;
  1421. _CONSTRUCTOR,
  1422. _DESTRUCTOR,
  1423. _FUNCTION,
  1424. _PROCEDURE,
  1425. _OPERATOR,
  1426. _CLASS:
  1427. read_proc;
  1428. _EXPORTS:
  1429. begin
  1430. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1431. begin
  1432. Message(parser_e_syntax_error);
  1433. consume_all_until(_SEMICOLON);
  1434. end
  1435. else if islibrary or
  1436. (target_info.system in system_unit_program_exports) then
  1437. read_exports
  1438. else
  1439. begin
  1440. Message(parser_w_unsupported_feature);
  1441. consume(_BEGIN);
  1442. end;
  1443. end
  1444. else
  1445. begin
  1446. case idtoken of
  1447. _RESOURCESTRING :
  1448. begin
  1449. { m_class is needed, because the resourcestring
  1450. loading is in the ObjPas unit }
  1451. { if (m_class in current_settings.modeswitches) then}
  1452. resourcestring_dec
  1453. { else
  1454. break;}
  1455. end;
  1456. _PROPERTY:
  1457. begin
  1458. if (m_fpc in current_settings.modeswitches) then
  1459. property_dec
  1460. else
  1461. break;
  1462. end;
  1463. else
  1464. break;
  1465. end;
  1466. end;
  1467. end;
  1468. until false;
  1469. { check for incomplete class definitions, this is only required
  1470. for fpc modes }
  1471. if (m_fpc in current_settings.modeswitches) then
  1472. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1473. end;
  1474. procedure read_interface_declarations;
  1475. begin
  1476. repeat
  1477. case token of
  1478. _CONST :
  1479. const_dec;
  1480. _TYPE :
  1481. type_dec;
  1482. _VAR :
  1483. var_dec;
  1484. _THREADVAR :
  1485. threadvar_dec;
  1486. _FUNCTION,
  1487. _PROCEDURE,
  1488. _OPERATOR :
  1489. read_proc;
  1490. else
  1491. begin
  1492. case idtoken of
  1493. _RESOURCESTRING :
  1494. resourcestring_dec;
  1495. _PROPERTY:
  1496. begin
  1497. if (m_fpc in current_settings.modeswitches) then
  1498. property_dec
  1499. else
  1500. break;
  1501. end;
  1502. else
  1503. break;
  1504. end;
  1505. end;
  1506. end;
  1507. until false;
  1508. { check for incomplete class definitions, this is only required
  1509. for fpc modes }
  1510. if (m_fpc in current_settings.modeswitches) then
  1511. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1512. end;
  1513. {****************************************************************************
  1514. SPECIALIZATION BODY GENERATION
  1515. ****************************************************************************}
  1516. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1517. function find_module_from_symtable(st:tsymtable):tmodule;
  1518. var
  1519. hp : tmodule;
  1520. begin
  1521. result:=nil;
  1522. hp:=tmodule(loaded_units.first);
  1523. while assigned(hp) do
  1524. begin
  1525. if (hp.globalsymtable=st) or
  1526. (hp.localsymtable=st) then
  1527. begin
  1528. result:=hp;
  1529. exit;
  1530. end;
  1531. hp:=tmodule(hp.next);
  1532. end;
  1533. end;
  1534. var
  1535. i : longint;
  1536. hp : tdef;
  1537. oldcurrent_filepos : tfileposinfo;
  1538. oldsymtablestack : tsymtablestack;
  1539. pu : tused_unit;
  1540. hmodule : tmodule;
  1541. begin
  1542. if not((tsym(p).typ=typesym) and
  1543. (ttypesym(p).typedef.typ=objectdef) and
  1544. (df_specialization in ttypesym(p).typedef.defoptions)
  1545. ) then
  1546. exit;
  1547. { Setup symtablestack a definition time }
  1548. oldsymtablestack:=symtablestack;
  1549. symtablestack:=tsymtablestack.create;
  1550. if not assigned(tobjectdef(ttypesym(p).typedef).genericdef) then
  1551. internalerror(200705151);
  1552. hmodule:=find_module_from_symtable(tobjectdef(ttypesym(p).typedef).genericdef.owner);
  1553. if hmodule=nil then
  1554. internalerror(200705152);
  1555. pu:=tused_unit(hmodule.used_units.first);
  1556. while assigned(pu) do
  1557. begin
  1558. if not assigned(pu.u.globalsymtable) then
  1559. internalerror(200705153);
  1560. symtablestack.push(pu.u.globalsymtable);
  1561. pu:=tused_unit(pu.next);
  1562. end;
  1563. if assigned(hmodule.globalsymtable) then
  1564. symtablestack.push(hmodule.globalsymtable);
  1565. if assigned(hmodule.localsymtable) then
  1566. symtablestack.push(hmodule.localsymtable);
  1567. { definitions }
  1568. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1569. begin
  1570. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1571. if hp.typ=procdef then
  1572. begin
  1573. if assigned(tprocdef(hp).genericdef) and
  1574. (tprocdef(hp).genericdef.typ=procdef) and
  1575. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1576. begin
  1577. oldcurrent_filepos:=current_filepos;
  1578. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1579. current_tokenpos:=current_filepos;
  1580. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1581. read_proc_body(nil,tprocdef(hp));
  1582. current_filepos:=oldcurrent_filepos;
  1583. end
  1584. else
  1585. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1586. end;
  1587. end;
  1588. { Restore symtablestack }
  1589. symtablestack.free;
  1590. symtablestack:=oldsymtablestack;
  1591. end;
  1592. procedure generate_specialization_procs;
  1593. begin
  1594. if assigned(current_module.globalsymtable) then
  1595. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1596. if assigned(current_module.localsymtable) then
  1597. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1598. end;
  1599. end.