psub.pas 65 KB

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