psub.pas 115 KB

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