psub.pas 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052
  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. cclasses,globals,
  22. node,nbas,
  23. symdef,procinfo,optdfa;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  28. procedure add_entry_exit_code;
  29. public
  30. { code for the subroutine as tree }
  31. code : tnode;
  32. { positions in the tree for init/final }
  33. entry_asmnode,
  34. loadpara_asmnode,
  35. exitlabel_asmnode,
  36. stackcheck_asmnode,
  37. init_asmnode,
  38. final_asmnode : tasmnode;
  39. dfabuilder : TDFABuilder;
  40. destructor destroy;override;
  41. procedure printproc(pass:string);
  42. procedure generate_code;
  43. procedure resetprocdef;
  44. procedure add_to_symtablestack;
  45. procedure remove_from_symtablestack;
  46. procedure parse_body;
  47. function has_assembler_child : boolean;
  48. end;
  49. procedure printnode_reset;
  50. { reads the declaration blocks }
  51. procedure read_declarations(islibrary : boolean);
  52. { reads declarations in the interface part of a unit }
  53. procedure read_interface_declarations;
  54. procedure generate_specialization_procs;
  55. implementation
  56. uses
  57. sysutils,
  58. { common }
  59. cutils,
  60. { global }
  61. globtype,tokens,verbose,comphook,constexp,
  62. systems,
  63. { aasm }
  64. cpuinfo,cpubase,aasmbase,aasmtai,aasmdata,
  65. { symtable }
  66. symconst,symbase,symsym,symtype,symtable,defutil,
  67. paramgr,
  68. ppu,fmodule,
  69. { pass 1 }
  70. nutils,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  71. pass_1,
  72. {$ifdef state_tracking}
  73. nstate,
  74. {$endif state_tracking}
  75. { pass 2 }
  76. {$ifndef NOPASS2}
  77. pass_2,
  78. {$endif}
  79. { parser }
  80. scanner,import,gendef,
  81. pbase,pstatmnt,pdecl,pdecsub,pexports,
  82. { codegen }
  83. tgobj,cgbase,cgobj,cgcpu,dbgbase,
  84. ncgutil,regvars,
  85. optbase,
  86. opttail,
  87. optcse,optloop,
  88. optutils
  89. {$if defined(arm) or defined(powerpc) or defined(powerpc64) or defined(avr)}
  90. ,aasmcpu
  91. {$endif arm}
  92. {$ifndef NOOPT}
  93. {$ifdef i386}
  94. ,aopt386
  95. {$else i386}
  96. ,aopt
  97. {$endif i386}
  98. {$endif}
  99. ;
  100. {****************************************************************************
  101. PROCEDURE/FUNCTION BODY PARSING
  102. ****************************************************************************}
  103. procedure initializevars(p:TObject;arg:pointer);
  104. var
  105. b : tblocknode;
  106. begin
  107. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  108. exit;
  109. with tabstractnormalvarsym(p) do
  110. begin
  111. if assigned(defaultconstsym) then
  112. begin
  113. b:=tblocknode(arg);
  114. b.left:=cstatementnode.create(
  115. cassignmentnode.create(
  116. cloadnode.create(tsym(p),tsym(p).owner),
  117. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  118. b.left);
  119. end;
  120. end;
  121. end;
  122. procedure check_finalize_paras(p:TObject;arg:pointer);
  123. begin
  124. if (tsym(p).typ=paravarsym) and
  125. (tparavarsym(p).varspez=vs_value) and
  126. is_managed_type(tparavarsym(p).vardef) then
  127. include(current_procinfo.flags,pi_needs_implicit_finally);
  128. end;
  129. procedure check_finalize_locals(p:TObject;arg:pointer);
  130. begin
  131. { include the result: it needs to be finalized in case an exception }
  132. { occurs }
  133. if (tsym(p).typ=localvarsym) and
  134. (tlocalvarsym(p).refs>0) and
  135. is_managed_type(tlocalvarsym(p).vardef) then
  136. include(current_procinfo.flags,pi_needs_implicit_finally);
  137. end;
  138. function block(islibrary : boolean) : tnode;
  139. var
  140. oldfilepos: tfileposinfo;
  141. begin
  142. { parse const,types and vars }
  143. read_declarations(islibrary);
  144. { do we have an assembler block without the po_assembler?
  145. we should allow this for Delphi compatibility (PFV) }
  146. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  147. include(current_procinfo.procdef.procoptions,po_assembler);
  148. { Handle assembler block different }
  149. if (po_assembler in current_procinfo.procdef.procoptions) then
  150. begin
  151. block:=assembler_block;
  152. exit;
  153. end;
  154. {Unit initialization?.}
  155. if (
  156. assigned(current_procinfo.procdef.localst) and
  157. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  158. (current_module.is_unit or islibrary)
  159. ) then
  160. begin
  161. if (token=_END) then
  162. begin
  163. consume(_END);
  164. { We need at least a node, else the entry/exit code is not
  165. generated and thus no PASCALMAIN symbol which we need (PFV) }
  166. if islibrary then
  167. block:=cnothingnode.create
  168. else
  169. block:=nil;
  170. end
  171. else
  172. begin
  173. if token=_INITIALIZATION then
  174. begin
  175. { The library init code is already called and does not
  176. need to be in the initfinal table (PFV) }
  177. block:=statement_block(_INITIALIZATION);
  178. { optimize empty initialization block away }
  179. if (block.nodetype=blockn) and (tblocknode(block).left=nil) then
  180. FreeAndNil(block)
  181. else
  182. if not islibrary then
  183. current_module.flags:=current_module.flags or uf_init;
  184. end
  185. else if token=_FINALIZATION then
  186. begin
  187. { when a unit has only a finalization section, we can come to this
  188. point when we try to read the nonh existing initalization section
  189. so we've to check if we are really try to parse the finalization }
  190. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  191. begin
  192. block:=statement_block(_FINALIZATION);
  193. { optimize empty finalization block away }
  194. if (block.nodetype=blockn) and (tblocknode(block).left=nil) then
  195. FreeAndNil(block)
  196. else
  197. current_module.flags:=current_module.flags or uf_finalize;
  198. end
  199. else
  200. block:=nil;
  201. end
  202. else
  203. begin
  204. { The library init code is already called and does not
  205. need to be in the initfinal table (PFV) }
  206. if not islibrary then
  207. current_module.flags:=current_module.flags or uf_init;
  208. block:=statement_block(_BEGIN);
  209. end;
  210. end;
  211. end
  212. else
  213. begin
  214. block:=statement_block(_BEGIN);
  215. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  216. begin
  217. { initialization of local variables with their initial
  218. values: part of function entry }
  219. oldfilepos:=current_filepos;
  220. current_filepos:=current_procinfo.entrypos;
  221. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  222. current_filepos:=oldfilepos;
  223. end;
  224. end;
  225. end;
  226. {****************************************************************************
  227. PROCEDURE/FUNCTION COMPILING
  228. ****************************************************************************}
  229. procedure printnode_reset;
  230. begin
  231. assign(printnodefile,treelogfilename);
  232. {$push}{$I-}
  233. rewrite(printnodefile);
  234. {$pop}
  235. if ioresult<>0 then
  236. begin
  237. Comment(V_Error,'Error creating '+treelogfilename);
  238. exit;
  239. end;
  240. close(printnodefile);
  241. end;
  242. procedure add_label_init(p:TObject;arg:pointer);
  243. begin
  244. if tstoredsym(p).typ=labelsym then
  245. begin
  246. addstatement(tstatementnode(arg^),
  247. cifnode.create(caddnode.create(equaln,
  248. ccallnode.createintern('fpc_setjmp',
  249. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  250. cordconstnode.create(1,sinttype,true))
  251. ,cgotonode.create(tlabelsym(p)),nil)
  252. );
  253. end;
  254. end;
  255. function generate_bodyentry_block:tnode;
  256. var
  257. srsym : tsym;
  258. para : tcallparanode;
  259. newstatement : tstatementnode;
  260. begin
  261. result:=internalstatements(newstatement);
  262. if assigned(current_structdef) then
  263. begin
  264. { a constructor needs a help procedure }
  265. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  266. begin
  267. if is_class(current_structdef) then
  268. begin
  269. include(current_procinfo.flags,pi_needs_implicit_finally);
  270. srsym:=search_struct_member(current_structdef,'NEWINSTANCE');
  271. if assigned(srsym) and
  272. (srsym.typ=procsym) then
  273. begin
  274. { if vmt>1 then newinstance }
  275. addstatement(newstatement,cifnode.create(
  276. caddnode.create(gtn,
  277. ctypeconvnode.create_internal(
  278. load_vmt_pointer_node,
  279. voidpointertype),
  280. cpointerconstnode.create(1,voidpointertype)),
  281. cassignmentnode.create(
  282. ctypeconvnode.create_internal(
  283. load_self_pointer_node,
  284. voidpointertype),
  285. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  286. nil));
  287. end
  288. else
  289. internalerror(200305108);
  290. end
  291. else
  292. if is_object(current_structdef) then
  293. begin
  294. { parameter 3 : vmt_offset }
  295. { parameter 2 : address of pointer to vmt,
  296. this is required to allow setting the vmt to -1 to indicate
  297. that memory was allocated }
  298. { parameter 1 : self pointer }
  299. para:=ccallparanode.create(
  300. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  301. ccallparanode.create(
  302. ctypeconvnode.create_internal(
  303. load_vmt_pointer_node,
  304. voidpointertype),
  305. ccallparanode.create(
  306. ctypeconvnode.create_internal(
  307. load_self_pointer_node,
  308. voidpointertype),
  309. nil)));
  310. addstatement(newstatement,cassignmentnode.create(
  311. ctypeconvnode.create_internal(
  312. load_self_pointer_node,
  313. voidpointertype),
  314. ccallnode.createintern('fpc_help_constructor',para)));
  315. end
  316. else
  317. if not is_record(current_structdef) then
  318. internalerror(200305103);
  319. { if self=nil then exit
  320. calling fail instead of exit is useless because
  321. there is nothing to dispose (PFV) }
  322. if is_class_or_object(current_structdef) then
  323. addstatement(newstatement,cifnode.create(
  324. caddnode.create(equaln,
  325. load_self_pointer_node,
  326. cnilnode.create),
  327. cexitnode.create(nil),
  328. nil));
  329. end;
  330. { maybe call BeforeDestruction for classes }
  331. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  332. is_class(current_structdef) then
  333. begin
  334. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  335. if assigned(srsym) and
  336. (srsym.typ=procsym) then
  337. begin
  338. { if vmt>0 then beforedestruction }
  339. addstatement(newstatement,cifnode.create(
  340. caddnode.create(gtn,
  341. ctypeconvnode.create_internal(
  342. load_vmt_pointer_node,ptrsinttype),
  343. ctypeconvnode.create_internal(
  344. cnilnode.create,ptrsinttype)),
  345. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  346. nil));
  347. end
  348. else
  349. internalerror(200305104);
  350. end;
  351. end;
  352. if m_non_local_goto in current_settings.modeswitches then
  353. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  354. end;
  355. function generate_bodyexit_block:tnode;
  356. var
  357. srsym : tsym;
  358. para : tcallparanode;
  359. newstatement : tstatementnode;
  360. oldlocalswitches: tlocalswitches;
  361. begin
  362. result:=internalstatements(newstatement);
  363. if assigned(current_structdef) then
  364. begin
  365. { Don't test self and the vmt here. The reason is that }
  366. { a constructor already checks whether these are valid }
  367. { before. Further, in case of TThread the thread may }
  368. { free the class instance right after AfterConstruction }
  369. { has been called, so it may no longer be valid (JM) }
  370. oldlocalswitches:=current_settings.localswitches;
  371. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  372. { a destructor needs a help procedure }
  373. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  374. begin
  375. if is_class(current_structdef) then
  376. begin
  377. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  378. if assigned(srsym) and
  379. (srsym.typ=procsym) then
  380. begin
  381. { if self<>0 and vmt<>0 then freeinstance }
  382. addstatement(newstatement,cifnode.create(
  383. caddnode.create(andn,
  384. caddnode.create(unequaln,
  385. load_self_pointer_node,
  386. cnilnode.create),
  387. caddnode.create(unequaln,
  388. ctypeconvnode.create(
  389. load_vmt_pointer_node,
  390. voidpointertype),
  391. cpointerconstnode.create(0,voidpointertype))),
  392. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  393. nil));
  394. end
  395. else
  396. internalerror(200305108);
  397. end
  398. else
  399. if is_object(current_structdef) then
  400. begin
  401. { finalize object data, but only if not in inherited call }
  402. if is_managed_type(current_structdef) then
  403. begin
  404. addstatement(newstatement,cifnode.create(
  405. caddnode.create(unequaln,
  406. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  407. cnilnode.create),
  408. finalize_data_node(load_self_node),
  409. nil));
  410. end;
  411. { parameter 3 : vmt_offset }
  412. { parameter 2 : pointer to vmt }
  413. { parameter 1 : self pointer }
  414. para:=ccallparanode.create(
  415. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  416. ccallparanode.create(
  417. ctypeconvnode.create_internal(
  418. load_vmt_pointer_node,
  419. voidpointertype),
  420. ccallparanode.create(
  421. ctypeconvnode.create_internal(
  422. load_self_pointer_node,
  423. voidpointertype),
  424. nil)));
  425. addstatement(newstatement,
  426. ccallnode.createintern('fpc_help_destructor',para));
  427. end
  428. else
  429. internalerror(200305105);
  430. end;
  431. current_settings.localswitches:=oldlocalswitches;
  432. end;
  433. end;
  434. function generate_except_block:tnode;
  435. var
  436. newstatement : tstatementnode;
  437. { safecall handling }
  438. sym: tsym;
  439. argnode: tnode;
  440. begin
  441. generate_except_block:=internalstatements(newstatement);
  442. { a constructor needs call destructor (if available) when it
  443. is not inherited }
  444. if not assigned(current_structdef) or
  445. (current_procinfo.procdef.proctypeoption<>potype_constructor) then
  446. begin
  447. { no constructor }
  448. { must be the return value finalized before reraising the exception? }
  449. if (not is_void(current_procinfo.procdef.returndef)) and
  450. is_managed_type(current_procinfo.procdef.returndef) and
  451. (not paramanager.ret_in_param(current_procinfo.procdef.returndef, current_procinfo.procdef.proccalloption)) and
  452. (not is_class(current_procinfo.procdef.returndef)) then
  453. addstatement(newstatement,finalize_data_node(load_result_node));
  454. {$if defined(x86) or defined(arm)}
  455. { safecall handling }
  456. if (tf_safecall_exceptions in target_info.flags) and
  457. (current_procinfo.procdef.proccalloption=pocall_safecall) then
  458. begin
  459. { create a local hidden variable "safe_result" }
  460. { it will be used in ncgflw unit }
  461. { to set "real" result value for safecall routine }
  462. sym:=tlocalvarsym.create('$safe_result',vs_value,hresultdef,[]);
  463. include(sym.symoptions,sp_internal);
  464. current_procinfo.procdef.localst.insert(sym);
  465. { if safecall is used for a class method we need to call }
  466. { SafecallException virtual method }
  467. { In other case we return E_UNEXPECTED error value }
  468. if is_class(current_procinfo.procdef.struct) then
  469. argnode:=load_self_node
  470. else
  471. argnode:=cnilnode.create;
  472. addstatement(newstatement,cassignmentnode.create(
  473. cloadnode.create(sym,sym.Owner),
  474. ccallnode.createinternres('fpc_safecallhandler',
  475. ccallparanode.create(argnode,nil),hresultdef)));
  476. end;
  477. {$endif}
  478. end;
  479. end;
  480. {****************************************************************************
  481. TCGProcInfo
  482. ****************************************************************************}
  483. destructor tcgprocinfo.destroy;
  484. begin
  485. if assigned(code) then
  486. code.free;
  487. inherited destroy;
  488. end;
  489. procedure tcgprocinfo.printproc(pass:string);
  490. begin
  491. assign(printnodefile,treelogfilename);
  492. {$push}{$I-}
  493. append(printnodefile);
  494. if ioresult<>0 then
  495. rewrite(printnodefile);
  496. {$pop}
  497. if ioresult<>0 then
  498. begin
  499. Comment(V_Error,'Error creating '+treelogfilename);
  500. exit;
  501. end;
  502. writeln(printnodefile);
  503. writeln(printnodefile,'*******************************************************************************');
  504. writeln(printnodefile, pass);
  505. writeln(printnodefile,procdef.fullprocname(false));
  506. writeln(printnodefile,'*******************************************************************************');
  507. printnode(printnodefile,code);
  508. close(printnodefile);
  509. end;
  510. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  511. var
  512. oldlocalswitches: tlocalswitches;
  513. srsym: tsym;
  514. afterconstructionblock,
  515. exceptblock,
  516. newblock: tblocknode;
  517. newstatement: tstatementnode;
  518. pd: tprocdef;
  519. begin
  520. if assigned(current_structdef) and
  521. (current_procinfo.procdef.proctypeoption=potype_constructor) then
  522. begin
  523. { Don't test self and the vmt here. See generate_bodyexit_block }
  524. { why (JM) }
  525. oldlocalswitches:=current_settings.localswitches;
  526. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  527. { call AfterConstruction for classes }
  528. if is_class(current_structdef) then
  529. begin
  530. srsym:=search_struct_member(current_structdef,'AFTERCONSTRUCTION');
  531. if assigned(srsym) and
  532. (srsym.typ=procsym) then
  533. begin
  534. current_filepos:=exitpos;
  535. afterconstructionblock:=internalstatements(newstatement);
  536. { first execute all constructor code. If no exception
  537. occurred then we will execute afterconstruction,
  538. otherwise we won't (the exception will jump over us) }
  539. addstatement(newstatement,tocode);
  540. { Self can be nil when fail is called }
  541. { if self<>nil and vmt<>nil then afterconstruction }
  542. addstatement(newstatement,cifnode.create(
  543. caddnode.create(andn,
  544. caddnode.create(unequaln,
  545. load_self_node,
  546. cnilnode.create),
  547. caddnode.create(unequaln,
  548. load_vmt_pointer_node,
  549. cnilnode.create)),
  550. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  551. nil));
  552. tocode:=afterconstructionblock;
  553. end
  554. else
  555. internalerror(200305106);
  556. end;
  557. if withexceptblock and (current_structdef.typ=objectdef) then
  558. begin
  559. { Generate the implicit "fail" code for a constructor (destroy
  560. in case an exception happened) }
  561. pd:=tobjectdef(current_structdef).find_destructor;
  562. { this will always be the case for classes, since tobject has
  563. a destructor }
  564. if assigned(pd) then
  565. begin
  566. current_filepos:=exitpos;
  567. exceptblock:=internalstatements(newstatement);
  568. { first free the instance if non-nil }
  569. { if vmt<>0 then call destructor }
  570. addstatement(newstatement,cifnode.create(
  571. caddnode.create(unequaln,
  572. load_vmt_pointer_node,
  573. cnilnode.create),
  574. { cnf_create_failed -> don't call BeforeDestruction }
  575. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed]),
  576. nil));
  577. { then re-raise the exception }
  578. addstatement(newstatement,craisenode.create(nil,nil,nil));
  579. current_filepos:=entrypos;
  580. newblock:=internalstatements(newstatement);
  581. { try
  582. tocode
  583. except
  584. exceptblock
  585. end
  586. }
  587. addstatement(newstatement,ctryexceptnode.create(
  588. tocode,
  589. nil,
  590. exceptblock));
  591. tocode:=newblock;
  592. end;
  593. end;
  594. current_settings.localswitches:=oldlocalswitches;
  595. end;
  596. end;
  597. procedure tcgprocinfo.add_entry_exit_code;
  598. var
  599. finalcode,
  600. bodyentrycode,
  601. bodyexitcode,
  602. exceptcode,
  603. wrappedbody: tnode;
  604. newblock : tblocknode;
  605. codestatement,
  606. newstatement : tstatementnode;
  607. oldfilepos : tfileposinfo;
  608. begin
  609. oldfilepos:=current_filepos;
  610. { Generate code/locations used at start of proc }
  611. current_filepos:=entrypos;
  612. entry_asmnode:=casmnode.create_get_position;
  613. loadpara_asmnode:=casmnode.create_get_position;
  614. stackcheck_asmnode:=casmnode.create_get_position;
  615. init_asmnode:=casmnode.create_get_position;
  616. bodyentrycode:=generate_bodyentry_block;
  617. { Generate code/locations used at end of proc }
  618. current_filepos:=exitpos;
  619. exitlabel_asmnode:=casmnode.create_get_position;
  620. final_asmnode:=casmnode.create_get_position;
  621. bodyexitcode:=generate_bodyexit_block;
  622. { Generate procedure by combining init+body+final,
  623. depending on the implicit finally we need to add
  624. an try...finally...end wrapper }
  625. newblock:=internalstatements(newstatement);
  626. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  627. (pi_needs_implicit_finally in flags) and
  628. { but it's useless in init/final code of units }
  629. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  630. not(po_assembler in procdef.procoptions) then
  631. begin
  632. { Generate special exception block only needed when
  633. implicit finaly is used }
  634. current_filepos:=exitpos;
  635. exceptcode:=generate_except_block;
  636. { Generate code that will be in the try...finally }
  637. finalcode:=internalstatements(codestatement);
  638. addstatement(codestatement,final_asmnode);
  639. { Initialize before try...finally...end frame }
  640. addstatement(newstatement,loadpara_asmnode);
  641. addstatement(newstatement,stackcheck_asmnode);
  642. addstatement(newstatement,entry_asmnode);
  643. addstatement(newstatement,init_asmnode);
  644. addstatement(newstatement,bodyentrycode);
  645. current_filepos:=entrypos;
  646. wrappedbody:=ctryfinallynode.create_implicit(
  647. code,
  648. finalcode,
  649. exceptcode);
  650. { afterconstruction must be called after final_asmnode, because it
  651. has to execute after the temps have been finalised in case of a
  652. refcounted class (afterconstruction decreases the refcount
  653. without freeing the instance if the count becomes nil, while
  654. the finalising of the temps can free the instance) }
  655. maybe_add_constructor_wrapper(wrappedbody,true);
  656. addstatement(newstatement,wrappedbody);
  657. addstatement(newstatement,exitlabel_asmnode);
  658. addstatement(newstatement,bodyexitcode);
  659. { set flag the implicit finally has been generated }
  660. include(flags,pi_has_implicit_finally);
  661. end
  662. else
  663. begin
  664. maybe_add_constructor_wrapper(code,false);
  665. addstatement(newstatement,loadpara_asmnode);
  666. addstatement(newstatement,stackcheck_asmnode);
  667. addstatement(newstatement,entry_asmnode);
  668. addstatement(newstatement,init_asmnode);
  669. addstatement(newstatement,bodyentrycode);
  670. addstatement(newstatement,code);
  671. addstatement(newstatement,exitlabel_asmnode);
  672. addstatement(newstatement,bodyexitcode);
  673. addstatement(newstatement,final_asmnode);
  674. end;
  675. do_firstpass(tnode(newblock));
  676. code:=newblock;
  677. current_filepos:=oldfilepos;
  678. end;
  679. procedure clearrefs(p:TObject;arg:pointer);
  680. begin
  681. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  682. if tabstractvarsym(p).refs>1 then
  683. tabstractvarsym(p).refs:=1;
  684. end;
  685. procedure translate_registers(p:TObject;list:pointer);
  686. begin
  687. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  688. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  689. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  690. begin
  691. if not(cs_no_regalloc in current_settings.globalswitches) then
  692. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  693. if cs_asm_source in current_settings.globalswitches then
  694. TAsmList(list).concat(Tai_comment.Create(strpnew('Var '+tabstractnormalvarsym(p).realname+' located in register '+
  695. std_regname(tabstractnormalvarsym(p).localloc.register))))
  696. end;
  697. end;
  698. function tcgprocinfo.has_assembler_child : boolean;
  699. var
  700. hp : tprocinfo;
  701. begin
  702. result:=false;
  703. hp:=get_first_nestedproc;
  704. while assigned(hp) do
  705. begin
  706. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  707. begin
  708. result:=true;
  709. exit;
  710. end;
  711. hp:=tprocinfo(hp.next);
  712. end;
  713. end;
  714. procedure tcgprocinfo.generate_code;
  715. var
  716. old_current_procinfo : tprocinfo;
  717. oldmaxfpuregisters : longint;
  718. oldfilepos : tfileposinfo;
  719. old_current_structdef : tabstractrecorddef;
  720. templist : TAsmList;
  721. headertai : tai;
  722. i : integer;
  723. varsym : tabstractnormalvarsym;
  724. {RedoDFA : boolean;}
  725. begin
  726. { the initialization procedure can be empty, then we
  727. don't need to generate anything. When it was an empty
  728. procedure there would be at least a blocknode }
  729. if not assigned(code) then
  730. exit;
  731. { We need valid code }
  732. if Errorcount<>0 then
  733. exit;
  734. { No code can be generated for generic template }
  735. if (df_generic in procdef.defoptions) then
  736. internalerror(200511152);
  737. { The RA and Tempgen shall not be available yet }
  738. if assigned(tg) then
  739. internalerror(200309201);
  740. old_current_procinfo:=current_procinfo;
  741. oldfilepos:=current_filepos;
  742. old_current_structdef:=current_structdef;
  743. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  744. current_procinfo:=self;
  745. current_filepos:=entrypos;
  746. current_structdef:=procdef.struct;
  747. templist:=TAsmList.create;
  748. { add parast/localst to symtablestack }
  749. add_to_symtablestack;
  750. { clear register count }
  751. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  752. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  753. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  754. if (procdef.localst.symtablelevel=main_program_level) and
  755. (not current_module.is_unit) then
  756. include(flags,pi_do_call);
  757. { set implicit_finally flag when there are locals/paras to be finalized }
  758. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  759. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  760. {$if defined(x86) or defined(arm)}
  761. { set implicit_finally flag for if procedure is safecall }
  762. if (tf_safecall_exceptions in target_info.flags) and
  763. (procdef.proccalloption=pocall_safecall) then
  764. include(flags, pi_needs_implicit_finally);
  765. {$endif}
  766. { firstpass everything }
  767. flowcontrol:=[];
  768. do_firstpass(code);
  769. {$ifdef i386}
  770. procdef.fpu_used:=node_resources_fpu(code);
  771. if procdef.fpu_used>0 then
  772. include(flags,pi_uses_fpu);
  773. {$endif i386}
  774. { Print the node to tree.log }
  775. if paraprintnodetree=1 then
  776. printproc( 'after the firstpass');
  777. { do this before adding the entry code else the tail recursion recognition won't work,
  778. if this causes troubles, it must be if'ed
  779. }
  780. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  781. (pi_is_recursive in flags) then
  782. do_opttail(code,procdef);
  783. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  784. { creating dfa is not always possible }
  785. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  786. pi_needs_implicit_finally,pi_has_implicit_finally])=[]) then
  787. begin
  788. dfabuilder:=TDFABuilder.Create;
  789. dfabuilder.createdfainfo(code);
  790. { when life info is available, we can give more sophisticated warning about unintialized
  791. variables }
  792. { iterate through life info of the first node }
  793. for i:=0 to dfabuilder.nodemap.count-1 do
  794. begin
  795. if DFASetIn(code.optinfo^.life,i) then
  796. case tnode(dfabuilder.nodemap[i]).nodetype of
  797. loadn:
  798. begin
  799. varsym:=tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry);
  800. { Give warning/note for living locals }
  801. if assigned(varsym.owner) and
  802. not(vo_is_external in varsym.varoptions) then
  803. begin
  804. if (vo_is_funcret in varsym.varoptions) then
  805. CGMessage(sym_w_function_result_uninitialized)
  806. else
  807. begin
  808. if (varsym.owner=procdef.localst) and not (vo_is_typed_const in varsym.varoptions) then
  809. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  810. end;
  811. end;
  812. end;
  813. end;
  814. end;
  815. include(flags,pi_dfaavailable);
  816. end;
  817. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  818. { our induction variable strength reduction doesn't like
  819. for loops with more than one entry }
  820. and not(pi_has_label in current_procinfo.flags) then
  821. begin
  822. {RedoDFA:=}OptimizeInductionVariables(code);
  823. end;
  824. if cs_opt_nodecse in current_settings.optimizerswitches then
  825. do_optcse(code);
  826. { add implicit entry and exit code }
  827. add_entry_exit_code;
  828. { only do secondpass if there are no errors }
  829. if (ErrorCount=0) then
  830. begin
  831. create_codegen;
  832. { set the start offset to the start of the temp area in the stack }
  833. tg:=ttgobj.create;
  834. {$if defined(x86) or defined(arm)}
  835. { try to strip the stack frame }
  836. { set the framepointer to esp if:
  837. - no assembler directive, those are handled in assembler_block
  838. in pstatment.pas (for cases not caught by the Delphi
  839. exception below)
  840. - no exceptions are used
  841. - no pushes are used/esp modifications, could be:
  842. * outgoing parameters on the stack
  843. * incoming parameters on the stack
  844. * open arrays
  845. - no inline assembler
  846. or
  847. - Delphi mode
  848. - assembler directive
  849. - no pushes are used/esp modifications, could be:
  850. * outgoing parameters on the stack
  851. * incoming parameters on the stack
  852. * open arrays
  853. - no local variables
  854. }
  855. if ((po_assembler in procdef.procoptions) and
  856. (m_delphi in current_settings.modeswitches) and
  857. { localst at main_program_level is a staticsymtable }
  858. (procdef.localst.symtablelevel<>main_program_level) and
  859. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  860. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  861. not(cs_generate_stackframes in current_settings.localswitches) and
  862. not(po_assembler in procdef.procoptions) and
  863. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  864. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  865. pi_needs_stackframe])=[])
  866. )
  867. then
  868. begin
  869. { we need the parameter info here to determine if the procedure gets
  870. parameters on the stack
  871. calling generate_parameter_info doesn't hurt but it costs time
  872. (necessary to init para_stack_size)
  873. }
  874. generate_parameter_info;
  875. if not(procdef.stack_tainting_parameter(calleeside)) and
  876. not(has_assembler_child) and (para_stack_size=0) then
  877. begin
  878. { Only need to set the framepointer }
  879. framepointer:=NR_STACK_POINTER_REG;
  880. tg.direction:=1;
  881. end;
  882. end;
  883. {$endif}
  884. { Create register allocator }
  885. cg.init_register_allocators;
  886. set_first_temp_offset;
  887. generate_parameter_info;
  888. { allocate got register if needed }
  889. current_procinfo.allocate_got_register(aktproccode);
  890. { Allocate space in temp/registers for parast and localst }
  891. current_filepos:=entrypos;
  892. gen_alloc_symtable(aktproccode,procdef.parast);
  893. gen_alloc_symtable(aktproccode,procdef.localst);
  894. { Store temp offset for information about 'real' temps }
  895. tempstart:=tg.lasttemp;
  896. { Generate code to load register parameters in temps and insert local
  897. copies for values parameters. This must be done before the code for the
  898. body is generated because the localloc is updated.
  899. Note: The generated code will be inserted after the code generation of
  900. the body is finished, because only then the position is known }
  901. {$ifdef oldregvars}
  902. assign_regvars(code);
  903. {$endif oldreg}
  904. current_filepos:=entrypos;
  905. gen_load_para_value(templist);
  906. { caller paraloc info is also necessary in the stackframe_entry
  907. code of the ppc (and possibly other processors) }
  908. procdef.init_paraloc_info(callerside);
  909. { generate code for the node tree }
  910. do_secondpass(code);
  911. aktproccode.concatlist(current_asmdata.CurrAsmList);
  912. { The position of the loadpara_asmnode is now known }
  913. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  914. { first generate entry and initialize code with the correct
  915. position and switches }
  916. current_filepos:=entrypos;
  917. current_settings.localswitches:=entryswitches;
  918. cg.set_regalloc_live_range_direction(rad_backwards);
  919. gen_entry_code(templist);
  920. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  921. gen_initialize_code(templist);
  922. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  923. { now generate finalize and exit code with the correct position
  924. and switches }
  925. current_filepos:=exitpos;
  926. current_settings.localswitches:=exitswitches;
  927. cg.set_regalloc_live_range_direction(rad_forward);
  928. gen_finalize_code(templist);
  929. { the finalcode must be concated if there was no position available,
  930. using insertlistafter will result in an insert at the start
  931. when currentai=nil }
  932. if assigned(final_asmnode.currenttai) then
  933. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  934. else
  935. aktproccode.concatlist(templist);
  936. { insert exit label at the correct position }
  937. cg.a_label(templist,CurrExitLabel);
  938. if assigned(exitlabel_asmnode.currenttai) then
  939. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  940. else
  941. aktproccode.concatlist(templist);
  942. { exit code }
  943. gen_exit_code(templist);
  944. aktproccode.concatlist(templist);
  945. {$ifdef OLDREGVARS}
  946. { note: this must be done only after as much code as possible has }
  947. { been generated. The result is that when you ungetregister() a }
  948. { regvar, it will actually free the regvar (and alse free the }
  949. { the regvars at the same time). Doing this too early will }
  950. { confuse the register allocator, as the regvars will still be }
  951. { used. It should be done before loading the result regs (so }
  952. { they don't conflict with the regvars) and before }
  953. { gen_entry_code (that one has to be able to allocate the }
  954. { regvars again) (JM) }
  955. free_regvars(aktproccode);
  956. {$endif OLDREGVARS}
  957. { generate symbol and save end of header position }
  958. current_filepos:=entrypos;
  959. gen_proc_symbol(templist);
  960. headertai:=tai(templist.last);
  961. { insert symbol }
  962. aktproccode.insertlist(templist);
  963. { Free space in temp/registers for parast and localst, must be
  964. done after gen_entry_code }
  965. current_filepos:=exitpos;
  966. { make sure the got/pic register doesn't get freed in the }
  967. { middle of a loop }
  968. if (cs_create_pic in current_settings.moduleswitches) and
  969. (pi_needs_got in current_procinfo.flags) and
  970. (current_procinfo.got<>NR_NO) then
  971. cg.a_reg_sync(aktproccode,current_procinfo.got);
  972. gen_free_symtable(aktproccode,procdef.localst);
  973. gen_free_symtable(aktproccode,procdef.parast);
  974. { add code that will load the return value, this is not done
  975. for assembler routines when they didn't reference the result
  976. variable }
  977. gen_load_return_value(templist);
  978. aktproccode.concatlist(templist);
  979. { Already reserve all registers for stack checking code and
  980. generate the call to the helper function }
  981. if not(tf_no_generic_stackcheck in target_info.flags) and
  982. (cs_check_stack in entryswitches) and
  983. not(po_assembler in procdef.procoptions) and
  984. (procdef.proctypeoption<>potype_proginit) then
  985. begin
  986. current_filepos:=entrypos;
  987. gen_stack_check_call(templist);
  988. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  989. end;
  990. { this code (got loading) comes before everything which has }
  991. { already been generated, so reset the info about already }
  992. { backwards extended registers (so their live range can be }
  993. { extended backwards even further if needed) }
  994. { This code must be }
  995. { a) generated after do_secondpass has been called }
  996. { (because pi_needs_got may be set there) }
  997. { b) generated before register allocation, because the }
  998. { got/pic register can be a virtual one }
  999. { c) inserted before the entry code, because the entry }
  1000. { code may need global symbols such as init rtti }
  1001. { d) inserted after the stackframe allocation, because }
  1002. { this register may have to be spilled }
  1003. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1004. current_filepos:=entrypos;
  1005. { load got if necessary }
  1006. cg.g_maybe_got_init(templist);
  1007. aktproccode.insertlistafter(headertai,templist);
  1008. { re-enable if more code at the end is ever generated here
  1009. cg.set_regalloc_live_range_direction(rad_forward);
  1010. }
  1011. { The procedure body is finished, we can now
  1012. allocate the registers }
  1013. cg.do_register_allocation(aktproccode,headertai);
  1014. { translate imag. register to their real counter parts
  1015. this is necessary for debuginfo and verbose assembler output
  1016. when SSA will be implented, this will be more complicated because we've to
  1017. maintain location lists }
  1018. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1019. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1020. if (cs_create_pic in current_settings.moduleswitches) and
  1021. (pi_needs_got in current_procinfo.flags) and
  1022. not(cs_no_regalloc in current_settings.globalswitches) and
  1023. (current_procinfo.got<>NR_NO) then
  1024. cg.translate_register(current_procinfo.got);
  1025. { Add save and restore of used registers }
  1026. current_filepos:=entrypos;
  1027. gen_save_used_regs(templist);
  1028. { Remember the last instruction of register saving block
  1029. (may be =nil for e.g. assembler procedures) }
  1030. current_procinfo.endprologue_ai:=templist.last;
  1031. aktproccode.insertlistafter(headertai,templist);
  1032. current_filepos:=exitpos;
  1033. gen_restore_used_regs(aktproccode);
  1034. { We know the size of the stack, now we can generate the
  1035. parameter that is passed to the stack checking code }
  1036. if not(tf_no_generic_stackcheck in target_info.flags) and
  1037. (cs_check_stack in entryswitches) and
  1038. not(po_assembler in procdef.procoptions) and
  1039. (procdef.proctypeoption<>potype_proginit) then
  1040. begin
  1041. current_filepos:=entrypos;
  1042. gen_stack_check_size_para(templist);
  1043. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1044. end;
  1045. { Add entry code (stack allocation) after header }
  1046. current_filepos:=entrypos;
  1047. gen_proc_entry_code(templist);
  1048. aktproccode.insertlistafter(headertai,templist);
  1049. {$if defined(x86) or defined(arm)}
  1050. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1051. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1052. (tf_safecall_exceptions in target_info.flags) and
  1053. (procdef.proccalloption=pocall_safecall) then
  1054. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1055. {$endif}
  1056. { Add exit code at the end }
  1057. current_filepos:=exitpos;
  1058. gen_proc_exit_code(templist);
  1059. aktproccode.concatlist(templist);
  1060. { check if the implicit finally has been generated. The flag
  1061. should already be set in pass1 }
  1062. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1063. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1064. (pi_needs_implicit_finally in flags) and
  1065. not(po_assembler in procdef.procoptions) and
  1066. not(pi_has_implicit_finally in flags) then
  1067. internalerror(200405231);
  1068. {$ifndef NoOpt}
  1069. if not(cs_no_regalloc in current_settings.globalswitches) then
  1070. begin
  1071. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1072. { do not optimize pure assembler procedures }
  1073. not(pi_is_assembler in flags) then
  1074. optimize(aktproccode);
  1075. end;
  1076. {$endif NoOpt}
  1077. {$ifdef ARM}
  1078. { because of the limited constant size of the arm, all data access is done pc relative }
  1079. finalizearmcode(aktproccode,aktlocaldata);
  1080. {$endif ARM}
  1081. {$ifdef AVR}
  1082. { because of the limited branch distance of cond. branches, they must be replaced
  1083. somtimes by normal jmps and an inverse branch }
  1084. finalizeavrcode(aktproccode);
  1085. {$endif AVR}
  1086. { Add end symbol and debug info }
  1087. { this must be done after the pcrelativedata is appended else the distance calculation of
  1088. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1089. so it should be inserted before the end symbol (FK)
  1090. }
  1091. current_filepos:=exitpos;
  1092. gen_proc_symbol_end(templist);
  1093. aktproccode.concatlist(templist);
  1094. {$if defined(POWERPC) or defined(POWERPC64)}
  1095. fixup_jmps(aktproccode);
  1096. {$endif}
  1097. { insert line debuginfo }
  1098. if (cs_debuginfo in current_settings.moduleswitches) or
  1099. (cs_use_lineinfo in current_settings.globalswitches) then
  1100. current_debuginfo.insertlineinfo(aktproccode);
  1101. { add the procedure to the al_procedures }
  1102. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  1103. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  1104. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  1105. { save local data (casetable) also in the same file }
  1106. if assigned(aktlocaldata) and
  1107. (not aktlocaldata.empty) then
  1108. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  1109. { only now we can remove the temps }
  1110. tg.resettempgen;
  1111. { stop tempgen and ra }
  1112. tg.free;
  1113. cg.done_register_allocators;
  1114. destroy_codegen;
  1115. tg:=nil;
  1116. end;
  1117. dfabuilder.free;
  1118. { restore symtablestack }
  1119. remove_from_symtablestack;
  1120. { restore }
  1121. templist.free;
  1122. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1123. current_filepos:=oldfilepos;
  1124. current_structdef:=old_current_structdef;
  1125. current_procinfo:=old_current_procinfo;
  1126. end;
  1127. procedure tcgprocinfo.add_to_symtablestack;
  1128. begin
  1129. { insert symtables for the class, but only if it is no nested function }
  1130. if assigned(procdef.struct) and
  1131. not(assigned(parent) and
  1132. assigned(parent.procdef) and
  1133. assigned(parent.procdef.struct)) then
  1134. push_nested_hierarchy(procdef.struct);
  1135. { insert parasymtable in symtablestack when parsing
  1136. a function }
  1137. if procdef.parast.symtablelevel>=normal_function_level then
  1138. symtablestack.push(procdef.parast);
  1139. { insert localsymtable, except for the main procedure
  1140. (in that case the localst is the unit's static symtable,
  1141. which is already on the stack) }
  1142. if procdef.localst.symtablelevel>=normal_function_level then
  1143. symtablestack.push(procdef.localst);
  1144. end;
  1145. procedure tcgprocinfo.remove_from_symtablestack;
  1146. begin
  1147. { remove localsymtable }
  1148. if procdef.localst.symtablelevel>=normal_function_level then
  1149. symtablestack.pop(procdef.localst);
  1150. { remove parasymtable }
  1151. if procdef.parast.symtablelevel>=normal_function_level then
  1152. symtablestack.pop(procdef.parast);
  1153. { remove symtables for the class, but only if it is no nested function }
  1154. if assigned(procdef.struct) and
  1155. not(assigned(parent) and
  1156. assigned(parent.procdef) and
  1157. assigned(parent.procdef.struct)) then
  1158. pop_nested_hierarchy(procdef.struct);
  1159. end;
  1160. procedure tcgprocinfo.resetprocdef;
  1161. begin
  1162. { remove code tree, if not inline procedure }
  1163. if assigned(code) then
  1164. begin
  1165. { the inline procedure has already got a copy of the tree
  1166. stored in procdef.inlininginfo }
  1167. code.free;
  1168. code:=nil;
  1169. end;
  1170. end;
  1171. function checknodeinlining(procdef: tprocdef): boolean;
  1172. var
  1173. i : integer;
  1174. currpara : tparavarsym;
  1175. begin
  1176. result := false;
  1177. if (pi_has_assembler_block in current_procinfo.flags) then
  1178. begin
  1179. Message1(parser_w_not_supported_for_inline,'assembler');
  1180. Message(parser_w_inlining_disabled);
  1181. exit;
  1182. end;
  1183. for i:=0 to procdef.paras.count-1 do
  1184. begin
  1185. currpara:=tparavarsym(procdef.paras[i]);
  1186. case currpara.vardef.typ of
  1187. formaldef :
  1188. begin
  1189. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  1190. begin
  1191. Message1(parser_w_not_supported_for_inline,'formal parameter');
  1192. Message(parser_w_inlining_disabled);
  1193. exit;
  1194. end;
  1195. end;
  1196. arraydef :
  1197. begin
  1198. if is_array_of_const(currpara.vardef) or
  1199. is_variant_array(currpara.vardef) then
  1200. begin
  1201. Message1(parser_w_not_supported_for_inline,'array of const');
  1202. Message(parser_w_inlining_disabled);
  1203. exit;
  1204. end;
  1205. { open arrays might need re-basing of the index, i.e. if you pass
  1206. an array[1..10] as open array, you have to add 1 to all index operations
  1207. if you directly inline it }
  1208. if is_open_array(currpara.vardef) then
  1209. begin
  1210. Message1(parser_w_not_supported_for_inline,'open array');
  1211. Message(parser_w_inlining_disabled);
  1212. exit;
  1213. end;
  1214. end;
  1215. end;
  1216. end;
  1217. result:=true;
  1218. end;
  1219. procedure tcgprocinfo.parse_body;
  1220. var
  1221. old_current_procinfo : tprocinfo;
  1222. old_block_type : tblock_type;
  1223. st : TSymtable;
  1224. old_current_structdef: tabstractrecorddef;
  1225. old_current_genericdef,
  1226. old_current_specializedef: tstoreddef;
  1227. begin
  1228. old_current_procinfo:=current_procinfo;
  1229. old_block_type:=block_type;
  1230. old_current_structdef:=current_structdef;
  1231. old_current_genericdef:=current_genericdef;
  1232. old_current_specializedef:=current_specializedef;
  1233. current_procinfo:=self;
  1234. current_structdef:=procdef.struct;
  1235. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1236. current_genericdef:=current_structdef;
  1237. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1238. current_specializedef:=current_structdef;
  1239. { calculate the lexical level }
  1240. if procdef.parast.symtablelevel>maxnesting then
  1241. Message(parser_e_too_much_lexlevel);
  1242. block_type:=bt_body;
  1243. {$ifdef state_tracking}
  1244. { aktstate:=Tstate_storage.create;}
  1245. {$endif state_tracking}
  1246. { allocate the symbol for this procedure }
  1247. alloc_proc_symbol(procdef);
  1248. { add parast/localst to symtablestack }
  1249. add_to_symtablestack;
  1250. { save entry info }
  1251. entrypos:=current_filepos;
  1252. entryswitches:=current_settings.localswitches;
  1253. if (df_generic in procdef.defoptions) then
  1254. begin
  1255. { start token recorder for generic template }
  1256. procdef.initgeneric;
  1257. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1258. end;
  1259. { parse the code ... }
  1260. code:=block(current_module.islibrary);
  1261. if (df_generic in procdef.defoptions) then
  1262. begin
  1263. { stop token recorder for generic template }
  1264. current_scanner.stoprecordtokens;
  1265. { Give an error for accesses in the static symtable that aren't visible
  1266. outside the current unit }
  1267. st:=procdef.owner;
  1268. while (st.symtabletype=ObjectSymtable) do
  1269. st:=st.defowner.owner;
  1270. if (pi_uses_static_symtable in flags) and
  1271. (st.symtabletype<>staticsymtable) then
  1272. Comment(V_Error,'Global Generic template references static symtable');
  1273. end;
  1274. { save exit info }
  1275. exitswitches:=current_settings.localswitches;
  1276. exitpos:=last_endtoken_filepos;
  1277. { the procedure is now defined }
  1278. procdef.forwarddef:=false;
  1279. if assigned(code) then
  1280. begin
  1281. { get a better entry point }
  1282. entrypos:=code.fileinfo;
  1283. { Finish type checking pass }
  1284. do_typecheckpass(code);
  1285. end;
  1286. { Check for unused labels, forwards, symbols for procedures. Static
  1287. symtable is checked in pmodules.
  1288. The check must be done after the typecheckpass }
  1289. if (Errorcount=0) and
  1290. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1291. begin
  1292. { check if forwards are resolved }
  1293. tstoredsymtable(procdef.localst).check_forwards;
  1294. { check if all labels are used }
  1295. tstoredsymtable(procdef.localst).checklabels;
  1296. { check for unused symbols, but only if there is no asm block }
  1297. if not(pi_has_assembler_block in flags) then
  1298. begin
  1299. tstoredsymtable(procdef.localst).allsymbolsused;
  1300. tstoredsymtable(procdef.parast).allsymbolsused;
  1301. end;
  1302. end;
  1303. if (po_inline in procdef.procoptions) then
  1304. begin
  1305. { Can we inline this procedure? }
  1306. if checknodeinlining(procdef) then
  1307. begin
  1308. new(procdef.inlininginfo);
  1309. include(procdef.procoptions,po_has_inlininginfo);
  1310. procdef.inlininginfo^.code:=code.getcopy;
  1311. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1312. { The blocknode needs to set an exit label }
  1313. if procdef.inlininginfo^.code.nodetype=blockn then
  1314. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1315. end;
  1316. end;
  1317. { Print the node to tree.log }
  1318. if paraprintnodetree=1 then
  1319. printproc( 'after parsing');
  1320. { ... remove symbol tables }
  1321. remove_from_symtablestack;
  1322. {$ifdef state_tracking}
  1323. { aktstate.destroy;}
  1324. {$endif state_tracking}
  1325. current_structdef:=old_current_structdef;
  1326. current_genericdef:=old_current_genericdef;
  1327. current_specializedef:=old_current_specializedef;
  1328. current_procinfo:=old_current_procinfo;
  1329. { Restore old state }
  1330. block_type:=old_block_type;
  1331. end;
  1332. {****************************************************************************
  1333. PROCEDURE/FUNCTION PARSING
  1334. ****************************************************************************}
  1335. procedure check_init_paras(p:TObject;arg:pointer);
  1336. begin
  1337. if tsym(p).typ<>paravarsym then
  1338. exit;
  1339. with tparavarsym(p) do
  1340. if is_managed_type(vardef) and
  1341. (varspez in [vs_value,vs_out]) then
  1342. include(current_procinfo.flags,pi_do_call);
  1343. end;
  1344. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1345. {
  1346. Parses the procedure directives, then parses the procedure body, then
  1347. generates the code for it
  1348. }
  1349. procedure do_generate_code(pi:tcgprocinfo);
  1350. var
  1351. hpi : tcgprocinfo;
  1352. begin
  1353. { generate code for this procedure }
  1354. pi.generate_code;
  1355. { process nested procs }
  1356. hpi:=tcgprocinfo(pi.get_first_nestedproc);
  1357. while assigned(hpi) do
  1358. begin
  1359. do_generate_code(hpi);
  1360. hpi:=tcgprocinfo(hpi.next);
  1361. end;
  1362. pi.resetprocdef;
  1363. end;
  1364. var
  1365. oldfailtokenmode : tmodeswitch;
  1366. isnestedproc : boolean;
  1367. begin
  1368. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1369. { create a new procedure }
  1370. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1371. current_module.procinfo:=current_procinfo;
  1372. current_procinfo.procdef:=pd;
  1373. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1374. { Insert mangledname }
  1375. pd.aliasnames.insert(pd.mangledname);
  1376. { Handle Export of this procedure }
  1377. if (po_exports in pd.procoptions) and
  1378. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1379. begin
  1380. pd.aliasnames.insert(pd.procsym.realname);
  1381. if cs_link_deffile in current_settings.globalswitches then
  1382. deffile.AddExport(pd.mangledname);
  1383. end;
  1384. { Insert result variables in the localst }
  1385. insert_funcret_local(pd);
  1386. { check if there are para's which require initing -> set }
  1387. { pi_do_call (if not yet set) }
  1388. if not(pi_do_call in current_procinfo.flags) then
  1389. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1390. { set _FAIL as keyword if constructor }
  1391. if (pd.proctypeoption=potype_constructor) then
  1392. begin
  1393. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1394. tokeninfo^[_FAIL].keyword:=m_all;
  1395. end;
  1396. tcgprocinfo(current_procinfo).parse_body;
  1397. { We can't support inlining for procedures that have nested
  1398. procedures because the nested procedures use a fixed offset
  1399. for accessing locals in the parent procedure (PFV) }
  1400. if current_procinfo.has_nestedprocs then
  1401. begin
  1402. if (df_generic in current_procinfo.procdef.defoptions) then
  1403. Comment(V_Error,'Generic methods cannot have nested procedures')
  1404. else
  1405. if (po_inline in current_procinfo.procdef.procoptions) then
  1406. begin
  1407. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1408. Message(parser_w_inlining_disabled);
  1409. exclude(current_procinfo.procdef.procoptions,po_inline);
  1410. end;
  1411. end;
  1412. { When it's a nested procedure then defer the code generation,
  1413. when back at normal function level then generate the code
  1414. for all defered nested procedures and the current procedure }
  1415. if not isnestedproc then
  1416. begin
  1417. if not(df_generic in current_procinfo.procdef.defoptions) then
  1418. do_generate_code(tcgprocinfo(current_procinfo));
  1419. end;
  1420. { reset _FAIL as _SELF normal }
  1421. if (pd.proctypeoption=potype_constructor) then
  1422. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1423. { release procinfo }
  1424. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1425. internalerror(200304274);
  1426. current_module.procinfo:=current_procinfo.parent;
  1427. { For specialization we didn't record the last semicolon. Moving this parsing
  1428. into the parse_body routine is not done because of having better file position
  1429. information available }
  1430. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1431. consume(_SEMICOLON);
  1432. if not isnestedproc then
  1433. { current_procinfo is checked for nil later on }
  1434. freeandnil(current_procinfo);
  1435. end;
  1436. procedure read_proc(isclassmethod:boolean);
  1437. {
  1438. Parses the procedure directives, then parses the procedure body, then
  1439. generates the code for it
  1440. }
  1441. var
  1442. old_current_procinfo : tprocinfo;
  1443. old_current_structdef: tabstractrecorddef;
  1444. old_current_genericdef,
  1445. old_current_specializedef: tstoreddef;
  1446. pdflags : tpdflags;
  1447. pd,firstpd : tprocdef;
  1448. s : string;
  1449. begin
  1450. { save old state }
  1451. old_current_procinfo:=current_procinfo;
  1452. old_current_structdef:=current_structdef;
  1453. old_current_genericdef:=current_genericdef;
  1454. old_current_specializedef:=current_specializedef;
  1455. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1456. to another procdef }
  1457. current_procinfo:=nil;
  1458. current_structdef:=nil;
  1459. current_genericdef:=nil;
  1460. current_specializedef:=nil;
  1461. { parse procedure declaration }
  1462. pd:=parse_proc_dec(isclassmethod,old_current_structdef);
  1463. { set the default function options }
  1464. if parse_only then
  1465. begin
  1466. pd.forwarddef:=true;
  1467. { set also the interface flag, for better error message when the
  1468. implementation doesn't much this header }
  1469. pd.interfacedef:=true;
  1470. include(pd.procoptions,po_global);
  1471. pdflags:=[pd_interface];
  1472. end
  1473. else
  1474. begin
  1475. pdflags:=[pd_body];
  1476. if (not current_module.in_interface) then
  1477. include(pdflags,pd_implemen);
  1478. if (not current_module.is_unit) or
  1479. create_smartlink or
  1480. {
  1481. taking addresses of static procedures goes wrong
  1482. if they aren't global when pic is used (FK)
  1483. }
  1484. (cs_create_pic in current_settings.moduleswitches) then
  1485. include(pd.procoptions,po_global);
  1486. pd.forwarddef:=false;
  1487. end;
  1488. { parse the directives that may follow }
  1489. parse_proc_directives(pd,pdflags);
  1490. { hint directives, these can be separated by semicolons here,
  1491. that needs to be handled here with a loop (PFV) }
  1492. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1493. Consume(_SEMICOLON);
  1494. { Set calling convention }
  1495. handle_calling_convention(pd);
  1496. { search for forward declarations }
  1497. if not proc_add_definition(pd) then
  1498. begin
  1499. { A method must be forward defined (in the object declaration) }
  1500. if assigned(pd.struct) and
  1501. (not assigned(old_current_structdef)) then
  1502. begin
  1503. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1504. tprocsym(pd.procsym).write_parameter_lists(pd);
  1505. end
  1506. else
  1507. begin
  1508. { Give a better error if there is a forward def in the interface and only
  1509. a single implementation }
  1510. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1511. if (not pd.forwarddef) and
  1512. (not pd.interfacedef) and
  1513. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1514. firstpd.forwarddef and
  1515. firstpd.interfacedef and
  1516. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1517. { don't give an error if it may be an overload }
  1518. not(m_fpc in current_settings.modeswitches) and
  1519. (not(po_overload in pd.procoptions) or
  1520. not(po_overload in firstpd.procoptions)) then
  1521. begin
  1522. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1523. tprocsym(pd.procsym).write_parameter_lists(pd);
  1524. end;
  1525. end;
  1526. end;
  1527. { Set mangled name }
  1528. proc_set_mangledname(pd);
  1529. { compile procedure when a body is needed }
  1530. if (pd_body in pdflags) then
  1531. begin
  1532. read_proc_body(old_current_procinfo,pd);
  1533. end
  1534. else
  1535. begin
  1536. { Handle imports }
  1537. if (po_external in pd.procoptions) then
  1538. begin
  1539. { External declared in implementation, and there was already a
  1540. forward (or interface) declaration then we need to generate
  1541. a stub that calls the external routine }
  1542. if (not pd.forwarddef) and
  1543. (pd.hasforward)
  1544. { it is unclear to me what's the use of the following condition,
  1545. so commented out, see also issue #18371 (FK)
  1546. and
  1547. not(
  1548. assigned(pd.import_dll) and
  1549. (target_info.system in [system_i386_wdosx,
  1550. system_arm_wince,system_i386_wince])
  1551. ) } then
  1552. begin
  1553. s:=proc_get_importname(pd);
  1554. if s<>'' then
  1555. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1556. end;
  1557. { Import DLL specified? }
  1558. if assigned(pd.import_dll) then
  1559. begin
  1560. if assigned (pd.import_name) then
  1561. current_module.AddExternalImport(pd.import_dll^,
  1562. pd.import_name^,proc_get_importname(pd),
  1563. pd.import_nr,false,false)
  1564. else
  1565. current_module.AddExternalImport(pd.import_dll^,
  1566. proc_get_importname(pd),proc_get_importname(pd),
  1567. pd.import_nr,false,true);
  1568. end
  1569. else
  1570. begin
  1571. { add import name to external list for DLL scanning }
  1572. if tf_has_dllscanner in target_info.flags then
  1573. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1574. end;
  1575. end;
  1576. end;
  1577. { make sure that references to forward-declared functions are not }
  1578. { treated as references to external symbols, needed for darwin. }
  1579. { make sure we don't change the binding of real external symbols }
  1580. if not(po_external in pd.procoptions) then
  1581. begin
  1582. if (po_global in pd.procoptions) or
  1583. (cs_profile in current_settings.moduleswitches) then
  1584. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1585. else
  1586. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1587. end;
  1588. current_structdef:=old_current_structdef;
  1589. current_genericdef:=old_current_genericdef;
  1590. current_specializedef:=old_current_specializedef;
  1591. current_procinfo:=old_current_procinfo;
  1592. end;
  1593. {****************************************************************************
  1594. DECLARATION PARSING
  1595. ****************************************************************************}
  1596. { search in symtablestack for not complete classes }
  1597. procedure check_forward_class(p:TObject;arg:pointer);
  1598. begin
  1599. if (tsym(p).typ=typesym) and
  1600. (ttypesym(p).typedef.typ=objectdef) and
  1601. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1602. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1603. end;
  1604. procedure read_declarations(islibrary : boolean);
  1605. var
  1606. is_classdef:boolean;
  1607. begin
  1608. is_classdef:=false;
  1609. repeat
  1610. if not assigned(current_procinfo) then
  1611. internalerror(200304251);
  1612. case token of
  1613. _LABEL:
  1614. label_dec;
  1615. _CONST:
  1616. const_dec;
  1617. _TYPE:
  1618. type_dec;
  1619. _VAR:
  1620. var_dec;
  1621. _THREADVAR:
  1622. threadvar_dec;
  1623. _CLASS:
  1624. begin
  1625. is_classdef:=false;
  1626. if try_to_consume(_CLASS) then
  1627. begin
  1628. { class modifier is only allowed for procedures, functions, }
  1629. { constructors, destructors, fields and properties }
  1630. if not(token in [_FUNCTION,_PROCEDURE,_PROPERTY,_VAR,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1631. not((token=_ID) and (idtoken=_OPERATOR)) then
  1632. Message(parser_e_procedure_or_function_expected);
  1633. if is_interface(current_structdef) then
  1634. Message(parser_e_no_static_method_in_interfaces)
  1635. else
  1636. { class methods are also allowed for Objective-C protocols }
  1637. is_classdef:=true;
  1638. end;
  1639. end;
  1640. _CONSTRUCTOR,
  1641. _DESTRUCTOR,
  1642. _FUNCTION,
  1643. _PROCEDURE,
  1644. _OPERATOR:
  1645. begin
  1646. read_proc(is_classdef);
  1647. is_classdef:=false;
  1648. end;
  1649. _EXPORTS:
  1650. begin
  1651. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1652. begin
  1653. Message(parser_e_syntax_error);
  1654. consume_all_until(_SEMICOLON);
  1655. end
  1656. else if islibrary or
  1657. (target_info.system in systems_unit_program_exports) then
  1658. read_exports
  1659. else
  1660. begin
  1661. Message(parser_w_unsupported_feature);
  1662. consume(_BEGIN);
  1663. end;
  1664. end
  1665. else
  1666. begin
  1667. case idtoken of
  1668. _RESOURCESTRING:
  1669. begin
  1670. { m_class is needed, because the resourcestring
  1671. loading is in the ObjPas unit }
  1672. { if (m_class in current_settings.modeswitches) then}
  1673. resourcestring_dec
  1674. { else
  1675. break;}
  1676. end;
  1677. _OPERATOR:
  1678. begin
  1679. if is_classdef then
  1680. begin
  1681. read_proc(is_classdef);
  1682. is_classdef:=false;
  1683. end
  1684. else
  1685. break;
  1686. end;
  1687. _PROPERTY:
  1688. begin
  1689. if (m_fpc in current_settings.modeswitches) then
  1690. begin
  1691. property_dec(is_classdef);
  1692. is_classdef:=false;
  1693. end
  1694. else
  1695. break;
  1696. end;
  1697. else
  1698. break;
  1699. end;
  1700. end;
  1701. end;
  1702. until false;
  1703. { check for incomplete class definitions, this is only required
  1704. for fpc modes }
  1705. if (m_fpc in current_settings.modeswitches) then
  1706. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1707. end;
  1708. procedure read_interface_declarations;
  1709. begin
  1710. repeat
  1711. case token of
  1712. _CONST :
  1713. const_dec;
  1714. _TYPE :
  1715. type_dec;
  1716. _VAR :
  1717. var_dec;
  1718. _THREADVAR :
  1719. threadvar_dec;
  1720. _FUNCTION,
  1721. _PROCEDURE,
  1722. _OPERATOR :
  1723. read_proc(false);
  1724. else
  1725. begin
  1726. case idtoken of
  1727. _RESOURCESTRING :
  1728. resourcestring_dec;
  1729. _PROPERTY:
  1730. begin
  1731. if (m_fpc in current_settings.modeswitches) then
  1732. property_dec(false)
  1733. else
  1734. break;
  1735. end;
  1736. else
  1737. break;
  1738. end;
  1739. end;
  1740. end;
  1741. until false;
  1742. { check for incomplete class definitions, this is only required
  1743. for fpc modes }
  1744. if (m_fpc in current_settings.modeswitches) then
  1745. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1746. end;
  1747. {****************************************************************************
  1748. SPECIALIZATION BODY GENERATION
  1749. ****************************************************************************}
  1750. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1751. var
  1752. i : longint;
  1753. hp : tdef;
  1754. oldcurrent_filepos : tfileposinfo;
  1755. oldsymtablestack : tsymtablestack;
  1756. oldextendeddefs : TFPHashObjectList;
  1757. pu : tused_unit;
  1758. hmodule : tmodule;
  1759. specobj : tabstractrecorddef;
  1760. begin
  1761. if not((tsym(p).typ=typesym) and
  1762. (ttypesym(p).typedef.typesym=tsym(p)) and
  1763. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  1764. (df_specialization in ttypesym(p).typedef.defoptions)
  1765. ) then
  1766. exit;
  1767. { Setup symtablestack a definition time }
  1768. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  1769. if not (is_class_or_object(specobj) or is_record(specobj)) then
  1770. exit;
  1771. oldsymtablestack:=symtablestack;
  1772. oldextendeddefs:=current_module.extendeddefs;
  1773. current_module.extendeddefs:=TFPHashObjectList.create(true);
  1774. symtablestack:=tdefawaresymtablestack.create;
  1775. if not assigned(specobj.genericdef) then
  1776. internalerror(200705151);
  1777. hmodule:=find_module_from_symtable(specobj.genericdef.owner);
  1778. if hmodule=nil then
  1779. internalerror(200705152);
  1780. pu:=tused_unit(hmodule.used_units.first);
  1781. while assigned(pu) do
  1782. begin
  1783. if not assigned(pu.u.globalsymtable) then
  1784. internalerror(200705153);
  1785. symtablestack.push(pu.u.globalsymtable);
  1786. pu:=tused_unit(pu.next);
  1787. end;
  1788. if assigned(hmodule.globalsymtable) then
  1789. symtablestack.push(hmodule.globalsymtable);
  1790. if assigned(hmodule.localsymtable) then
  1791. symtablestack.push(hmodule.localsymtable);
  1792. { procedure definitions for classes or objects }
  1793. for i:=0 to specobj.symtable.DefList.Count-1 do
  1794. begin
  1795. hp:=tdef(specobj.symtable.DefList[i]);
  1796. if hp.typ=procdef then
  1797. begin
  1798. if assigned(tprocdef(hp).genericdef) and
  1799. (tprocdef(hp).genericdef.typ=procdef) and
  1800. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1801. begin
  1802. oldcurrent_filepos:=current_filepos;
  1803. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1804. { use the index the module got from the current compilation process }
  1805. current_filepos.moduleindex:=hmodule.unit_index;
  1806. current_tokenpos:=current_filepos;
  1807. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf,
  1808. tprocdef(tprocdef(hp).genericdef).change_endian);
  1809. read_proc_body(nil,tprocdef(hp));
  1810. current_filepos:=oldcurrent_filepos;
  1811. end
  1812. else
  1813. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  1814. end;
  1815. end;
  1816. { Restore symtablestack }
  1817. current_module.extendeddefs.free;
  1818. current_module.extendeddefs:=oldextendeddefs;
  1819. symtablestack.free;
  1820. symtablestack:=oldsymtablestack;
  1821. end;
  1822. procedure generate_specialization_procs;
  1823. begin
  1824. if assigned(current_module.globalsymtable) then
  1825. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1826. if assigned(current_module.localsymtable) then
  1827. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1828. end;
  1829. end.