psub.pas 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  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. {$if defined(POWERPC) or defined(POWERPC64)}
  914. fixup_jmps(aktproccode);
  915. {$endif}
  916. { insert line debuginfo }
  917. if (cs_debuginfo in current_settings.moduleswitches) or
  918. (cs_use_lineinfo in current_settings.globalswitches) then
  919. debuginfo.insertlineinfo(aktproccode);
  920. { add the procedure to the al_procedures }
  921. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  922. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  923. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  924. { save local data (casetable) also in the same file }
  925. if assigned(aktlocaldata) and
  926. (not aktlocaldata.empty) then
  927. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  928. { only now we can remove the temps }
  929. tg.resettempgen;
  930. { stop tempgen and ra }
  931. tg.free;
  932. cg.done_register_allocators;
  933. tg:=nil;
  934. end;
  935. { restore symtablestack }
  936. remove_from_symtablestack;
  937. { restore }
  938. templist.free;
  939. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  940. current_filepos:=oldfilepos;
  941. current_procinfo:=oldprocinfo;
  942. end;
  943. procedure tcgprocinfo.add_to_symtablestack;
  944. var
  945. _class,hp : tobjectdef;
  946. begin
  947. { insert symtables for the class, but only if it is no nested function }
  948. if assigned(procdef._class) and
  949. not(assigned(parent) and
  950. assigned(parent.procdef) and
  951. assigned(parent.procdef._class)) then
  952. begin
  953. { insert them in the reverse order }
  954. hp:=nil;
  955. repeat
  956. _class:=procdef._class;
  957. while _class.childof<>hp do
  958. _class:=_class.childof;
  959. hp:=_class;
  960. symtablestack.push(_class.symtable);
  961. until hp=procdef._class;
  962. end;
  963. { insert parasymtable in symtablestack when parsing
  964. a function }
  965. if procdef.parast.symtablelevel>=normal_function_level then
  966. symtablestack.push(procdef.parast);
  967. { insert localsymtable }
  968. symtablestack.push(procdef.localst);
  969. end;
  970. procedure tcgprocinfo.remove_from_symtablestack;
  971. var
  972. _class : tobjectdef;
  973. begin
  974. { remove localsymtable }
  975. symtablestack.pop(procdef.localst);
  976. { remove parasymtable }
  977. if procdef.parast.symtablelevel>=normal_function_level then
  978. symtablestack.pop(procdef.parast);
  979. { remove symtables for the class, but only if it is no nested function }
  980. if assigned(procdef._class) and
  981. not(assigned(parent) and
  982. assigned(parent.procdef) and
  983. assigned(parent.procdef._class)) then
  984. begin
  985. _class:=procdef._class;
  986. while assigned(_class) do
  987. begin
  988. symtablestack.pop(_class.symtable);
  989. _class:=_class.childof;
  990. end;
  991. end;
  992. end;
  993. procedure tcgprocinfo.resetprocdef;
  994. begin
  995. { remove code tree, if not inline procedure }
  996. if assigned(code) then
  997. begin
  998. { the inline procedure has already got a copy of the tree
  999. stored in procdef.inlininginfo }
  1000. code.free;
  1001. code:=nil;
  1002. end;
  1003. end;
  1004. function checknodeinlining(procdef: tprocdef): boolean;
  1005. var
  1006. i : integer;
  1007. currpara : tparavarsym;
  1008. begin
  1009. result := false;
  1010. if (pi_has_assembler_block in current_procinfo.flags) then
  1011. exit;
  1012. for i:=0 to procdef.paras.count-1 do
  1013. begin
  1014. currpara:=tparavarsym(procdef.paras[i]);
  1015. { we can't handle formaldefs and special arrays (the latter may need a }
  1016. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  1017. { you have to add 1 to all index operations if you directly inline it }
  1018. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  1019. (currpara.vardef.typ=formaldef)) or
  1020. is_special_array(currpara.vardef) then
  1021. exit;
  1022. end;
  1023. result:=true;
  1024. end;
  1025. procedure tcgprocinfo.parse_body;
  1026. var
  1027. oldprocinfo : tprocinfo;
  1028. oldblock_type : tblock_type;
  1029. st : TSymtable;
  1030. begin
  1031. oldprocinfo:=current_procinfo;
  1032. oldblock_type:=block_type;
  1033. { reset break and continue labels }
  1034. block_type:=bt_body;
  1035. current_procinfo:=self;
  1036. { calculate the lexical level }
  1037. if procdef.parast.symtablelevel>maxnesting then
  1038. Message(parser_e_too_much_lexlevel);
  1039. {$ifdef state_tracking}
  1040. { aktstate:=Tstate_storage.create;}
  1041. {$endif state_tracking}
  1042. { allocate the symbol for this procedure }
  1043. alloc_proc_symbol(procdef);
  1044. { add parast/localst to symtablestack }
  1045. add_to_symtablestack;
  1046. { save entry info }
  1047. entrypos:=current_filepos;
  1048. entryswitches:=current_settings.localswitches;
  1049. if (df_generic in procdef.defoptions) then
  1050. begin
  1051. { start token recorder for generic template }
  1052. procdef.initgeneric;
  1053. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1054. end;
  1055. { parse the code ... }
  1056. code:=block(current_module.islibrary);
  1057. if (df_generic in procdef.defoptions) then
  1058. begin
  1059. { stop token recorder for generic template }
  1060. current_scanner.stoprecordtokens;
  1061. { Give a warning for accesses in the static symtable that aren't visible
  1062. outside the current unit }
  1063. st:=procdef.owner;
  1064. while (st.symtabletype=ObjectSymtable) do
  1065. st:=st.defowner.owner;
  1066. if (pi_uses_static_symtable in flags) and
  1067. (st.symtabletype<>staticsymtable) then
  1068. Comment(V_Warning,'Global Generic template references static symtable');
  1069. end;
  1070. { save exit info }
  1071. exitswitches:=current_settings.localswitches;
  1072. exitpos:=last_endtoken_filepos;
  1073. { the procedure is now defined }
  1074. procdef.forwarddef:=false;
  1075. if assigned(code) then
  1076. begin
  1077. { get a better entry point }
  1078. entrypos:=code.fileinfo;
  1079. { Finish type checking pass }
  1080. do_typecheckpass(code);
  1081. end;
  1082. { Check for unused labels, forwards, symbols for procedures. Static
  1083. symtable is checked in pmodules.
  1084. The check must be done after the typecheckpass }
  1085. if (Errorcount=0) and
  1086. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1087. begin
  1088. { check if forwards are resolved }
  1089. tstoredsymtable(procdef.localst).check_forwards;
  1090. { check if all labels are used }
  1091. tstoredsymtable(procdef.localst).checklabels;
  1092. { remove cross unit overloads }
  1093. tstoredsymtable(procdef.localst).unchain_overloaded;
  1094. { check for unused symbols, but only if there is no asm block }
  1095. if not(pi_has_assembler_block in flags) then
  1096. begin
  1097. tstoredsymtable(procdef.localst).allsymbolsused;
  1098. tstoredsymtable(procdef.parast).allsymbolsused;
  1099. end;
  1100. end;
  1101. if (po_inline in procdef.procoptions) then
  1102. begin
  1103. { Can we inline this procedure? }
  1104. if checknodeinlining(procdef) then
  1105. begin
  1106. new(procdef.inlininginfo);
  1107. include(procdef.procoptions,po_has_inlininginfo);
  1108. procdef.inlininginfo^.code:=code.getcopy;
  1109. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1110. { The blocknode needs to set an exit label }
  1111. if procdef.inlininginfo^.code.nodetype=blockn then
  1112. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1113. end;
  1114. end;
  1115. { Print the node to tree.log }
  1116. if paraprintnodetree=1 then
  1117. printproc;
  1118. { ... remove symbol tables }
  1119. remove_from_symtablestack;
  1120. {$ifdef state_tracking}
  1121. { aktstate.destroy;}
  1122. {$endif state_tracking}
  1123. current_procinfo:=oldprocinfo;
  1124. { Restore old state }
  1125. block_type:=oldblock_type;
  1126. end;
  1127. {****************************************************************************
  1128. PROCEDURE/FUNCTION PARSING
  1129. ****************************************************************************}
  1130. procedure check_init_paras(p:TObject;arg:pointer);
  1131. begin
  1132. if tsym(p).typ<>paravarsym then
  1133. exit;
  1134. with tparavarsym(p) do
  1135. if (not is_class(vardef) and
  1136. vardef.needs_inittable and
  1137. (varspez in [vs_value,vs_out])) then
  1138. include(current_procinfo.flags,pi_do_call);
  1139. end;
  1140. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1141. {
  1142. Parses the procedure directives, then parses the procedure body, then
  1143. generates the code for it
  1144. }
  1145. procedure do_generate_code(pi:tcgprocinfo);
  1146. var
  1147. hpi : tcgprocinfo;
  1148. begin
  1149. { generate code for this procedure }
  1150. pi.generate_code;
  1151. { process nested procs }
  1152. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1153. while assigned(hpi) do
  1154. begin
  1155. do_generate_code(hpi);
  1156. hpi:=tcgprocinfo(hpi.next);
  1157. end;
  1158. pi.resetprocdef;
  1159. end;
  1160. var
  1161. oldfailtokenmode : tmodeswitch;
  1162. isnestedproc : boolean;
  1163. begin
  1164. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1165. { create a new procedure }
  1166. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1167. current_module.procinfo:=current_procinfo;
  1168. current_procinfo.procdef:=pd;
  1169. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1170. { Insert mangledname }
  1171. pd.aliasnames.insert(pd.mangledname);
  1172. { Handle Export of this procedure }
  1173. if (po_exports in pd.procoptions) and
  1174. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1175. begin
  1176. pd.aliasnames.insert(pd.procsym.realname);
  1177. if cs_link_deffile in current_settings.globalswitches then
  1178. deffile.AddExport(pd.mangledname);
  1179. end;
  1180. { Insert result variables in the localst }
  1181. insert_funcret_local(pd);
  1182. { check if there are para's which require initing -> set }
  1183. { pi_do_call (if not yet set) }
  1184. if not(pi_do_call in current_procinfo.flags) then
  1185. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1186. { set _FAIL as keyword if constructor }
  1187. if (pd.proctypeoption=potype_constructor) then
  1188. begin
  1189. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1190. tokeninfo^[_FAIL].keyword:=m_all;
  1191. end;
  1192. tcgprocinfo(current_procinfo).parse_body;
  1193. { When it's a nested procedure then defer the code generation,
  1194. when back at normal function level then generate the code
  1195. for all defered nested procedures and the current procedure }
  1196. if isnestedproc then
  1197. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1198. else
  1199. begin
  1200. { We can't support inlining for procedures that have nested
  1201. procedures because the nested procedures use a fixed offset
  1202. for accessing locals in the parent procedure (PFV) }
  1203. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1204. begin
  1205. if (df_generic in current_procinfo.procdef.defoptions) then
  1206. {$warning TODO Add error message for nested procs in generics}
  1207. internalerror(200511151)
  1208. else if (po_inline in current_procinfo.procdef.procoptions) then
  1209. begin
  1210. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1211. Message(parser_w_inlining_disabled);
  1212. current_procinfo.procdef.proccalloption:=pocall_default;
  1213. end;
  1214. end;
  1215. if not(df_generic in current_procinfo.procdef.defoptions) then
  1216. do_generate_code(tcgprocinfo(current_procinfo));
  1217. end;
  1218. { reset _FAIL as _SELF normal }
  1219. if (pd.proctypeoption=potype_constructor) then
  1220. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1221. { release procinfo }
  1222. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1223. internalerror(200304274);
  1224. current_module.procinfo:=current_procinfo.parent;
  1225. { For specialization we didn't record the last semicolon. Moving this parsing
  1226. into the parse_body routine is not done because of having better file position
  1227. information available }
  1228. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1229. consume(_SEMICOLON);
  1230. if not isnestedproc then
  1231. { current_procinfo is checked for nil later on }
  1232. freeandnil(current_procinfo);
  1233. end;
  1234. procedure read_proc;
  1235. {
  1236. Parses the procedure directives, then parses the procedure body, then
  1237. generates the code for it
  1238. }
  1239. procedure do_generate_code(pi:tcgprocinfo);
  1240. var
  1241. hpi : tcgprocinfo;
  1242. begin
  1243. { generate code for this procedure }
  1244. pi.generate_code;
  1245. { process nested procs }
  1246. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1247. while assigned(hpi) do
  1248. begin
  1249. do_generate_code(hpi);
  1250. hpi:=tcgprocinfo(hpi.next);
  1251. end;
  1252. pi.resetprocdef;
  1253. end;
  1254. var
  1255. old_current_procinfo : tprocinfo;
  1256. pdflags : tpdflags;
  1257. pd,firstpd : tprocdef;
  1258. s : string;
  1259. begin
  1260. { save old state }
  1261. old_current_procinfo:=current_procinfo;
  1262. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1263. to an other procdef }
  1264. current_procinfo:=nil;
  1265. { parse procedure declaration }
  1266. if assigned(old_current_procinfo) and
  1267. assigned(old_current_procinfo.procdef) then
  1268. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1269. else
  1270. pd:=parse_proc_dec(nil);
  1271. { set the default function options }
  1272. if parse_only then
  1273. begin
  1274. pd.forwarddef:=true;
  1275. { set also the interface flag, for better error message when the
  1276. implementation doesn't much this header }
  1277. pd.interfacedef:=true;
  1278. include(pd.procoptions,po_global);
  1279. pdflags:=[pd_interface];
  1280. end
  1281. else
  1282. begin
  1283. pdflags:=[pd_body];
  1284. if (not current_module.in_interface) then
  1285. include(pdflags,pd_implemen);
  1286. if (not current_module.is_unit) or
  1287. maybe_smartlink_symbol or
  1288. {
  1289. taking addresses of static procedures goes wrong
  1290. if they aren't global when pic is used (FK)
  1291. }
  1292. (cs_create_pic in current_settings.moduleswitches) then
  1293. include(pd.procoptions,po_global);
  1294. pd.forwarddef:=false;
  1295. end;
  1296. { parse the directives that may follow }
  1297. parse_proc_directives(pd,pdflags);
  1298. { hint directives, these can be separated by semicolons here,
  1299. that needs to be handled here with a loop (PFV) }
  1300. while try_consume_hintdirective(pd.symoptions) do
  1301. Consume(_SEMICOLON);
  1302. { Set calling convention }
  1303. handle_calling_convention(pd);
  1304. { search for forward declarations }
  1305. if not proc_add_definition(pd) then
  1306. begin
  1307. { A method must be forward defined (in the object declaration) }
  1308. if assigned(pd._class) and
  1309. (not assigned(old_current_procinfo.procdef._class)) then
  1310. begin
  1311. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1312. tprocsym(pd.procsym).write_parameter_lists(pd);
  1313. end
  1314. else
  1315. begin
  1316. { Give a better error if there is a forward def in the interface and only
  1317. a single implementation }
  1318. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1319. if (not pd.forwarddef) and
  1320. (not pd.interfacedef) and
  1321. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1322. firstpd.forwarddef and
  1323. firstpd.interfacedef and
  1324. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1325. { don't give an error if it may be an overload }
  1326. not(m_fpc in current_settings.modeswitches) and
  1327. (not(po_overload in pd.procoptions) or
  1328. not(po_overload in firstpd.procoptions)) then
  1329. begin
  1330. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1331. tprocsym(pd.procsym).write_parameter_lists(pd);
  1332. end;
  1333. end;
  1334. end;
  1335. { Set mangled name }
  1336. proc_set_mangledname(pd);
  1337. { compile procedure when a body is needed }
  1338. if (pd_body in pdflags) then
  1339. begin
  1340. read_proc_body(old_current_procinfo,pd);
  1341. end
  1342. else
  1343. begin
  1344. { Handle imports }
  1345. if (po_external in pd.procoptions) then
  1346. begin
  1347. { External declared in implementation, and there was already a
  1348. forward (or interface) declaration then we need to generate
  1349. a stub that calls the external routine }
  1350. if (not pd.forwarddef) and
  1351. (pd.hasforward) and
  1352. not(
  1353. assigned(pd.import_dll) and
  1354. (target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1355. system_arm_wince,system_i386_wince])
  1356. ) then
  1357. begin
  1358. s:=proc_get_importname(pd);
  1359. if s<>'' then
  1360. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1361. end;
  1362. { Import DLL specified? }
  1363. if assigned(pd.import_dll) then
  1364. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1365. else
  1366. begin
  1367. { add import name to external list for DLL scanning }
  1368. if tf_has_dllscanner in target_info.flags then
  1369. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1370. end;
  1371. end;
  1372. end;
  1373. { make sure that references to forward-declared functions are not }
  1374. { treated as references to external symbols, needed for darwin. }
  1375. { make sure we don't change the binding of real external symbols }
  1376. if not(po_external in pd.procoptions) then
  1377. begin
  1378. if (po_global in pd.procoptions) or
  1379. (cs_profile in current_settings.moduleswitches) then
  1380. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1381. else
  1382. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1383. end;
  1384. current_procinfo:=old_current_procinfo;
  1385. end;
  1386. {****************************************************************************
  1387. DECLARATION PARSING
  1388. ****************************************************************************}
  1389. { search in symtablestack for not complete classes }
  1390. procedure check_forward_class(p:TObject;arg:pointer);
  1391. begin
  1392. if (tsym(p).typ=typesym) and
  1393. (ttypesym(p).typedef.typ=objectdef) and
  1394. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1395. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1396. end;
  1397. procedure read_declarations(islibrary : boolean);
  1398. begin
  1399. repeat
  1400. if not assigned(current_procinfo) then
  1401. internalerror(200304251);
  1402. case token of
  1403. _LABEL:
  1404. label_dec;
  1405. _CONST:
  1406. const_dec;
  1407. _TYPE:
  1408. type_dec;
  1409. _VAR:
  1410. var_dec;
  1411. _THREADVAR:
  1412. threadvar_dec;
  1413. _CONSTRUCTOR,
  1414. _DESTRUCTOR,
  1415. _FUNCTION,
  1416. _PROCEDURE,
  1417. _OPERATOR,
  1418. _CLASS:
  1419. read_proc;
  1420. _EXPORTS:
  1421. begin
  1422. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1423. begin
  1424. Message(parser_e_syntax_error);
  1425. consume_all_until(_SEMICOLON);
  1426. end
  1427. else if islibrary or
  1428. (target_info.system in system_unit_program_exports) then
  1429. read_exports
  1430. else
  1431. begin
  1432. Message(parser_w_unsupported_feature);
  1433. consume(_BEGIN);
  1434. end;
  1435. end
  1436. else
  1437. begin
  1438. case idtoken of
  1439. _RESOURCESTRING :
  1440. begin
  1441. { m_class is needed, because the resourcestring
  1442. loading is in the ObjPas unit }
  1443. { if (m_class in current_settings.modeswitches) then}
  1444. resourcestring_dec
  1445. { else
  1446. break;}
  1447. end;
  1448. _PROPERTY:
  1449. begin
  1450. if (m_fpc in current_settings.modeswitches) then
  1451. property_dec
  1452. else
  1453. break;
  1454. end;
  1455. else
  1456. break;
  1457. end;
  1458. end;
  1459. end;
  1460. until false;
  1461. { check for incomplete class definitions, this is only required
  1462. for fpc modes }
  1463. if (m_fpc in current_settings.modeswitches) then
  1464. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1465. end;
  1466. procedure read_interface_declarations;
  1467. begin
  1468. repeat
  1469. case token of
  1470. _CONST :
  1471. const_dec;
  1472. _TYPE :
  1473. type_dec;
  1474. _VAR :
  1475. var_dec;
  1476. _THREADVAR :
  1477. threadvar_dec;
  1478. _FUNCTION,
  1479. _PROCEDURE,
  1480. _OPERATOR :
  1481. read_proc;
  1482. else
  1483. begin
  1484. case idtoken of
  1485. _RESOURCESTRING :
  1486. resourcestring_dec;
  1487. _PROPERTY:
  1488. begin
  1489. if (m_fpc in current_settings.modeswitches) then
  1490. property_dec
  1491. else
  1492. break;
  1493. end;
  1494. else
  1495. break;
  1496. end;
  1497. end;
  1498. end;
  1499. until false;
  1500. { check for incomplete class definitions, this is only required
  1501. for fpc modes }
  1502. if (m_fpc in current_settings.modeswitches) then
  1503. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1504. end;
  1505. {****************************************************************************
  1506. SPECIALIZATION BODY GENERATION
  1507. ****************************************************************************}
  1508. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1509. var
  1510. i : longint;
  1511. hp : tdef;
  1512. oldcurrent_filepos : tfileposinfo;
  1513. begin
  1514. if not((tsym(p).typ=typesym) and
  1515. (ttypesym(p).typedef.typ=objectdef) and
  1516. (df_specialization in ttypesym(p).typedef.defoptions)
  1517. ) then
  1518. exit;
  1519. { definitions }
  1520. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1521. begin
  1522. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1523. if hp.typ=procdef then
  1524. begin
  1525. if assigned(tprocdef(hp).genericdef) and
  1526. (tprocdef(hp).genericdef.typ=procdef) and
  1527. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1528. begin
  1529. oldcurrent_filepos:=current_filepos;
  1530. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1531. current_tokenpos:=current_filepos;
  1532. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1533. read_proc_body(nil,tprocdef(hp));
  1534. current_filepos:=oldcurrent_filepos;
  1535. end
  1536. else
  1537. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1538. end;
  1539. end;
  1540. end;
  1541. procedure generate_specialization_procs;
  1542. begin
  1543. if assigned(current_module.globalsymtable) then
  1544. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1545. if assigned(current_module.localsymtable) then
  1546. begin
  1547. symtablestack.push(current_module.localsymtable);
  1548. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1549. symtablestack.pop(current_module.localsymtable);
  1550. end;
  1551. end;
  1552. end.