psub.pas 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  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,optdfa;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  28. procedure add_entry_exit_code;
  29. procedure setup_tempgen;
  30. public
  31. { code for the subroutine as tree }
  32. code : tnode;
  33. { positions in the tree for init/final }
  34. entry_asmnode,
  35. loadpara_asmnode,
  36. exitlabel_asmnode,
  37. stackcheck_asmnode,
  38. init_asmnode,
  39. final_asmnode : tasmnode;
  40. dfabuilder : TDFABuilder;
  41. destructor destroy;override;
  42. procedure printproc(pass:string);
  43. procedure generate_code;
  44. procedure generate_code_tree;
  45. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  46. procedure resetprocdef;
  47. procedure add_to_symtablestack;
  48. procedure remove_from_symtablestack;
  49. procedure parse_body;
  50. function has_assembler_child : boolean;
  51. end;
  52. procedure printnode_reset;
  53. { reads the declaration blocks }
  54. procedure read_declarations(islibrary : boolean);
  55. { reads declarations in the interface part of a unit }
  56. procedure read_interface_declarations;
  57. { reads any routine in the implementation, or a non-method routine
  58. declaration in the interface (depending on whether or not parse_only is
  59. true) }
  60. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef);
  61. procedure generate_specialization_procs;
  62. implementation
  63. uses
  64. sysutils,
  65. { common }
  66. cutils,
  67. { global }
  68. globtype,tokens,verbose,comphook,constexp,
  69. systems,
  70. { aasm }
  71. cpuinfo,cpubase,aasmbase,aasmtai,aasmdata,
  72. { symtable }
  73. symconst,symbase,symsym,symtype,symtable,defutil,symcreat,
  74. paramgr,
  75. ppu,fmodule,
  76. { pass 1 }
  77. nutils,ngenutil,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  78. pass_1,
  79. {$ifdef state_tracking}
  80. nstate,
  81. {$endif state_tracking}
  82. { pass 2 }
  83. {$ifndef NOPASS2}
  84. pass_2,
  85. {$endif}
  86. { parser }
  87. scanner,import,gendef,
  88. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,pparautl,
  89. { codegen }
  90. tgobj,cgbase,cgobj,cgcpu,hlcgobj,hlcgcpu,dbgbase,
  91. ncgutil,regvars,
  92. optbase,
  93. opttail,
  94. optcse,optloop,
  95. optutils
  96. {$if defined(arm) or defined(powerpc) or defined(powerpc64) or defined(avr)}
  97. ,aasmcpu
  98. {$endif arm}
  99. {$ifndef NOOPT}
  100. {$ifdef i386}
  101. ,aopt386
  102. {$else i386}
  103. ,aopt
  104. {$endif i386}
  105. {$endif}
  106. ;
  107. {****************************************************************************
  108. PROCEDURE/FUNCTION BODY PARSING
  109. ****************************************************************************}
  110. procedure initializedefaultvars(p:TObject;arg:pointer);
  111. var
  112. b : tblocknode;
  113. begin
  114. if tsym(p).typ<>localvarsym then
  115. exit;
  116. with tabstractnormalvarsym(p) do
  117. begin
  118. if vo_is_default_var in varoptions then
  119. begin
  120. b:=tblocknode(arg);
  121. b.left:=cstatementnode.create(
  122. ccallnode.createintern('fpc_zeromem',
  123. ccallparanode.create(
  124. cordconstnode.create(vardef.size,ptruinttype,false),
  125. ccallparanode.create(
  126. caddrnode.create_internal(
  127. cloadnode.create(tsym(p),tsym(p).owner)),
  128. nil
  129. )
  130. )
  131. ),
  132. b.left);
  133. end;
  134. end;
  135. end;
  136. procedure initializevars(p:TObject;arg:pointer);
  137. var
  138. b : tblocknode;
  139. begin
  140. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  141. exit;
  142. with tabstractnormalvarsym(p) do
  143. begin
  144. if assigned(defaultconstsym) then
  145. begin
  146. b:=tblocknode(arg);
  147. b.left:=cstatementnode.create(
  148. cassignmentnode.create(
  149. cloadnode.create(tsym(p),tsym(p).owner),
  150. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  151. b.left);
  152. end
  153. else
  154. initializedefaultvars(p,arg);
  155. end;
  156. end;
  157. procedure check_finalize_paras(p:TObject;arg:pointer);
  158. begin
  159. if (tsym(p).typ=paravarsym) and
  160. tparavarsym(p).needs_finalization then
  161. include(current_procinfo.flags,pi_needs_implicit_finally);
  162. end;
  163. procedure check_finalize_locals(p:TObject;arg:pointer);
  164. begin
  165. { include the result: it needs to be finalized in case an exception }
  166. { occurs }
  167. if (tsym(p).typ=localvarsym) and
  168. (tlocalvarsym(p).refs>0) and
  169. is_managed_type(tlocalvarsym(p).vardef) then
  170. include(current_procinfo.flags,pi_needs_implicit_finally);
  171. end;
  172. function block(islibrary : boolean) : tnode;
  173. var
  174. oldfilepos: tfileposinfo;
  175. begin
  176. { parse const,types and vars }
  177. read_declarations(islibrary);
  178. { do we have an assembler block without the po_assembler?
  179. we should allow this for Delphi compatibility (PFV) }
  180. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  181. include(current_procinfo.procdef.procoptions,po_assembler);
  182. { Handle assembler block different }
  183. if (po_assembler in current_procinfo.procdef.procoptions) then
  184. begin
  185. block:=assembler_block;
  186. exit;
  187. end;
  188. {Unit initialization?.}
  189. if (
  190. assigned(current_procinfo.procdef.localst) and
  191. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  192. (current_module.is_unit or islibrary)
  193. ) then
  194. begin
  195. if (token=_END) then
  196. begin
  197. consume(_END);
  198. { We need at least a node, else the entry/exit code is not
  199. generated and thus no PASCALMAIN symbol which we need (PFV) }
  200. if islibrary then
  201. block:=cnothingnode.create
  202. else
  203. block:=nil;
  204. end
  205. else
  206. begin
  207. if token=_INITIALIZATION then
  208. begin
  209. { The library init code is already called and does not
  210. need to be in the initfinal table (PFV) }
  211. block:=statement_block(_INITIALIZATION);
  212. end
  213. else if token=_FINALIZATION then
  214. begin
  215. { when a unit has only a finalization section, we can come to this
  216. point when we try to read the nonh existing initalization section
  217. so we've to check if we are really try to parse the finalization }
  218. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  219. block:=statement_block(_FINALIZATION)
  220. else
  221. block:=nil;
  222. end
  223. else
  224. block:=statement_block(_BEGIN);
  225. end;
  226. end
  227. else
  228. begin
  229. { parse routine body }
  230. block:=statement_block(_BEGIN);
  231. { initialized variables }
  232. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  233. begin
  234. { initialization of local variables with their initial
  235. values: part of function entry }
  236. oldfilepos:=current_filepos;
  237. current_filepos:=current_procinfo.entrypos;
  238. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  239. current_filepos:=oldfilepos;
  240. end
  241. else if current_procinfo.procdef.localst.symtabletype=staticsymtable then
  242. begin
  243. { for program and unit initialization code we also need to
  244. initialize the local variables used of Default() }
  245. oldfilepos:=current_filepos;
  246. current_filepos:=current_procinfo.entrypos;
  247. current_procinfo.procdef.localst.SymList.ForEachCall(@initializedefaultvars,block);
  248. current_filepos:=oldfilepos;
  249. end;
  250. if assigned(current_procinfo.procdef.parentfpstruct) then
  251. begin
  252. { we only do this after the code has been parsed because
  253. otherwise for-loop counters moved to the struct cause
  254. errors; we still do it nevertheless to prevent false
  255. "unused" symbols warnings and to assist debug info
  256. generation }
  257. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  258. { finish the parentfpstruct (add padding, ...) }
  259. finish_parentfpstruct(current_procinfo.procdef);
  260. end;
  261. end;
  262. { init/final code must be wrapped later (after code for main proc body
  263. has been generated }
  264. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  265. block:=cnodeutils.wrap_proc_body(current_procinfo.procdef,block);
  266. end;
  267. {****************************************************************************
  268. PROCEDURE/FUNCTION COMPILING
  269. ****************************************************************************}
  270. procedure printnode_reset;
  271. begin
  272. assign(printnodefile,treelogfilename);
  273. {$push}{$I-}
  274. rewrite(printnodefile);
  275. {$pop}
  276. if ioresult<>0 then
  277. begin
  278. Comment(V_Error,'Error creating '+treelogfilename);
  279. exit;
  280. end;
  281. close(printnodefile);
  282. end;
  283. procedure add_label_init(p:TObject;arg:pointer);
  284. begin
  285. if tstoredsym(p).typ=labelsym then
  286. begin
  287. addstatement(tstatementnode(arg^),
  288. cifnode.create(caddnode.create(equaln,
  289. ccallnode.createintern('fpc_setjmp',
  290. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  291. cordconstnode.create(1,sinttype,true))
  292. ,cgotonode.create(tlabelsym(p)),nil)
  293. );
  294. end;
  295. end;
  296. function generate_bodyentry_block:tnode;
  297. var
  298. srsym : tsym;
  299. para : tcallparanode;
  300. call : tcallnode;
  301. newstatement : tstatementnode;
  302. begin
  303. result:=internalstatements(newstatement);
  304. if assigned(current_structdef) then
  305. begin
  306. { a constructor needs a help procedure }
  307. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  308. begin
  309. if is_class(current_structdef) then
  310. begin
  311. srsym:=search_struct_member(current_structdef,'NEWINSTANCE');
  312. if assigned(srsym) and
  313. (srsym.typ=procsym) then
  314. begin
  315. { if vmt>1 then newinstance }
  316. addstatement(newstatement,cifnode.create(
  317. caddnode.create(gtn,
  318. ctypeconvnode.create_internal(
  319. load_vmt_pointer_node,
  320. voidpointertype),
  321. cpointerconstnode.create(1,voidpointertype)),
  322. cassignmentnode.create(
  323. ctypeconvnode.create_internal(
  324. load_self_pointer_node,
  325. voidpointertype),
  326. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  327. nil));
  328. end
  329. else
  330. internalerror(200305108);
  331. end
  332. else
  333. if is_object(current_structdef) then
  334. begin
  335. { parameter 3 : vmt_offset }
  336. { parameter 2 : address of pointer to vmt,
  337. this is required to allow setting the vmt to -1 to indicate
  338. that memory was allocated }
  339. { parameter 1 : self pointer }
  340. para:=ccallparanode.create(
  341. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  342. ccallparanode.create(
  343. ctypeconvnode.create_internal(
  344. load_vmt_pointer_node,
  345. voidpointertype),
  346. ccallparanode.create(
  347. ctypeconvnode.create_internal(
  348. load_self_pointer_node,
  349. voidpointertype),
  350. nil)));
  351. addstatement(newstatement,cassignmentnode.create(
  352. ctypeconvnode.create_internal(
  353. load_self_pointer_node,
  354. voidpointertype),
  355. ccallnode.createintern('fpc_help_constructor',para)));
  356. end
  357. else
  358. if is_javaclass(current_structdef) then
  359. begin
  360. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  361. not current_procinfo.ConstructorCallingConstructor then
  362. begin
  363. { call inherited constructor }
  364. srsym:=search_struct_member(tobjectdef(current_structdef).childof,'CREATE');
  365. if assigned(srsym) and
  366. (srsym.typ=procsym) then
  367. begin
  368. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited]);
  369. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  370. addstatement(newstatement,call);
  371. end
  372. else
  373. internalerror(2011010312);
  374. end;
  375. end
  376. else
  377. if not is_record(current_structdef) then
  378. internalerror(200305103);
  379. { if self=nil then exit
  380. calling fail instead of exit is useless because
  381. there is nothing to dispose (PFV) }
  382. if is_class_or_object(current_structdef) then
  383. addstatement(newstatement,cifnode.create(
  384. caddnode.create(equaln,
  385. load_self_pointer_node,
  386. cnilnode.create),
  387. cexitnode.create(nil),
  388. nil));
  389. end;
  390. { maybe call BeforeDestruction for classes }
  391. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  392. is_class(current_structdef) then
  393. begin
  394. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  395. if assigned(srsym) and
  396. (srsym.typ=procsym) then
  397. begin
  398. { if vmt>0 then beforedestruction }
  399. addstatement(newstatement,cifnode.create(
  400. caddnode.create(gtn,
  401. ctypeconvnode.create_internal(
  402. load_vmt_pointer_node,ptrsinttype),
  403. ctypeconvnode.create_internal(
  404. cnilnode.create,ptrsinttype)),
  405. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  406. nil));
  407. end
  408. else
  409. internalerror(200305104);
  410. end;
  411. end;
  412. if m_non_local_goto in current_settings.modeswitches then
  413. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  414. end;
  415. function generate_bodyexit_block:tnode;
  416. var
  417. srsym : tsym;
  418. para : tcallparanode;
  419. newstatement : tstatementnode;
  420. oldlocalswitches: tlocalswitches;
  421. begin
  422. result:=internalstatements(newstatement);
  423. if assigned(current_structdef) then
  424. begin
  425. { Don't test self and the vmt here. The reason is that }
  426. { a constructor already checks whether these are valid }
  427. { before. Further, in case of TThread the thread may }
  428. { free the class instance right after AfterConstruction }
  429. { has been called, so it may no longer be valid (JM) }
  430. oldlocalswitches:=current_settings.localswitches;
  431. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  432. { a destructor needs a help procedure }
  433. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  434. begin
  435. if is_class(current_structdef) then
  436. begin
  437. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  438. if assigned(srsym) and
  439. (srsym.typ=procsym) then
  440. begin
  441. { if self<>0 and vmt<>0 then freeinstance }
  442. addstatement(newstatement,cifnode.create(
  443. caddnode.create(andn,
  444. caddnode.create(unequaln,
  445. load_self_pointer_node,
  446. cnilnode.create),
  447. caddnode.create(unequaln,
  448. ctypeconvnode.create(
  449. load_vmt_pointer_node,
  450. voidpointertype),
  451. cpointerconstnode.create(0,voidpointertype))),
  452. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  453. nil));
  454. end
  455. else
  456. internalerror(200305108);
  457. end
  458. else
  459. if is_object(current_structdef) then
  460. begin
  461. { finalize object data, but only if not in inherited call }
  462. if is_managed_type(current_structdef) then
  463. begin
  464. addstatement(newstatement,cifnode.create(
  465. caddnode.create(unequaln,
  466. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  467. cnilnode.create),
  468. cnodeutils.finalize_data_node(load_self_node),
  469. nil));
  470. end;
  471. { parameter 3 : vmt_offset }
  472. { parameter 2 : pointer to vmt }
  473. { parameter 1 : self pointer }
  474. para:=ccallparanode.create(
  475. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  476. ccallparanode.create(
  477. ctypeconvnode.create_internal(
  478. load_vmt_pointer_node,
  479. voidpointertype),
  480. ccallparanode.create(
  481. ctypeconvnode.create_internal(
  482. load_self_pointer_node,
  483. voidpointertype),
  484. nil)));
  485. addstatement(newstatement,
  486. ccallnode.createintern('fpc_help_destructor',para));
  487. end
  488. else if is_javaclass(current_structdef) then
  489. begin
  490. { nothing to do }
  491. end
  492. else
  493. internalerror(200305105);
  494. end;
  495. current_settings.localswitches:=oldlocalswitches;
  496. end;
  497. end;
  498. function generate_except_block:tnode;
  499. var
  500. newstatement : tstatementnode;
  501. begin
  502. generate_except_block:=internalstatements(newstatement);
  503. { a constructor needs call destructor (if available) when it
  504. is not inherited }
  505. if not assigned(current_structdef) or
  506. (current_procinfo.procdef.proctypeoption<>potype_constructor) then
  507. begin
  508. { no constructor }
  509. { must be the return value finalized before reraising the exception? }
  510. if (not is_void(current_procinfo.procdef.returndef)) and
  511. is_managed_type(current_procinfo.procdef.returndef) and
  512. (not paramanager.ret_in_param(current_procinfo.procdef.returndef, current_procinfo.procdef.proccalloption)) and
  513. (not is_class(current_procinfo.procdef.returndef)) then
  514. addstatement(newstatement,cnodeutils.finalize_data_node(load_result_node));
  515. end;
  516. end;
  517. {****************************************************************************
  518. TCGProcInfo
  519. ****************************************************************************}
  520. destructor tcgprocinfo.destroy;
  521. begin
  522. if assigned(code) then
  523. code.free;
  524. inherited destroy;
  525. end;
  526. procedure tcgprocinfo.printproc(pass:string);
  527. begin
  528. assign(printnodefile,treelogfilename);
  529. {$push}{$I-}
  530. append(printnodefile);
  531. if ioresult<>0 then
  532. rewrite(printnodefile);
  533. {$pop}
  534. if ioresult<>0 then
  535. begin
  536. Comment(V_Error,'Error creating '+treelogfilename);
  537. exit;
  538. end;
  539. writeln(printnodefile);
  540. writeln(printnodefile,'*******************************************************************************');
  541. writeln(printnodefile, pass);
  542. writeln(printnodefile,procdef.fullprocname(false));
  543. writeln(printnodefile,'*******************************************************************************');
  544. printnode(printnodefile,code);
  545. close(printnodefile);
  546. end;
  547. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  548. var
  549. oldlocalswitches: tlocalswitches;
  550. srsym: tsym;
  551. afterconstructionblock,
  552. exceptblock,
  553. newblock: tblocknode;
  554. newstatement: tstatementnode;
  555. pd: tprocdef;
  556. begin
  557. if assigned(procdef.struct) and
  558. (procdef.proctypeoption=potype_constructor) then
  559. begin
  560. withexceptblock:=
  561. withexceptblock and
  562. not(target_info.system in systems_garbage_collected_managed_types);
  563. { Don't test self and the vmt here. See generate_bodyexit_block }
  564. { why (JM) }
  565. oldlocalswitches:=current_settings.localswitches;
  566. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  567. { call AfterConstruction for classes }
  568. if is_class(procdef.struct) then
  569. begin
  570. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  571. if assigned(srsym) and
  572. (srsym.typ=procsym) then
  573. begin
  574. current_filepos:=exitpos;
  575. afterconstructionblock:=internalstatements(newstatement);
  576. { first execute all constructor code. If no exception
  577. occurred then we will execute afterconstruction,
  578. otherwise we won't (the exception will jump over us) }
  579. addstatement(newstatement,tocode);
  580. { if implicit finally node wasn't created, then exit label and
  581. finalization code must be handled here and placed before
  582. afterconstruction }
  583. if not ((pi_needs_implicit_finally in flags) and
  584. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  585. begin
  586. include(tocode.flags,nf_block_with_exit);
  587. addstatement(newstatement,final_asmnode);
  588. end;
  589. { Self can be nil when fail is called }
  590. { if self<>nil and vmt<>nil then afterconstruction }
  591. addstatement(newstatement,cifnode.create(
  592. caddnode.create(andn,
  593. caddnode.create(unequaln,
  594. load_self_node,
  595. cnilnode.create),
  596. caddnode.create(unequaln,
  597. load_vmt_pointer_node,
  598. cnilnode.create)),
  599. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  600. nil));
  601. tocode:=afterconstructionblock;
  602. end
  603. else
  604. internalerror(200305106);
  605. end;
  606. if withexceptblock and (procdef.struct.typ=objectdef) then
  607. begin
  608. { Generate the implicit "fail" code for a constructor (destroy
  609. in case an exception happened) }
  610. pd:=tobjectdef(procdef.struct).find_destructor;
  611. { this will always be the case for classes, since tobject has
  612. a destructor }
  613. if assigned(pd) then
  614. begin
  615. current_filepos:=exitpos;
  616. exceptblock:=internalstatements(newstatement);
  617. { first free the instance if non-nil }
  618. { if vmt<>0 then call destructor }
  619. addstatement(newstatement,cifnode.create(
  620. caddnode.create(unequaln,
  621. load_vmt_pointer_node,
  622. cnilnode.create),
  623. { cnf_create_failed -> don't call BeforeDestruction }
  624. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed]),
  625. nil));
  626. { then re-raise the exception }
  627. addstatement(newstatement,craisenode.create(nil,nil,nil));
  628. current_filepos:=entrypos;
  629. newblock:=internalstatements(newstatement);
  630. { try
  631. tocode
  632. except
  633. exceptblock
  634. end
  635. }
  636. addstatement(newstatement,ctryexceptnode.create(
  637. tocode,
  638. nil,
  639. exceptblock));
  640. tocode:=newblock;
  641. end;
  642. end;
  643. current_settings.localswitches:=oldlocalswitches;
  644. end;
  645. end;
  646. procedure tcgprocinfo.add_entry_exit_code;
  647. var
  648. finalcode,
  649. bodyentrycode,
  650. bodyexitcode,
  651. exceptcode,
  652. wrappedbody,
  653. newblock : tnode;
  654. codestatement,
  655. newstatement : tstatementnode;
  656. oldfilepos : tfileposinfo;
  657. is_constructor: boolean;
  658. begin
  659. is_constructor:=assigned(procdef.struct) and
  660. (procdef.proctypeoption=potype_constructor);
  661. oldfilepos:=current_filepos;
  662. { Generate code/locations used at start of proc }
  663. current_filepos:=entrypos;
  664. entry_asmnode:=casmnode.create_get_position;
  665. loadpara_asmnode:=casmnode.create_get_position;
  666. stackcheck_asmnode:=casmnode.create_get_position;
  667. init_asmnode:=casmnode.create_get_position;
  668. bodyentrycode:=generate_bodyentry_block;
  669. { Generate code/locations used at end of proc }
  670. current_filepos:=exitpos;
  671. exitlabel_asmnode:=casmnode.create_get_position;
  672. final_asmnode:=casmnode.create_get_position;
  673. bodyexitcode:=generate_bodyexit_block;
  674. { Generate procedure by combining init+body+final,
  675. depending on the implicit finally we need to add
  676. an try...finally...end wrapper }
  677. newblock:=internalstatements(newstatement);
  678. { initialization is common for all cases }
  679. addstatement(newstatement,loadpara_asmnode);
  680. addstatement(newstatement,stackcheck_asmnode);
  681. addstatement(newstatement,entry_asmnode);
  682. addstatement(newstatement,init_asmnode);
  683. addstatement(newstatement,bodyentrycode);
  684. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  685. (pi_needs_implicit_finally in flags) and
  686. { but it's useless in init/final code of units }
  687. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  688. not(po_assembler in procdef.procoptions) and
  689. not(target_info.system in systems_garbage_collected_managed_types) then
  690. begin
  691. { Generate special exception block only needed when
  692. implicit finaly is used }
  693. current_filepos:=exitpos;
  694. exceptcode:=generate_except_block;
  695. { Generate code that will be in the try...finally }
  696. finalcode:=internalstatements(codestatement);
  697. addstatement(codestatement,final_asmnode);
  698. current_filepos:=entrypos;
  699. wrappedbody:=ctryfinallynode.create_implicit(
  700. code,
  701. finalcode,
  702. exceptcode);
  703. { afterconstruction must be called after final_asmnode, because it
  704. has to execute after the temps have been finalised in case of a
  705. refcounted class (afterconstruction decreases the refcount
  706. without freeing the instance if the count becomes nil, while
  707. the finalising of the temps can free the instance) }
  708. maybe_add_constructor_wrapper(wrappedbody,true);
  709. addstatement(newstatement,wrappedbody);
  710. addstatement(newstatement,exitlabel_asmnode);
  711. addstatement(newstatement,bodyexitcode);
  712. { set flag the implicit finally has been generated }
  713. include(flags,pi_has_implicit_finally);
  714. end
  715. else
  716. begin
  717. { constructors need destroy-on-exception code even if they don't
  718. have managed variables/temps }
  719. maybe_add_constructor_wrapper(code,
  720. cs_implicit_exceptions in current_settings.moduleswitches);
  721. addstatement(newstatement,code);
  722. addstatement(newstatement,exitlabel_asmnode);
  723. addstatement(newstatement,bodyexitcode);
  724. if not is_constructor then
  725. addstatement(newstatement,final_asmnode);
  726. end;
  727. do_firstpass(newblock);
  728. code:=newblock;
  729. current_filepos:=oldfilepos;
  730. end;
  731. procedure clearrefs(p:TObject;arg:pointer);
  732. begin
  733. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  734. if tabstractvarsym(p).refs>1 then
  735. tabstractvarsym(p).refs:=1;
  736. end;
  737. procedure translate_registers(p:TObject;list:pointer);
  738. begin
  739. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  740. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  741. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  742. begin
  743. if not(cs_no_regalloc in current_settings.globalswitches) then
  744. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  745. if cs_asm_source in current_settings.globalswitches then
  746. TAsmList(list).concat(Tai_comment.Create(strpnew('Var '+tabstractnormalvarsym(p).realname+' located in register '+
  747. std_regname(tabstractnormalvarsym(p).localloc.register))))
  748. end;
  749. end;
  750. procedure tcgprocinfo.setup_tempgen;
  751. begin
  752. tg:=tgobjclass.create;
  753. {$if defined(x86) or defined(arm)}
  754. { try to strip the stack frame }
  755. { set the framepointer to esp if:
  756. - no assembler directive, those are handled in assembler_block
  757. in pstatment.pas (for cases not caught by the Delphi
  758. exception below)
  759. - no exceptions are used
  760. - no pushes are used/esp modifications, could be:
  761. * outgoing parameters on the stack
  762. * incoming parameters on the stack
  763. * open arrays
  764. - no inline assembler
  765. or
  766. - Delphi mode
  767. - assembler directive
  768. - no pushes are used/esp modifications, could be:
  769. * outgoing parameters on the stack
  770. * incoming parameters on the stack
  771. * open arrays
  772. - no local variables
  773. }
  774. if ((po_assembler in procdef.procoptions) and
  775. (m_delphi in current_settings.modeswitches) and
  776. { localst at main_program_level is a staticsymtable }
  777. (procdef.localst.symtablelevel<>main_program_level) and
  778. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  779. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  780. not(cs_generate_stackframes in current_settings.localswitches) and
  781. not(po_assembler in procdef.procoptions) and
  782. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  783. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  784. pi_needs_stackframe])=[])
  785. )
  786. then
  787. begin
  788. { we need the parameter info here to determine if the procedure gets
  789. parameters on the stack
  790. calling generate_parameter_info doesn't hurt but it costs time
  791. (necessary to init para_stack_size)
  792. }
  793. generate_parameter_info;
  794. if not(procdef.stack_tainting_parameter(calleeside)) and
  795. not(has_assembler_child) and (para_stack_size=0) then
  796. begin
  797. { Only need to set the framepointer }
  798. framepointer:=NR_STACK_POINTER_REG;
  799. tg.direction:=1;
  800. end;
  801. end;
  802. {$endif}
  803. {$ifdef MIPS}
  804. framepointer:=NR_STACK_POINTER_REG;
  805. tg.direction:=1;
  806. {$endif MIPS}
  807. { set the start offset to the start of the temp area in the stack }
  808. set_first_temp_offset;
  809. end;
  810. function tcgprocinfo.has_assembler_child : boolean;
  811. var
  812. hp : tprocinfo;
  813. begin
  814. result:=false;
  815. hp:=get_first_nestedproc;
  816. while assigned(hp) do
  817. begin
  818. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  819. begin
  820. result:=true;
  821. exit;
  822. end;
  823. hp:=tprocinfo(hp.next);
  824. end;
  825. end;
  826. procedure tcgprocinfo.generate_code_tree;
  827. var
  828. hpi : tcgprocinfo;
  829. begin
  830. { generate code for this procedure }
  831. generate_code;
  832. { process nested procedures }
  833. hpi:=tcgprocinfo(get_first_nestedproc);
  834. while assigned(hpi) do
  835. begin
  836. hpi.generate_code_tree;
  837. hpi:=tcgprocinfo(hpi.next);
  838. end;
  839. resetprocdef;
  840. end;
  841. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  842. which can be called by OS during stack unwind. This resembles nested procedures,
  843. but finalizer procedures do not have their own local variables and work directly
  844. with the stack frame of parent. In particular, the tempgen must be shared, so
  845. 1) finalizer procedure is able to finalize temps of the parent,
  846. 2) if the finalizer procedure is complex enough to need its own temps, they are
  847. allocated in stack frame of parent, so second-level finalizer procedures are
  848. not needed.
  849. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  850. procedure (after the parent) and have to do it inline.
  851. This is called by platform-specific tryfinallynodes during pass2.
  852. Here we put away the codegen (which carries the register allocator state), process
  853. the 'nested' procedure, then restore previous cg and continue processing the parent
  854. procedure. generate_code() will create another cg, but not another tempgen because
  855. setup_tempgen() is not called for potype_exceptfilter procedures. }
  856. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  857. var
  858. saved_cg: tcg;
  859. saved_hlcg: thlcgobj;
  860. begin
  861. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  862. InternalError(201201141);
  863. { flush code generated this far }
  864. aktproccode.concatlist(current_asmdata.CurrAsmList);
  865. { save the codegen }
  866. saved_cg:=cg;
  867. saved_hlcg:=hlcg;
  868. cg:=nil;
  869. hlcg:=nil;
  870. nestedpi.generate_code;
  871. { prevents generating code the second time when processing nested procedures }
  872. nestedpi.resetprocdef;
  873. cg:=saved_cg;
  874. hlcg:=saved_hlcg;
  875. add_reg_instruction_hook:[email protected]_reg_instruction;
  876. end;
  877. procedure tcgprocinfo.generate_code;
  878. var
  879. old_current_procinfo : tprocinfo;
  880. oldmaxfpuregisters : longint;
  881. oldfilepos : tfileposinfo;
  882. old_current_structdef : tabstractrecorddef;
  883. templist : TAsmList;
  884. headertai : tai;
  885. i : integer;
  886. varsym : tabstractnormalvarsym;
  887. {RedoDFA : boolean;}
  888. begin
  889. { the initialization procedure can be empty, then we
  890. don't need to generate anything. When it was an empty
  891. procedure there would be at least a blocknode }
  892. if not assigned(code) then
  893. exit;
  894. { We need valid code }
  895. if Errorcount<>0 then
  896. exit;
  897. { No code can be generated for generic template }
  898. if (df_generic in procdef.defoptions) then
  899. internalerror(200511152);
  900. { For regular procedures the RA and Tempgen shall not be available yet,
  901. but exception filters reuse Tempgen of parent }
  902. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  903. internalerror(200309201);
  904. old_current_procinfo:=current_procinfo;
  905. oldfilepos:=current_filepos;
  906. old_current_structdef:=current_structdef;
  907. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  908. current_procinfo:=self;
  909. current_filepos:=entrypos;
  910. current_structdef:=procdef.struct;
  911. templist:=TAsmList.create;
  912. { add parast/localst to symtablestack }
  913. add_to_symtablestack;
  914. { clear register count }
  915. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  916. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  917. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  918. if (procdef.localst.symtablelevel=main_program_level) and
  919. (not current_module.is_unit) then
  920. include(flags,pi_do_call);
  921. { set implicit_finally flag when there are locals/paras to be finalized }
  922. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  923. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  924. {$if defined(x86) or defined(arm)}
  925. { set implicit_finally flag for if procedure is safecall }
  926. if (tf_safecall_exceptions in target_info.flags) and
  927. (procdef.proccalloption=pocall_safecall) then
  928. include(flags, pi_needs_implicit_finally);
  929. {$endif}
  930. { firstpass everything }
  931. flowcontrol:=[];
  932. do_firstpass(code);
  933. {$ifdef i386}
  934. procdef.fpu_used:=node_resources_fpu(code);
  935. if procdef.fpu_used>0 then
  936. include(flags,pi_uses_fpu);
  937. {$endif i386}
  938. { Print the node to tree.log }
  939. if paraprintnodetree=1 then
  940. printproc( 'after the firstpass');
  941. { do this before adding the entry code else the tail recursion recognition won't work,
  942. if this causes troubles, it must be if'ed
  943. }
  944. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  945. (pi_is_recursive in flags) then
  946. do_opttail(code,procdef);
  947. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  948. { creating dfa is not always possible }
  949. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  950. pi_needs_implicit_finally,pi_has_implicit_finally])=[]) then
  951. begin
  952. dfabuilder:=TDFABuilder.Create;
  953. dfabuilder.createdfainfo(code);
  954. { when life info is available, we can give more sophisticated warning about unintialized
  955. variables }
  956. { iterate through life info of the first node }
  957. for i:=0 to dfabuilder.nodemap.count-1 do
  958. begin
  959. if DFASetIn(code.optinfo^.life,i) then
  960. case tnode(dfabuilder.nodemap[i]).nodetype of
  961. loadn:
  962. begin
  963. varsym:=tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry);
  964. { Give warning/note for living locals }
  965. if assigned(varsym.owner) and
  966. not(vo_is_external in varsym.varoptions) then
  967. begin
  968. if (vo_is_funcret in varsym.varoptions) then
  969. CGMessage(sym_w_function_result_uninitialized)
  970. else
  971. begin
  972. if (varsym.owner=procdef.localst) and not (vo_is_typed_const in varsym.varoptions) then
  973. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  974. end;
  975. end;
  976. end;
  977. end;
  978. end;
  979. include(flags,pi_dfaavailable);
  980. end;
  981. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  982. { our induction variable strength reduction doesn't like
  983. for loops with more than one entry }
  984. and not(pi_has_label in flags) then
  985. begin
  986. {RedoDFA:=}OptimizeInductionVariables(code);
  987. end;
  988. if cs_opt_nodecse in current_settings.optimizerswitches then
  989. do_optcse(code);
  990. { add implicit entry and exit code }
  991. add_entry_exit_code;
  992. { only do secondpass if there are no errors }
  993. if (ErrorCount=0) then
  994. begin
  995. create_hlcodegen;
  996. if (procdef.proctypeoption<>potype_exceptfilter) then
  997. setup_tempgen;
  998. { Create register allocator, must come after framepointer is known }
  999. hlcg.init_register_allocators;
  1000. generate_parameter_info;
  1001. { allocate got register if needed }
  1002. allocate_got_register(aktproccode);
  1003. { Allocate space in temp/registers for parast and localst }
  1004. current_filepos:=entrypos;
  1005. gen_alloc_symtable(aktproccode,procdef.parast);
  1006. gen_alloc_symtable(aktproccode,procdef.localst);
  1007. { Store temp offset for information about 'real' temps }
  1008. tempstart:=tg.lasttemp;
  1009. { Generate code to load register parameters in temps and insert local
  1010. copies for values parameters. This must be done before the code for the
  1011. body is generated because the localloc is updated.
  1012. Note: The generated code will be inserted after the code generation of
  1013. the body is finished, because only then the position is known }
  1014. {$ifdef oldregvars}
  1015. assign_regvars(code);
  1016. {$endif oldreg}
  1017. current_filepos:=entrypos;
  1018. hlcg.gen_load_para_value(templist);
  1019. { caller paraloc info is also necessary in the stackframe_entry
  1020. code of the ppc (and possibly other processors) }
  1021. procdef.init_paraloc_info(callerside);
  1022. { generate code for the node tree }
  1023. do_secondpass(code);
  1024. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1025. { The position of the loadpara_asmnode is now known }
  1026. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1027. { first generate entry and initialize code with the correct
  1028. position and switches }
  1029. current_filepos:=entrypos;
  1030. current_settings.localswitches:=entryswitches;
  1031. cg.set_regalloc_live_range_direction(rad_backwards);
  1032. hlcg.gen_entry_code(templist);
  1033. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1034. hlcg.gen_initialize_code(templist);
  1035. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1036. { now generate finalize and exit code with the correct position
  1037. and switches }
  1038. current_filepos:=exitpos;
  1039. current_settings.localswitches:=exitswitches;
  1040. cg.set_regalloc_live_range_direction(rad_forward);
  1041. if assigned(finalize_procinfo) then
  1042. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1043. else
  1044. begin
  1045. hlcg.gen_finalize_code(templist);
  1046. { the finalcode must be concated if there was no position available,
  1047. using insertlistafter will result in an insert at the start
  1048. when currentai=nil }
  1049. if assigned(final_asmnode) and assigned(final_asmnode.currenttai) then
  1050. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  1051. else
  1052. aktproccode.concatlist(templist);
  1053. end;
  1054. { insert exit label at the correct position }
  1055. hlcg.a_label(templist,CurrExitLabel);
  1056. if assigned(exitlabel_asmnode.currenttai) then
  1057. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1058. else
  1059. aktproccode.concatlist(templist);
  1060. { exit code }
  1061. hlcg.gen_exit_code(templist);
  1062. aktproccode.concatlist(templist);
  1063. {$ifdef OLDREGVARS}
  1064. { note: this must be done only after as much code as possible has }
  1065. { been generated. The result is that when you ungetregister() a }
  1066. { regvar, it will actually free the regvar (and alse free the }
  1067. { the regvars at the same time). Doing this too early will }
  1068. { confuse the register allocator, as the regvars will still be }
  1069. { used. It should be done before loading the result regs (so }
  1070. { they don't conflict with the regvars) and before }
  1071. { gen_entry_code (that one has to be able to allocate the }
  1072. { regvars again) (JM) }
  1073. free_regvars(aktproccode);
  1074. {$endif OLDREGVARS}
  1075. { generate symbol and save end of header position }
  1076. current_filepos:=entrypos;
  1077. hlcg.gen_proc_symbol(templist);
  1078. headertai:=tai(templist.last);
  1079. { insert symbol }
  1080. aktproccode.insertlist(templist);
  1081. { Free space in temp/registers for parast and localst, must be
  1082. done after gen_entry_code }
  1083. current_filepos:=exitpos;
  1084. { make sure the got/pic register doesn't get freed in the }
  1085. { middle of a loop }
  1086. if (cs_create_pic in current_settings.moduleswitches) and
  1087. (pi_needs_got in flags) and
  1088. (got<>NR_NO) then
  1089. cg.a_reg_sync(aktproccode,got);
  1090. gen_free_symtable(aktproccode,procdef.localst);
  1091. gen_free_symtable(aktproccode,procdef.parast);
  1092. { add code that will load the return value, this is not done
  1093. for assembler routines when they didn't reference the result
  1094. variable }
  1095. hlcg.gen_load_return_value(templist);
  1096. aktproccode.concatlist(templist);
  1097. { Already reserve all registers for stack checking code and
  1098. generate the call to the helper function }
  1099. if not(tf_no_generic_stackcheck in target_info.flags) and
  1100. (cs_check_stack in entryswitches) and
  1101. not(po_assembler in procdef.procoptions) and
  1102. (procdef.proctypeoption<>potype_proginit) then
  1103. begin
  1104. current_filepos:=entrypos;
  1105. gen_stack_check_call(templist);
  1106. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1107. end;
  1108. { this code (got loading) comes before everything which has }
  1109. { already been generated, so reset the info about already }
  1110. { backwards extended registers (so their live range can be }
  1111. { extended backwards even further if needed) }
  1112. { This code must be }
  1113. { a) generated after do_secondpass has been called }
  1114. { (because pi_needs_got may be set there) }
  1115. { b) generated before register allocation, because the }
  1116. { got/pic register can be a virtual one }
  1117. { c) inserted before the entry code, because the entry }
  1118. { code may need global symbols such as init rtti }
  1119. { d) inserted after the stackframe allocation, because }
  1120. { this register may have to be spilled }
  1121. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1122. current_filepos:=entrypos;
  1123. { load got if necessary }
  1124. cg.g_maybe_got_init(templist);
  1125. aktproccode.insertlistafter(headertai,templist);
  1126. { re-enable if more code at the end is ever generated here
  1127. cg.set_regalloc_live_range_direction(rad_forward);
  1128. }
  1129. {$ifndef NoOpt}
  1130. {$ifndef i386}
  1131. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1132. { do not optimize pure assembler procedures }
  1133. not(pi_is_assembler in flags) then
  1134. preregallocschedule(aktproccode);
  1135. {$endif i386}
  1136. {$endif NoOpt}
  1137. { The procedure body is finished, we can now
  1138. allocate the registers }
  1139. cg.do_register_allocation(aktproccode,headertai);
  1140. { translate imag. register to their real counter parts
  1141. this is necessary for debuginfo and verbose assembler output
  1142. when SSA will be implented, this will be more complicated because we've to
  1143. maintain location lists }
  1144. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1145. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1146. if (cs_create_pic in current_settings.moduleswitches) and
  1147. (pi_needs_got in flags) and
  1148. not(cs_no_regalloc in current_settings.globalswitches) and
  1149. (got<>NR_NO) then
  1150. cg.translate_register(got);
  1151. { Add save and restore of used registers }
  1152. current_filepos:=entrypos;
  1153. gen_save_used_regs(templist);
  1154. { Remember the last instruction of register saving block
  1155. (may be =nil for e.g. assembler procedures) }
  1156. endprologue_ai:=templist.last;
  1157. aktproccode.insertlistafter(headertai,templist);
  1158. current_filepos:=exitpos;
  1159. gen_restore_used_regs(aktproccode);
  1160. { We know the size of the stack, now we can generate the
  1161. parameter that is passed to the stack checking code }
  1162. if not(tf_no_generic_stackcheck in target_info.flags) and
  1163. (cs_check_stack in entryswitches) and
  1164. not(po_assembler in procdef.procoptions) and
  1165. (procdef.proctypeoption<>potype_proginit) then
  1166. begin
  1167. current_filepos:=entrypos;
  1168. gen_stack_check_size_para(templist);
  1169. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1170. end;
  1171. { Add entry code (stack allocation) after header }
  1172. current_filepos:=entrypos;
  1173. gen_proc_entry_code(templist);
  1174. aktproccode.insertlistafter(headertai,templist);
  1175. {$if defined(x86) or defined(arm)}
  1176. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1177. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1178. (tf_safecall_exceptions in target_info.flags) and
  1179. (procdef.proccalloption=pocall_safecall) then
  1180. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1181. {$endif}
  1182. { Add exit code at the end }
  1183. current_filepos:=exitpos;
  1184. gen_proc_exit_code(templist);
  1185. aktproccode.concatlist(templist);
  1186. { check if the implicit finally has been generated. The flag
  1187. should already be set in pass1 }
  1188. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1189. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1190. (pi_needs_implicit_finally in flags) and
  1191. not(po_assembler in procdef.procoptions) and
  1192. not(pi_has_implicit_finally in flags) and
  1193. not(target_info.system in systems_garbage_collected_managed_types) then
  1194. internalerror(200405231);
  1195. {$ifndef NoOpt}
  1196. if not(cs_no_regalloc in current_settings.globalswitches) then
  1197. begin
  1198. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1199. { do not optimize pure assembler procedures }
  1200. not(pi_is_assembler in flags) then
  1201. optimize(aktproccode);
  1202. {$ifndef i386}
  1203. { schedule after assembler optimization, it could have brought up
  1204. new schedule possibilities }
  1205. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1206. { do not optimize pure assembler procedures }
  1207. not(pi_is_assembler in flags) then
  1208. preregallocschedule(aktproccode);
  1209. {$endif i386}
  1210. end;
  1211. {$endif NoOpt}
  1212. {$ifdef ARM}
  1213. { because of the limited constant size of the arm, all data access is done pc relative }
  1214. finalizearmcode(aktproccode,aktlocaldata);
  1215. {$endif ARM}
  1216. {$ifdef AVR}
  1217. { because of the limited branch distance of cond. branches, they must be replaced
  1218. somtimes by normal jmps and an inverse branch }
  1219. finalizeavrcode(aktproccode);
  1220. {$endif AVR}
  1221. { Add end symbol and debug info }
  1222. { this must be done after the pcrelativedata is appended else the distance calculation of
  1223. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1224. so it should be inserted before the end symbol (FK)
  1225. }
  1226. current_filepos:=exitpos;
  1227. hlcg.gen_proc_symbol_end(templist);
  1228. aktproccode.concatlist(templist);
  1229. {$if defined(POWERPC) or defined(POWERPC64)}
  1230. fixup_jmps(aktproccode);
  1231. {$endif}
  1232. { insert line debuginfo }
  1233. if (cs_debuginfo in current_settings.moduleswitches) or
  1234. (cs_use_lineinfo in current_settings.globalswitches) then
  1235. current_debuginfo.insertlineinfo(aktproccode);
  1236. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1237. { only now we can remove the temps }
  1238. if (procdef.proctypeoption<>potype_exceptfilter) then
  1239. begin
  1240. tg.resettempgen;
  1241. tg.free;
  1242. tg:=nil;
  1243. end;
  1244. { stop tempgen and ra }
  1245. hlcg.done_register_allocators;
  1246. destroy_hlcodegen;
  1247. end;
  1248. dfabuilder.free;
  1249. { restore symtablestack }
  1250. remove_from_symtablestack;
  1251. { restore }
  1252. templist.free;
  1253. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1254. current_filepos:=oldfilepos;
  1255. current_structdef:=old_current_structdef;
  1256. current_procinfo:=old_current_procinfo;
  1257. end;
  1258. procedure tcgprocinfo.add_to_symtablestack;
  1259. begin
  1260. { insert symtables for the class, but only if it is no nested function }
  1261. if assigned(procdef.struct) and
  1262. not(assigned(parent) and
  1263. assigned(parent.procdef) and
  1264. assigned(parent.procdef.struct)) then
  1265. push_nested_hierarchy(procdef.struct);
  1266. { insert parasymtable in symtablestack when parsing
  1267. a function }
  1268. if procdef.parast.symtablelevel>=normal_function_level then
  1269. symtablestack.push(procdef.parast);
  1270. { insert localsymtable, except for the main procedure
  1271. (in that case the localst is the unit's static symtable,
  1272. which is already on the stack) }
  1273. if procdef.localst.symtablelevel>=normal_function_level then
  1274. symtablestack.push(procdef.localst);
  1275. end;
  1276. procedure tcgprocinfo.remove_from_symtablestack;
  1277. begin
  1278. { remove localsymtable }
  1279. if procdef.localst.symtablelevel>=normal_function_level then
  1280. symtablestack.pop(procdef.localst);
  1281. { remove parasymtable }
  1282. if procdef.parast.symtablelevel>=normal_function_level then
  1283. symtablestack.pop(procdef.parast);
  1284. { remove symtables for the class, but only if it is no nested function }
  1285. if assigned(procdef.struct) and
  1286. not(assigned(parent) and
  1287. assigned(parent.procdef) and
  1288. assigned(parent.procdef.struct)) then
  1289. pop_nested_hierarchy(procdef.struct);
  1290. end;
  1291. procedure tcgprocinfo.resetprocdef;
  1292. begin
  1293. { remove code tree, if not inline procedure }
  1294. if assigned(code) then
  1295. begin
  1296. { the inline procedure has already got a copy of the tree
  1297. stored in procdef.inlininginfo }
  1298. code.free;
  1299. code:=nil;
  1300. end;
  1301. end;
  1302. function checknodeinlining(procdef: tprocdef): boolean;
  1303. var
  1304. i : integer;
  1305. currpara : tparavarsym;
  1306. begin
  1307. result := false;
  1308. if (pi_has_assembler_block in current_procinfo.flags) then
  1309. begin
  1310. Message1(parser_h_not_supported_for_inline,'assembler');
  1311. Message(parser_h_inlining_disabled);
  1312. exit;
  1313. end;
  1314. for i:=0 to procdef.paras.count-1 do
  1315. begin
  1316. currpara:=tparavarsym(procdef.paras[i]);
  1317. case currpara.vardef.typ of
  1318. formaldef :
  1319. begin
  1320. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  1321. begin
  1322. Message1(parser_h_not_supported_for_inline,'formal parameter');
  1323. Message(parser_h_inlining_disabled);
  1324. exit;
  1325. end;
  1326. end;
  1327. arraydef :
  1328. begin
  1329. if is_array_of_const(currpara.vardef) or
  1330. is_variant_array(currpara.vardef) then
  1331. begin
  1332. Message1(parser_h_not_supported_for_inline,'array of const');
  1333. Message(parser_h_inlining_disabled);
  1334. exit;
  1335. end;
  1336. { open arrays might need re-basing of the index, i.e. if you pass
  1337. an array[1..10] as open array, you have to add 1 to all index operations
  1338. if you directly inline it }
  1339. if is_open_array(currpara.vardef) then
  1340. begin
  1341. Message1(parser_h_not_supported_for_inline,'open array');
  1342. Message(parser_h_inlining_disabled);
  1343. exit;
  1344. end;
  1345. end;
  1346. end;
  1347. end;
  1348. result:=true;
  1349. end;
  1350. procedure tcgprocinfo.parse_body;
  1351. var
  1352. old_current_procinfo : tprocinfo;
  1353. old_block_type : tblock_type;
  1354. st : TSymtable;
  1355. old_current_structdef: tabstractrecorddef;
  1356. old_current_genericdef,
  1357. old_current_specializedef: tstoreddef;
  1358. old_parse_generic: boolean;
  1359. begin
  1360. old_current_procinfo:=current_procinfo;
  1361. old_block_type:=block_type;
  1362. old_current_structdef:=current_structdef;
  1363. old_current_genericdef:=current_genericdef;
  1364. old_current_specializedef:=current_specializedef;
  1365. old_parse_generic:=parse_generic;
  1366. current_procinfo:=self;
  1367. current_structdef:=procdef.struct;
  1368. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1369. begin
  1370. current_genericdef:=current_structdef;
  1371. parse_generic:=true;
  1372. end;
  1373. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1374. current_specializedef:=current_structdef;
  1375. { calculate the lexical level }
  1376. if procdef.parast.symtablelevel>maxnesting then
  1377. Message(parser_e_too_much_lexlevel);
  1378. block_type:=bt_body;
  1379. {$ifdef state_tracking}
  1380. { aktstate:=Tstate_storage.create;}
  1381. {$endif state_tracking}
  1382. { allocate the symbol for this procedure }
  1383. alloc_proc_symbol(procdef);
  1384. { add parast/localst to symtablestack }
  1385. add_to_symtablestack;
  1386. { save entry info }
  1387. entrypos:=current_filepos;
  1388. entryswitches:=current_settings.localswitches;
  1389. if (df_generic in procdef.defoptions) then
  1390. begin
  1391. { start token recorder for generic template }
  1392. procdef.initgeneric;
  1393. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1394. end;
  1395. { parse the code ... }
  1396. code:=block(current_module.islibrary);
  1397. if (df_generic in procdef.defoptions) then
  1398. begin
  1399. { stop token recorder for generic template }
  1400. current_scanner.stoprecordtokens;
  1401. { Give an error for accesses in the static symtable that aren't visible
  1402. outside the current unit }
  1403. st:=procdef.owner;
  1404. while (st.symtabletype=ObjectSymtable) do
  1405. st:=st.defowner.owner;
  1406. if (pi_uses_static_symtable in flags) and
  1407. (st.symtabletype<>staticsymtable) then
  1408. Comment(V_Error,'Global Generic template references static symtable');
  1409. end;
  1410. { save exit info }
  1411. exitswitches:=current_settings.localswitches;
  1412. exitpos:=last_endtoken_filepos;
  1413. { the procedure is now defined }
  1414. procdef.forwarddef:=false;
  1415. if assigned(code) then
  1416. begin
  1417. { get a better entry point }
  1418. entrypos:=code.fileinfo;
  1419. { Finish type checking pass }
  1420. do_typecheckpass(code);
  1421. if assigned(procdef.parentfpinitblock) then
  1422. begin
  1423. tblocknode(code).left:=cstatementnode.create(procdef.parentfpinitblock,tblocknode(code).left);
  1424. do_typecheckpass(tblocknode(code).left);
  1425. procdef.parentfpinitblock:=nil;
  1426. end;
  1427. end;
  1428. { Check for unused labels, forwards, symbols for procedures. Static
  1429. symtable is checked in pmodules.
  1430. The check must be done after the typecheckpass }
  1431. if (Errorcount=0) and
  1432. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1433. begin
  1434. { check if forwards are resolved }
  1435. tstoredsymtable(procdef.localst).check_forwards;
  1436. { check if all labels are used }
  1437. tstoredsymtable(procdef.localst).checklabels;
  1438. { check for unused symbols, but only if there is no asm block }
  1439. if not(pi_has_assembler_block in flags) then
  1440. begin
  1441. tstoredsymtable(procdef.localst).allsymbolsused;
  1442. tstoredsymtable(procdef.parast).allsymbolsused;
  1443. end;
  1444. end;
  1445. if (po_inline in procdef.procoptions) then
  1446. begin
  1447. { Can we inline this procedure? }
  1448. if checknodeinlining(procdef) then
  1449. begin
  1450. new(procdef.inlininginfo);
  1451. include(procdef.procoptions,po_has_inlininginfo);
  1452. procdef.inlininginfo^.code:=code.getcopy;
  1453. procdef.inlininginfo^.flags:=flags;
  1454. { The blocknode needs to set an exit label }
  1455. if procdef.inlininginfo^.code.nodetype=blockn then
  1456. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1457. end;
  1458. end;
  1459. { Print the node to tree.log }
  1460. if paraprintnodetree=1 then
  1461. printproc( 'after parsing');
  1462. { ... remove symbol tables }
  1463. remove_from_symtablestack;
  1464. {$ifdef state_tracking}
  1465. { aktstate.destroy;}
  1466. {$endif state_tracking}
  1467. current_structdef:=old_current_structdef;
  1468. current_genericdef:=old_current_genericdef;
  1469. current_specializedef:=old_current_specializedef;
  1470. current_procinfo:=old_current_procinfo;
  1471. parse_generic:=old_parse_generic;
  1472. { Restore old state }
  1473. block_type:=old_block_type;
  1474. end;
  1475. {****************************************************************************
  1476. PROCEDURE/FUNCTION PARSING
  1477. ****************************************************************************}
  1478. procedure check_init_paras(p:TObject;arg:pointer);
  1479. begin
  1480. if tsym(p).typ<>paravarsym then
  1481. exit;
  1482. with tparavarsym(p) do
  1483. if is_managed_type(vardef) and
  1484. (varspez in [vs_value,vs_out]) then
  1485. include(current_procinfo.flags,pi_do_call);
  1486. end;
  1487. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1488. {
  1489. Parses the procedure directives, then parses the procedure body, then
  1490. generates the code for it
  1491. }
  1492. var
  1493. oldfailtokenmode : tmodeswitch;
  1494. isnestedproc : boolean;
  1495. begin
  1496. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1497. { create a new procedure }
  1498. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1499. current_module.procinfo:=current_procinfo;
  1500. current_procinfo.procdef:=pd;
  1501. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1502. { Insert mangledname }
  1503. pd.aliasnames.insert(pd.mangledname);
  1504. { Handle Export of this procedure }
  1505. if (po_exports in pd.procoptions) and
  1506. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1507. begin
  1508. pd.aliasnames.insert(pd.procsym.realname);
  1509. if cs_link_deffile in current_settings.globalswitches then
  1510. deffile.AddExport(pd.mangledname);
  1511. end;
  1512. { Insert result variables in the localst }
  1513. insert_funcret_local(pd);
  1514. { check if there are para's which require initing -> set }
  1515. { pi_do_call (if not yet set) }
  1516. if not(pi_do_call in current_procinfo.flags) then
  1517. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1518. { set _FAIL as keyword if constructor }
  1519. if (pd.proctypeoption=potype_constructor) then
  1520. begin
  1521. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1522. tokeninfo^[_FAIL].keyword:=m_all;
  1523. end;
  1524. tcgprocinfo(current_procinfo).parse_body;
  1525. { We can't support inlining for procedures that have nested
  1526. procedures because the nested procedures use a fixed offset
  1527. for accessing locals in the parent procedure (PFV) }
  1528. if current_procinfo.has_nestedprocs then
  1529. begin
  1530. if (df_generic in current_procinfo.procdef.defoptions) then
  1531. Comment(V_Error,'Generic methods cannot have nested procedures')
  1532. else
  1533. if (po_inline in current_procinfo.procdef.procoptions) then
  1534. begin
  1535. Message1(parser_h_not_supported_for_inline,'nested procedures');
  1536. Message(parser_h_inlining_disabled);
  1537. exclude(current_procinfo.procdef.procoptions,po_inline);
  1538. end;
  1539. end;
  1540. { When it's a nested procedure then defer the code generation,
  1541. when back at normal function level then generate the code
  1542. for all defered nested procedures and the current procedure }
  1543. if not isnestedproc then
  1544. begin
  1545. if not(df_generic in current_procinfo.procdef.defoptions) then
  1546. tcgprocinfo(current_procinfo).generate_code_tree;
  1547. end;
  1548. { reset _FAIL as _SELF normal }
  1549. if (pd.proctypeoption=potype_constructor) then
  1550. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1551. { release procinfo }
  1552. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1553. internalerror(200304274);
  1554. current_module.procinfo:=current_procinfo.parent;
  1555. { For specialization we didn't record the last semicolon. Moving this parsing
  1556. into the parse_body routine is not done because of having better file position
  1557. information available }
  1558. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1559. consume(_SEMICOLON);
  1560. if not isnestedproc then
  1561. { current_procinfo is checked for nil later on }
  1562. freeandnil(current_procinfo);
  1563. end;
  1564. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef);
  1565. {
  1566. Parses the procedure directives, then parses the procedure body, then
  1567. generates the code for it
  1568. }
  1569. var
  1570. old_current_procinfo : tprocinfo;
  1571. old_current_structdef: tabstractrecorddef;
  1572. old_current_genericdef,
  1573. old_current_specializedef: tstoreddef;
  1574. pdflags : tpdflags;
  1575. pd,firstpd : tprocdef;
  1576. s : string;
  1577. begin
  1578. { save old state }
  1579. old_current_procinfo:=current_procinfo;
  1580. old_current_structdef:=current_structdef;
  1581. old_current_genericdef:=current_genericdef;
  1582. old_current_specializedef:=current_specializedef;
  1583. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1584. to another procdef }
  1585. current_procinfo:=nil;
  1586. current_structdef:=nil;
  1587. current_genericdef:=nil;
  1588. current_specializedef:=nil;
  1589. if not assigned(usefwpd) then
  1590. { parse procedure declaration }
  1591. pd:=parse_proc_dec(isclassmethod,old_current_structdef)
  1592. else
  1593. pd:=usefwpd;
  1594. { set the default function options }
  1595. if parse_only then
  1596. begin
  1597. pd.forwarddef:=true;
  1598. { set also the interface flag, for better error message when the
  1599. implementation doesn't much this header }
  1600. pd.interfacedef:=true;
  1601. include(pd.procoptions,po_global);
  1602. pdflags:=[pd_interface];
  1603. end
  1604. else
  1605. begin
  1606. pdflags:=[pd_body];
  1607. if (not current_module.in_interface) then
  1608. include(pdflags,pd_implemen);
  1609. if (not current_module.is_unit) or
  1610. create_smartlink or
  1611. {
  1612. taking addresses of static procedures goes wrong
  1613. if they aren't global when pic is used (FK)
  1614. }
  1615. (cs_create_pic in current_settings.moduleswitches) then
  1616. include(pd.procoptions,po_global);
  1617. pd.forwarddef:=false;
  1618. end;
  1619. if not assigned(usefwpd) then
  1620. begin
  1621. { parse the directives that may follow }
  1622. parse_proc_directives(pd,pdflags);
  1623. { hint directives, these can be separated by semicolons here,
  1624. that needs to be handled here with a loop (PFV) }
  1625. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1626. Consume(_SEMICOLON);
  1627. { Set calling convention }
  1628. handle_calling_convention(pd);
  1629. end;
  1630. { search for forward declarations }
  1631. if not proc_add_definition(pd) then
  1632. begin
  1633. { A method must be forward defined (in the object declaration) }
  1634. if assigned(pd.struct) and
  1635. (not assigned(old_current_structdef)) then
  1636. begin
  1637. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1638. tprocsym(pd.procsym).write_parameter_lists(pd);
  1639. end
  1640. else
  1641. begin
  1642. { Give a better error if there is a forward def in the interface and only
  1643. a single implementation }
  1644. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1645. if (not pd.forwarddef) and
  1646. (not pd.interfacedef) and
  1647. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1648. firstpd.forwarddef and
  1649. firstpd.interfacedef and
  1650. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1651. { don't give an error if it may be an overload }
  1652. not(m_fpc in current_settings.modeswitches) and
  1653. (not(po_overload in pd.procoptions) or
  1654. not(po_overload in firstpd.procoptions)) then
  1655. begin
  1656. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1657. tprocsym(pd.procsym).write_parameter_lists(pd);
  1658. end;
  1659. end;
  1660. end;
  1661. { Set mangled name }
  1662. proc_set_mangledname(pd);
  1663. { compile procedure when a body is needed }
  1664. if (pd_body in pdflags) then
  1665. begin
  1666. read_proc_body(old_current_procinfo,pd);
  1667. end
  1668. else
  1669. begin
  1670. { Handle imports }
  1671. if (po_external in pd.procoptions) then
  1672. begin
  1673. { External declared in implementation, and there was already a
  1674. forward (or interface) declaration then we need to generate
  1675. a stub that calls the external routine }
  1676. if (not pd.forwarddef) and
  1677. (pd.hasforward)
  1678. { it is unclear to me what's the use of the following condition,
  1679. so commented out, see also issue #18371 (FK)
  1680. and
  1681. not(
  1682. assigned(pd.import_dll) and
  1683. (target_info.system in [system_i386_wdosx,
  1684. system_arm_wince,system_i386_wince])
  1685. ) } then
  1686. begin
  1687. s:=proc_get_importname(pd);
  1688. if s<>'' then
  1689. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1690. end;
  1691. { Import DLL specified? }
  1692. if assigned(pd.import_dll) then
  1693. begin
  1694. if assigned (pd.import_name) then
  1695. current_module.AddExternalImport(pd.import_dll^,
  1696. pd.import_name^,proc_get_importname(pd),
  1697. pd.import_nr,false,false)
  1698. else
  1699. current_module.AddExternalImport(pd.import_dll^,
  1700. proc_get_importname(pd),proc_get_importname(pd),
  1701. pd.import_nr,false,true);
  1702. end
  1703. else
  1704. begin
  1705. { add import name to external list for DLL scanning }
  1706. if tf_has_dllscanner in target_info.flags then
  1707. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1708. end;
  1709. end;
  1710. end;
  1711. { make sure that references to forward-declared functions are not }
  1712. { treated as references to external symbols, needed for darwin. }
  1713. { make sure we don't change the binding of real external symbols }
  1714. if not(po_external in pd.procoptions) then
  1715. begin
  1716. if (po_global in pd.procoptions) or
  1717. (cs_profile in current_settings.moduleswitches) then
  1718. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1719. else
  1720. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1721. end;
  1722. current_structdef:=old_current_structdef;
  1723. current_genericdef:=old_current_genericdef;
  1724. current_specializedef:=old_current_specializedef;
  1725. current_procinfo:=old_current_procinfo;
  1726. end;
  1727. {****************************************************************************
  1728. DECLARATION PARSING
  1729. ****************************************************************************}
  1730. { search in symtablestack for not complete classes }
  1731. procedure check_forward_class(p:TObject;arg:pointer);
  1732. begin
  1733. if (tsym(p).typ=typesym) and
  1734. (ttypesym(p).typedef.typ=objectdef) and
  1735. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1736. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1737. end;
  1738. procedure read_declarations(islibrary : boolean);
  1739. var
  1740. is_classdef:boolean;
  1741. begin
  1742. is_classdef:=false;
  1743. repeat
  1744. if not assigned(current_procinfo) then
  1745. internalerror(200304251);
  1746. case token of
  1747. _LABEL:
  1748. label_dec;
  1749. _CONST:
  1750. const_dec;
  1751. _TYPE:
  1752. type_dec;
  1753. _VAR:
  1754. var_dec;
  1755. _THREADVAR:
  1756. threadvar_dec;
  1757. _CLASS:
  1758. begin
  1759. is_classdef:=false;
  1760. if try_to_consume(_CLASS) then
  1761. begin
  1762. { class modifier is only allowed for procedures, functions, }
  1763. { constructors, destructors }
  1764. if not(token in [_FUNCTION,_PROCEDURE,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1765. not((token=_ID) and (idtoken=_OPERATOR)) then
  1766. Message(parser_e_procedure_or_function_expected);
  1767. if is_interface(current_structdef) then
  1768. Message(parser_e_no_static_method_in_interfaces)
  1769. else
  1770. { class methods are also allowed for Objective-C protocols }
  1771. is_classdef:=true;
  1772. end;
  1773. end;
  1774. _CONSTRUCTOR,
  1775. _DESTRUCTOR,
  1776. _FUNCTION,
  1777. _PROCEDURE,
  1778. _OPERATOR:
  1779. begin
  1780. read_proc(is_classdef,nil);
  1781. is_classdef:=false;
  1782. end;
  1783. _EXPORTS:
  1784. begin
  1785. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1786. begin
  1787. Message(parser_e_syntax_error);
  1788. consume_all_until(_SEMICOLON);
  1789. end
  1790. else if islibrary or
  1791. (target_info.system in systems_unit_program_exports) then
  1792. read_exports
  1793. else
  1794. begin
  1795. Message(parser_w_unsupported_feature);
  1796. consume(_BEGIN);
  1797. end;
  1798. end
  1799. else
  1800. begin
  1801. case idtoken of
  1802. _RESOURCESTRING:
  1803. begin
  1804. { m_class is needed, because the resourcestring
  1805. loading is in the ObjPas unit }
  1806. { if (m_class in current_settings.modeswitches) then}
  1807. resourcestring_dec
  1808. { else
  1809. break;}
  1810. end;
  1811. _OPERATOR:
  1812. begin
  1813. if is_classdef then
  1814. begin
  1815. read_proc(is_classdef,nil);
  1816. is_classdef:=false;
  1817. end
  1818. else
  1819. break;
  1820. end;
  1821. _PROPERTY:
  1822. begin
  1823. if (m_fpc in current_settings.modeswitches) then
  1824. property_dec
  1825. else
  1826. break;
  1827. end;
  1828. else
  1829. break;
  1830. end;
  1831. end;
  1832. end;
  1833. until false;
  1834. { add implementations for synthetic method declarations added by
  1835. the compiler (not for unit/program init functions, their localst
  1836. is the staticst -> would duplicate the work done in pmodules) }
  1837. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  1838. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  1839. { check for incomplete class definitions, this is only required
  1840. for fpc modes }
  1841. if (m_fpc in current_settings.modeswitches) then
  1842. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1843. end;
  1844. procedure read_interface_declarations;
  1845. begin
  1846. repeat
  1847. case token of
  1848. _CONST :
  1849. const_dec;
  1850. _TYPE :
  1851. type_dec;
  1852. _VAR :
  1853. var_dec;
  1854. _THREADVAR :
  1855. threadvar_dec;
  1856. _FUNCTION,
  1857. _PROCEDURE,
  1858. _OPERATOR :
  1859. read_proc(false,nil);
  1860. else
  1861. begin
  1862. case idtoken of
  1863. _RESOURCESTRING :
  1864. resourcestring_dec;
  1865. _PROPERTY:
  1866. begin
  1867. if (m_fpc in current_settings.modeswitches) then
  1868. property_dec
  1869. else
  1870. break;
  1871. end;
  1872. else
  1873. break;
  1874. end;
  1875. end;
  1876. end;
  1877. until false;
  1878. { check for incomplete class definitions, this is only required
  1879. for fpc modes }
  1880. if (m_fpc in current_settings.modeswitches) then
  1881. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1882. end;
  1883. {****************************************************************************
  1884. SPECIALIZATION BODY GENERATION
  1885. ****************************************************************************}
  1886. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1887. var
  1888. oldcurrent_filepos : tfileposinfo;
  1889. specobj : tabstractrecorddef;
  1890. state : tspecializationstate;
  1891. procedure process_abstractrecorddef(def:tabstractrecorddef);
  1892. var
  1893. i : longint;
  1894. hp : tdef;
  1895. hmodule : tmodule;
  1896. begin
  1897. hmodule:=find_module_from_symtable(def.genericdef.owner);
  1898. if hmodule=nil then
  1899. internalerror(201202041);
  1900. for i:=0 to def.symtable.DefList.Count-1 do
  1901. begin
  1902. hp:=tdef(def.symtable.DefList[i]);
  1903. if hp.typ=procdef then
  1904. begin
  1905. { only generate the code if we need a body }
  1906. if assigned(tprocdef(hp).struct) and not tprocdef(hp).forwarddef then
  1907. continue;
  1908. if assigned(tprocdef(hp).genericdef) and
  1909. (tprocdef(hp).genericdef.typ=procdef) and
  1910. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1911. begin
  1912. oldcurrent_filepos:=current_filepos;
  1913. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1914. { use the index the module got from the current compilation process }
  1915. current_filepos.moduleindex:=hmodule.unit_index;
  1916. current_tokenpos:=current_filepos;
  1917. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf,
  1918. tprocdef(tprocdef(hp).genericdef).change_endian);
  1919. read_proc_body(nil,tprocdef(hp));
  1920. current_filepos:=oldcurrent_filepos;
  1921. end
  1922. { synthetic routines will be implemented afterwards }
  1923. else if tprocdef(hp).synthetickind=tsk_none then
  1924. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  1925. end
  1926. else
  1927. if hp.typ in [objectdef,recorddef] then
  1928. { generate code for subtypes as well }
  1929. process_abstractrecorddef(tabstractrecorddef(hp));
  1930. end;
  1931. end;
  1932. begin
  1933. if not((tsym(p).typ=typesym) and
  1934. (ttypesym(p).typedef.typesym=tsym(p)) and
  1935. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  1936. (df_specialization in ttypesym(p).typedef.defoptions)
  1937. ) then
  1938. exit;
  1939. { Setup symtablestack a definition time }
  1940. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  1941. if not (is_class_or_object(specobj) or is_record(specobj) or is_javaclass(specobj)) then
  1942. exit;
  1943. specialization_init(specobj.genericdef,state);
  1944. { procedure definitions for classes or objects }
  1945. process_abstractrecorddef(specobj);
  1946. specialization_done(state);
  1947. end;
  1948. procedure generate_specialization_procs;
  1949. begin
  1950. if assigned(current_module.globalsymtable) then
  1951. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1952. if assigned(current_module.localsymtable) then
  1953. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1954. end;
  1955. end.