psub.pas 93 KB

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