psub.pas 108 KB

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