psub.pas 105 KB

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