psub.pas 123 KB

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