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