psub.pas 84 KB

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