2
0

psub.pas 115 KB

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