psub.pas 115 KB

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