psub.pas 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  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. {$ifdef x86}
  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])=[]) then
  684. begin
  685. { we need the parameter info here to determine if the procedure gets
  686. parameters on the stack
  687. calling generate_parameter_info doesn't hurt but it costs time
  688. }
  689. generate_parameter_info;
  690. if not(stack_tainting_parameter) and
  691. not(has_assembler_child) then
  692. begin
  693. { Only need to set the framepointer }
  694. framepointer:=NR_STACK_POINTER_REG;
  695. tg.direction:=1;
  696. end;
  697. end;
  698. {$endif x86}
  699. { Create register allocator }
  700. cg.init_register_allocators;
  701. set_first_temp_offset;
  702. generate_parameter_info;
  703. { Allocate space in temp/registers for parast and localst }
  704. current_filepos:=entrypos;
  705. gen_alloc_symtable(aktproccode,procdef.parast);
  706. gen_alloc_symtable(aktproccode,procdef.localst);
  707. { Store temp offset for information about 'real' temps }
  708. tempstart:=tg.lasttemp;
  709. { Generate code to load register parameters in temps and insert local
  710. copies for values parameters. This must be done before the code for the
  711. body is generated because the localloc is updated.
  712. Note: The generated code will be inserted after the code generation of
  713. the body is finished, because only then the position is known }
  714. {$ifdef oldregvars}
  715. assign_regvars(code);
  716. {$endif oldreg}
  717. current_filepos:=entrypos;
  718. { record which registers are allocated here, since all code }
  719. { allocating registers comes after it }
  720. cg.set_regalloc_extend_backwards(true);
  721. gen_load_para_value(templist);
  722. cg.set_regalloc_extend_backwards(false);
  723. { caller paraloc info is also necessary in the stackframe_entry
  724. code of the ppc (and possibly other processors) }
  725. if not procdef.has_paraloc_info then
  726. begin
  727. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  728. procdef.has_paraloc_info:=true;
  729. end;
  730. { generate code for the node tree }
  731. do_secondpass(code);
  732. aktproccode.concatlist(current_asmdata.CurrAsmList);
  733. {$ifdef i386}
  734. procdef.fpu_used:=code.registersfpu;
  735. {$endif i386}
  736. { The position of the loadpara_asmnode is now known }
  737. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  738. { first generate entry and initialize code with the correct
  739. position and switches }
  740. current_filepos:=entrypos;
  741. current_settings.localswitches:=entryswitches;
  742. cg.set_regalloc_extend_backwards(true);
  743. gen_entry_code(templist);
  744. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  745. gen_initialize_code(templist);
  746. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  747. { now generate finalize and exit code with the correct position
  748. and switches }
  749. current_filepos:=exitpos;
  750. current_settings.localswitches:=exitswitches;
  751. cg.set_regalloc_extend_backwards(false);
  752. gen_finalize_code(templist);
  753. { the finalcode must be concated if there was no position available,
  754. using insertlistafter will result in an insert at the start
  755. when currentai=nil }
  756. if assigned(final_asmnode.currenttai) then
  757. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  758. else
  759. aktproccode.concatlist(templist);
  760. { insert exit label at the correct position }
  761. cg.a_label(templist,CurrExitLabel);
  762. if assigned(exitlabel_asmnode.currenttai) then
  763. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  764. else
  765. aktproccode.concatlist(templist);
  766. { exit code }
  767. gen_exit_code(templist);
  768. aktproccode.concatlist(templist);
  769. {$ifdef OLDREGVARS}
  770. { note: this must be done only after as much code as possible has }
  771. { been generated. The result is that when you ungetregister() a }
  772. { regvar, it will actually free the regvar (and alse free the }
  773. { the regvars at the same time). Doing this too early will }
  774. { confuse the register allocator, as the regvars will still be }
  775. { used. It should be done before loading the result regs (so }
  776. { they don't conflict with the regvars) and before }
  777. { gen_entry_code (that one has to be able to allocate the }
  778. { regvars again) (JM) }
  779. free_regvars(aktproccode);
  780. {$endif OLDREGVARS}
  781. { generate symbol and save end of header position }
  782. current_filepos:=entrypos;
  783. gen_proc_symbol(templist);
  784. headertai:=tai(templist.last);
  785. { insert symbol }
  786. aktproccode.insertlist(templist);
  787. { Free space in temp/registers for parast and localst, must be
  788. done after gen_entry_code }
  789. current_filepos:=exitpos;
  790. gen_free_symtable(aktproccode,procdef.localst);
  791. gen_free_symtable(aktproccode,procdef.parast);
  792. { add code that will load the return value, this is not done
  793. for assembler routines when they didn't reference the result
  794. variable }
  795. gen_load_return_value(templist);
  796. aktproccode.concatlist(templist);
  797. { Already reserve all registers for stack checking code and
  798. generate the call to the helper function }
  799. if (cs_check_stack in entryswitches) and
  800. not(po_assembler in procdef.procoptions) and
  801. (procdef.proctypeoption<>potype_proginit) then
  802. begin
  803. current_filepos:=entrypos;
  804. gen_stack_check_call(templist);
  805. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  806. end;
  807. { load got if necessary }
  808. cg.set_regalloc_extend_backwards(true);
  809. current_filepos:=entrypos;
  810. gen_got_load(templist);
  811. aktproccode.insertlistafter(headertai,templist);
  812. cg.set_regalloc_extend_backwards(false);
  813. { The procedure body is finished, we can now
  814. allocate the registers }
  815. cg.do_register_allocation(aktproccode,headertai);
  816. { translate imag. register to their real counter parts
  817. this is necessary for debuginfo and verbose assembler output
  818. when SSA will be implented, this will be more complicated because we've to
  819. maintain location lists }
  820. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  821. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  822. { Add save and restore of used registers }
  823. current_filepos:=entrypos;
  824. gen_save_used_regs(templist);
  825. aktproccode.insertlistafter(headertai,templist);
  826. current_filepos:=exitpos;
  827. gen_restore_used_regs(aktproccode);
  828. { We know the size of the stack, now we can generate the
  829. parameter that is passed to the stack checking code }
  830. if (cs_check_stack in entryswitches) and
  831. not(po_assembler in procdef.procoptions) and
  832. (procdef.proctypeoption<>potype_proginit) then
  833. begin
  834. current_filepos:=entrypos;
  835. gen_stack_check_size_para(templist);
  836. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  837. end;
  838. { Add entry code (stack allocation) after header }
  839. current_filepos:=entrypos;
  840. gen_proc_entry_code(templist);
  841. aktproccode.insertlistafter(headertai,templist);
  842. { Add exit code at the end }
  843. current_filepos:=exitpos;
  844. gen_proc_exit_code(templist);
  845. aktproccode.concatlist(templist);
  846. { check if the implicit finally has been generated. The flag
  847. should already be set in pass1 }
  848. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  849. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  850. (pi_needs_implicit_finally in flags) and
  851. not(pi_has_implicit_finally in flags) then
  852. internalerror(200405231);
  853. {$ifndef NoOpt}
  854. if not(cs_no_regalloc in current_settings.globalswitches) then
  855. begin
  856. if (cs_opt_level1 in current_settings.optimizerswitches) and
  857. { do not optimize pure assembler procedures }
  858. not(pi_is_assembler in flags) then
  859. optimize(aktproccode);
  860. end;
  861. {$endif NoOpt}
  862. {$ifdef ARM}
  863. { because of the limited constant size of the arm, all data access is done pc relative }
  864. insertpcrelativedata(aktproccode,aktlocaldata);
  865. {$endif ARM}
  866. { Add end symbol and debug info }
  867. { this must be done after the pcrelativedata is appended else the distance calculation of
  868. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  869. so it should be inserted before the end symbol (FK)
  870. }
  871. current_filepos:=exitpos;
  872. gen_proc_symbol_end(templist);
  873. aktproccode.concatlist(templist);
  874. {$ifdef POWERPC}
  875. fixup_jmps(aktproccode);
  876. {$endif POWERPC}
  877. {$ifdef POWERPC64}
  878. fixup_jmps(aktproccode);
  879. {$endif POWERPC64}
  880. { insert line debuginfo }
  881. if (cs_debuginfo in current_settings.moduleswitches) or
  882. (cs_use_lineinfo in current_settings.globalswitches) then
  883. debuginfo.insertlineinfo(aktproccode);
  884. { add the procedure to the al_procedures }
  885. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  886. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  887. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  888. { save local data (casetable) also in the same file }
  889. if assigned(aktlocaldata) and
  890. (not aktlocaldata.empty) then
  891. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  892. { only now we can remove the temps }
  893. tg.resettempgen;
  894. { stop tempgen and ra }
  895. tg.free;
  896. cg.done_register_allocators;
  897. tg:=nil;
  898. end;
  899. { restore symtablestack }
  900. remove_from_symtablestack;
  901. { restore }
  902. templist.free;
  903. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  904. current_filepos:=oldfilepos;
  905. current_procinfo:=oldprocinfo;
  906. end;
  907. procedure tcgprocinfo.add_to_symtablestack;
  908. var
  909. _class,hp : tobjectdef;
  910. begin
  911. { insert symtables for the class, but only if it is no nested function }
  912. if assigned(procdef._class) and
  913. not(assigned(parent) and
  914. assigned(parent.procdef) and
  915. assigned(parent.procdef._class)) then
  916. begin
  917. { insert them in the reverse order }
  918. hp:=nil;
  919. repeat
  920. _class:=procdef._class;
  921. while _class.childof<>hp do
  922. _class:=_class.childof;
  923. hp:=_class;
  924. symtablestack.push(_class.symtable);
  925. until hp=procdef._class;
  926. end;
  927. { insert parasymtable in symtablestack when parsing
  928. a function }
  929. if procdef.parast.symtablelevel>=normal_function_level then
  930. symtablestack.push(procdef.parast);
  931. { insert localsymtable }
  932. symtablestack.push(procdef.localst);
  933. end;
  934. procedure tcgprocinfo.remove_from_symtablestack;
  935. var
  936. _class : tobjectdef;
  937. begin
  938. { remove localsymtable }
  939. symtablestack.pop(procdef.localst);
  940. { remove parasymtable }
  941. if procdef.parast.symtablelevel>=normal_function_level then
  942. symtablestack.pop(procdef.parast);
  943. { remove symtables for the class, but only if it is no nested function }
  944. if assigned(procdef._class) and
  945. not(assigned(parent) and
  946. assigned(parent.procdef) and
  947. assigned(parent.procdef._class)) then
  948. begin
  949. _class:=procdef._class;
  950. while assigned(_class) do
  951. begin
  952. symtablestack.pop(_class.symtable);
  953. _class:=_class.childof;
  954. end;
  955. end;
  956. end;
  957. procedure tcgprocinfo.resetprocdef;
  958. begin
  959. { remove code tree, if not inline procedure }
  960. if assigned(code) then
  961. begin
  962. { the inline procedure has already got a copy of the tree
  963. stored in procdef.inlininginfo }
  964. code.free;
  965. code:=nil;
  966. end;
  967. end;
  968. function checknodeinlining(procdef: tprocdef): boolean;
  969. var
  970. i : integer;
  971. currpara : tparavarsym;
  972. begin
  973. result := false;
  974. if (pi_has_assembler_block in current_procinfo.flags) then
  975. exit;
  976. for i:=0 to procdef.paras.count-1 do
  977. begin
  978. currpara:=tparavarsym(procdef.paras[i]);
  979. { we can't handle formaldefs and special arrays (the latter may need a }
  980. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  981. { you have to add 1 to all index operations if you directly inline it }
  982. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  983. (currpara.vardef.typ=formaldef)) or
  984. is_special_array(currpara.vardef) then
  985. exit;
  986. end;
  987. result:=true;
  988. end;
  989. procedure tcgprocinfo.parse_body;
  990. var
  991. oldprocinfo : tprocinfo;
  992. oldblock_type : tblock_type;
  993. st : TSymtable;
  994. begin
  995. oldprocinfo:=current_procinfo;
  996. oldblock_type:=block_type;
  997. { reset break and continue labels }
  998. block_type:=bt_body;
  999. current_procinfo:=self;
  1000. { calculate the lexical level }
  1001. if procdef.parast.symtablelevel>maxnesting then
  1002. Message(parser_e_too_much_lexlevel);
  1003. { static is also important for local procedures !! }
  1004. if (po_staticmethod in procdef.procoptions) then
  1005. allow_only_static:=true
  1006. else if (procdef.parast.symtablelevel=normal_function_level) then
  1007. allow_only_static:=false;
  1008. {$ifdef state_tracking}
  1009. { aktstate:=Tstate_storage.create;}
  1010. {$endif state_tracking}
  1011. { allocate the symbol for this procedure }
  1012. alloc_proc_symbol(procdef);
  1013. { add parast/localst to symtablestack }
  1014. add_to_symtablestack;
  1015. { save entry info }
  1016. entrypos:=current_filepos;
  1017. entryswitches:=current_settings.localswitches;
  1018. if (df_generic in procdef.defoptions) then
  1019. begin
  1020. { start token recorder for generic template }
  1021. procdef.initgeneric;
  1022. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1023. end;
  1024. { parse the code ... }
  1025. code:=block(current_module.islibrary);
  1026. if (df_generic in procdef.defoptions) then
  1027. begin
  1028. { stop token recorder for generic template }
  1029. current_scanner.stoprecordtokens;
  1030. { Give a warning for accesses in the static symtable that aren't visible
  1031. outside the current unit }
  1032. st:=procdef.owner;
  1033. while (st.symtabletype=ObjectSymtable) do
  1034. st:=st.defowner.owner;
  1035. if (pi_uses_static_symtable in flags) and
  1036. (st.symtabletype<>staticsymtable) then
  1037. Comment(V_Warning,'Global Generic template references static symtable');
  1038. end;
  1039. { save exit info }
  1040. exitswitches:=current_settings.localswitches;
  1041. exitpos:=last_endtoken_filepos;
  1042. { the procedure is now defined }
  1043. procdef.forwarddef:=false;
  1044. if assigned(code) then
  1045. begin
  1046. { get a better entry point }
  1047. entrypos:=code.fileinfo;
  1048. { Finish type checking pass }
  1049. do_typecheckpass(code);
  1050. end;
  1051. { Check for unused labels, forwards, symbols for procedures. Static
  1052. symtable is checked in pmodules.
  1053. The check must be done after the typecheckpass }
  1054. if (Errorcount=0) and
  1055. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1056. begin
  1057. { check if forwards are resolved }
  1058. tstoredsymtable(procdef.localst).check_forwards;
  1059. { check if all labels are used }
  1060. tstoredsymtable(procdef.localst).checklabels;
  1061. { remove cross unit overloads }
  1062. tstoredsymtable(procdef.localst).unchain_overloaded;
  1063. { check for unused symbols, but only if there is no asm block }
  1064. if not(pi_has_assembler_block in flags) then
  1065. begin
  1066. tstoredsymtable(procdef.localst).allsymbolsused;
  1067. tstoredsymtable(procdef.parast).allsymbolsused;
  1068. end;
  1069. end;
  1070. if (po_inline in procdef.procoptions) then
  1071. begin
  1072. { Can we inline this procedure? }
  1073. if checknodeinlining(procdef) then
  1074. begin
  1075. new(procdef.inlininginfo);
  1076. include(procdef.procoptions,po_has_inlininginfo);
  1077. procdef.inlininginfo^.code:=code.getcopy;
  1078. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1079. { The blocknode needs to set an exit label }
  1080. if procdef.inlininginfo^.code.nodetype=blockn then
  1081. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1082. end;
  1083. end;
  1084. { Print the node to tree.log }
  1085. if paraprintnodetree=1 then
  1086. printproc;
  1087. { ... remove symbol tables }
  1088. remove_from_symtablestack;
  1089. {$ifdef state_tracking}
  1090. { aktstate.destroy;}
  1091. {$endif state_tracking}
  1092. { reset to normal non static function }
  1093. if (procdef.parast.symtablelevel=normal_function_level) then
  1094. allow_only_static:=false;
  1095. current_procinfo:=oldprocinfo;
  1096. { Restore old state }
  1097. block_type:=oldblock_type;
  1098. end;
  1099. {****************************************************************************
  1100. PROCEDURE/FUNCTION PARSING
  1101. ****************************************************************************}
  1102. procedure check_init_paras(p:TObject;arg:pointer);
  1103. begin
  1104. if tsym(p).typ<>paravarsym then
  1105. exit;
  1106. with tparavarsym(p) do
  1107. if (not is_class(vardef) and
  1108. vardef.needs_inittable and
  1109. (varspez in [vs_value,vs_out])) then
  1110. include(current_procinfo.flags,pi_do_call);
  1111. end;
  1112. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1113. {
  1114. Parses the procedure directives, then parses the procedure body, then
  1115. generates the code for it
  1116. }
  1117. procedure do_generate_code(pi:tcgprocinfo);
  1118. var
  1119. hpi : tcgprocinfo;
  1120. begin
  1121. { generate code for this procedure }
  1122. pi.generate_code;
  1123. { process nested procs }
  1124. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1125. while assigned(hpi) do
  1126. begin
  1127. do_generate_code(hpi);
  1128. hpi:=tcgprocinfo(hpi.next);
  1129. end;
  1130. pi.resetprocdef;
  1131. end;
  1132. var
  1133. oldfailtokenmode : tmodeswitch;
  1134. isnestedproc : boolean;
  1135. begin
  1136. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1137. { create a new procedure }
  1138. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1139. current_module.procinfo:=current_procinfo;
  1140. current_procinfo.procdef:=pd;
  1141. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1142. { Insert mangledname }
  1143. pd.aliasnames.insert(pd.mangledname);
  1144. { Handle Export of this procedure }
  1145. if (po_exports in pd.procoptions) and
  1146. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1147. begin
  1148. pd.aliasnames.insert(pd.procsym.realname);
  1149. if cs_link_deffile in current_settings.globalswitches then
  1150. deffile.AddExport(pd.mangledname);
  1151. end;
  1152. { Insert result variables in the localst }
  1153. insert_funcret_local(pd);
  1154. { check if there are para's which require initing -> set }
  1155. { pi_do_call (if not yet set) }
  1156. if not(pi_do_call in current_procinfo.flags) then
  1157. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1158. { set _FAIL as keyword if constructor }
  1159. if (pd.proctypeoption=potype_constructor) then
  1160. begin
  1161. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1162. tokeninfo^[_FAIL].keyword:=m_all;
  1163. end;
  1164. tcgprocinfo(current_procinfo).parse_body;
  1165. { When it's a nested procedure then defer the code generation,
  1166. when back at normal function level then generate the code
  1167. for all defered nested procedures and the current procedure }
  1168. if isnestedproc then
  1169. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1170. else
  1171. begin
  1172. { We can't support inlining for procedures that have nested
  1173. procedures because the nested procedures use a fixed offset
  1174. for accessing locals in the parent procedure (PFV) }
  1175. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1176. begin
  1177. if (df_generic in current_procinfo.procdef.defoptions) then
  1178. {$warning TODO Add error message for nested procs in generics}
  1179. internalerror(200511151)
  1180. else if (po_inline in current_procinfo.procdef.procoptions) then
  1181. begin
  1182. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1183. Message(parser_w_inlining_disabled);
  1184. current_procinfo.procdef.proccalloption:=pocall_default;
  1185. end;
  1186. end;
  1187. if not(df_generic in current_procinfo.procdef.defoptions) then
  1188. do_generate_code(tcgprocinfo(current_procinfo));
  1189. end;
  1190. { reset _FAIL as _SELF normal }
  1191. if (pd.proctypeoption=potype_constructor) then
  1192. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1193. { release procinfo }
  1194. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1195. internalerror(200304274);
  1196. current_module.procinfo:=current_procinfo.parent;
  1197. { For specialization we didn't record the last semicolon. Moving this parsing
  1198. into the parse_body routine is not done because of having better file position
  1199. information available }
  1200. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1201. consume(_SEMICOLON);
  1202. if not isnestedproc then
  1203. { current_procinfo is checked for nil later on }
  1204. freeandnil(current_procinfo);
  1205. end;
  1206. procedure read_proc;
  1207. {
  1208. Parses the procedure directives, then parses the procedure body, then
  1209. generates the code for it
  1210. }
  1211. procedure do_generate_code(pi:tcgprocinfo);
  1212. var
  1213. hpi : tcgprocinfo;
  1214. begin
  1215. { generate code for this procedure }
  1216. pi.generate_code;
  1217. { process nested procs }
  1218. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1219. while assigned(hpi) do
  1220. begin
  1221. do_generate_code(hpi);
  1222. hpi:=tcgprocinfo(hpi.next);
  1223. end;
  1224. pi.resetprocdef;
  1225. end;
  1226. var
  1227. old_current_procinfo : tprocinfo;
  1228. pdflags : tpdflags;
  1229. pd,firstpd : tprocdef;
  1230. s : string;
  1231. begin
  1232. { save old state }
  1233. old_current_procinfo:=current_procinfo;
  1234. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1235. to an other procdef }
  1236. current_procinfo:=nil;
  1237. { parse procedure declaration }
  1238. if assigned(old_current_procinfo) and
  1239. assigned(old_current_procinfo.procdef) then
  1240. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1241. else
  1242. pd:=parse_proc_dec(nil);
  1243. { set the default function options }
  1244. if parse_only then
  1245. begin
  1246. pd.forwarddef:=true;
  1247. { set also the interface flag, for better error message when the
  1248. implementation doesn't much this header }
  1249. pd.interfacedef:=true;
  1250. include(pd.procoptions,po_global);
  1251. pdflags:=[pd_interface];
  1252. end
  1253. else
  1254. begin
  1255. pdflags:=[pd_body];
  1256. if (not current_module.in_interface) then
  1257. include(pdflags,pd_implemen);
  1258. if (not current_module.is_unit) or
  1259. maybe_smartlink_symbol or
  1260. {
  1261. taking addresses of static procedures goes wrong
  1262. if they aren't global when pic is used (FK)
  1263. }
  1264. (cs_create_pic in current_settings.moduleswitches) then
  1265. include(pd.procoptions,po_global);
  1266. pd.forwarddef:=false;
  1267. end;
  1268. { parse the directives that may follow }
  1269. parse_proc_directives(pd,pdflags);
  1270. { hint directives, these can be separated by semicolons here,
  1271. that needs to be handled here with a loop (PFV) }
  1272. while try_consume_hintdirective(pd.symoptions) do
  1273. Consume(_SEMICOLON);
  1274. { Set calling convention }
  1275. handle_calling_convention(pd);
  1276. { search for forward declarations }
  1277. if not proc_add_definition(pd) then
  1278. begin
  1279. { A method must be forward defined (in the object declaration) }
  1280. if assigned(pd._class) and
  1281. (not assigned(old_current_procinfo.procdef._class)) then
  1282. begin
  1283. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1284. tprocsym(pd.procsym).write_parameter_lists(pd);
  1285. end
  1286. else
  1287. begin
  1288. { Give a better error if there is a forward def in the interface and only
  1289. a single implementation }
  1290. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1291. if (not pd.forwarddef) and
  1292. (not pd.interfacedef) and
  1293. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1294. firstpd.forwarddef and
  1295. firstpd.interfacedef and
  1296. not(tprocsym(pd.procsym).ProcdefList.Count>2) then
  1297. begin
  1298. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1299. tprocsym(pd.procsym).write_parameter_lists(pd);
  1300. end;
  1301. end;
  1302. end;
  1303. { Set mangled name }
  1304. proc_set_mangledname(pd);
  1305. { compile procedure when a body is needed }
  1306. if (pd_body in pdflags) then
  1307. begin
  1308. read_proc_body(old_current_procinfo,pd);
  1309. end
  1310. else
  1311. begin
  1312. { Handle imports }
  1313. if (po_external in pd.procoptions) then
  1314. begin
  1315. { External declared in implementation, and there was already a
  1316. forward (or interface) declaration then we need to generate
  1317. a stub that calls the external routine }
  1318. if (not pd.forwarddef) and
  1319. (pd.hasforward) and
  1320. not(
  1321. assigned(pd.import_dll) and
  1322. (target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1323. system_arm_wince,system_i386_wince])
  1324. ) then
  1325. begin
  1326. s:=proc_get_importname(pd);
  1327. if s<>'' then
  1328. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1329. end;
  1330. { Import DLL specified? }
  1331. if assigned(pd.import_dll) then
  1332. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1333. else
  1334. begin
  1335. { add import name to external list for DLL scanning }
  1336. if tf_has_dllscanner in target_info.flags then
  1337. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1338. end;
  1339. end;
  1340. end;
  1341. { make sure that references to forward-declared functions are not }
  1342. { treated as references to external symbols, needed for darwin. }
  1343. { make sure we don't change the binding of real external symbols }
  1344. if not(po_external in pd.procoptions) then
  1345. begin
  1346. if (po_global in pd.procoptions) or
  1347. (cs_profile in current_settings.moduleswitches) then
  1348. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1349. else
  1350. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1351. end;
  1352. current_procinfo:=old_current_procinfo;
  1353. end;
  1354. {****************************************************************************
  1355. DECLARATION PARSING
  1356. ****************************************************************************}
  1357. { search in symtablestack for not complete classes }
  1358. procedure check_forward_class(p:TObject;arg:pointer);
  1359. begin
  1360. if (tsym(p).typ=typesym) and
  1361. (ttypesym(p).typedef.typ=objectdef) and
  1362. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1363. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1364. end;
  1365. procedure read_declarations(islibrary : boolean);
  1366. begin
  1367. repeat
  1368. if not assigned(current_procinfo) then
  1369. internalerror(200304251);
  1370. case token of
  1371. _LABEL:
  1372. label_dec;
  1373. _CONST:
  1374. const_dec;
  1375. _TYPE:
  1376. type_dec;
  1377. _VAR:
  1378. var_dec;
  1379. _THREADVAR:
  1380. threadvar_dec;
  1381. _CONSTRUCTOR,
  1382. _DESTRUCTOR,
  1383. _FUNCTION,
  1384. _PROCEDURE,
  1385. _OPERATOR,
  1386. _CLASS:
  1387. read_proc;
  1388. _EXPORTS:
  1389. begin
  1390. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1391. begin
  1392. Message(parser_e_syntax_error);
  1393. consume_all_until(_SEMICOLON);
  1394. end
  1395. else if islibrary or
  1396. (target_info.system in system_unit_program_exports) then
  1397. read_exports
  1398. else
  1399. begin
  1400. Message(parser_w_unsupported_feature);
  1401. consume(_BEGIN);
  1402. end;
  1403. end
  1404. else
  1405. begin
  1406. case idtoken of
  1407. _RESOURCESTRING :
  1408. begin
  1409. { m_class is needed, because the resourcestring
  1410. loading is in the ObjPas unit }
  1411. if (m_class in current_settings.modeswitches) then
  1412. resourcestring_dec
  1413. else
  1414. break;
  1415. end;
  1416. _PROPERTY:
  1417. begin
  1418. if (m_fpc in current_settings.modeswitches) then
  1419. property_dec
  1420. else
  1421. break;
  1422. end;
  1423. else
  1424. break;
  1425. end;
  1426. end;
  1427. end;
  1428. until false;
  1429. { check for incomplete class definitions, this is only required
  1430. for fpc modes }
  1431. if (m_fpc in current_settings.modeswitches) then
  1432. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1433. end;
  1434. procedure read_interface_declarations;
  1435. begin
  1436. repeat
  1437. case token of
  1438. _CONST :
  1439. const_dec;
  1440. _TYPE :
  1441. type_dec;
  1442. _VAR :
  1443. var_dec;
  1444. _THREADVAR :
  1445. threadvar_dec;
  1446. _FUNCTION,
  1447. _PROCEDURE,
  1448. _OPERATOR :
  1449. read_proc;
  1450. else
  1451. begin
  1452. case idtoken of
  1453. _RESOURCESTRING :
  1454. resourcestring_dec;
  1455. _PROPERTY:
  1456. begin
  1457. if (m_fpc in current_settings.modeswitches) then
  1458. property_dec
  1459. else
  1460. break;
  1461. end;
  1462. else
  1463. break;
  1464. end;
  1465. end;
  1466. end;
  1467. until false;
  1468. { check for incomplete class definitions, this is only required
  1469. for fpc modes }
  1470. if (m_fpc in current_settings.modeswitches) then
  1471. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1472. end;
  1473. {****************************************************************************
  1474. SPECIALIZATION BODY GENERATION
  1475. ****************************************************************************}
  1476. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1477. var
  1478. i : longint;
  1479. hp : tdef;
  1480. oldcurrent_filepos : tfileposinfo;
  1481. begin
  1482. if not((tsym(p).typ=typesym) and
  1483. (ttypesym(p).typedef.typ=objectdef) and
  1484. (df_specialization in ttypesym(p).typedef.defoptions)
  1485. ) then
  1486. exit;
  1487. { definitions }
  1488. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1489. begin
  1490. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1491. if hp.typ=procdef then
  1492. begin
  1493. if assigned(tprocdef(hp).genericdef) and
  1494. (tprocdef(hp).genericdef.typ=procdef) and
  1495. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1496. begin
  1497. oldcurrent_filepos:=current_filepos;
  1498. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1499. current_tokenpos:=current_filepos;
  1500. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1501. read_proc_body(nil,tprocdef(hp));
  1502. current_filepos:=oldcurrent_filepos;
  1503. end
  1504. else
  1505. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1506. end;
  1507. end;
  1508. end;
  1509. procedure generate_specialization_procs;
  1510. begin
  1511. if assigned(current_module.globalsymtable) then
  1512. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1513. if assigned(current_module.localsymtable) then
  1514. begin
  1515. symtablestack.push(current_module.localsymtable);
  1516. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1517. symtablestack.pop(current_module.localsymtable);
  1518. end;
  1519. end;
  1520. end.