psub.pas 103 KB

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