psub.pas 103 KB

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