psub.pas 66 KB

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