psub.pas 130 KB

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