psub.pas 83 KB

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