psub.pas 65 KB

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