psub.pas 89 KB

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