psub.pas 127 KB

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