psub.pas 130 KB

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