psub.pas 91 KB

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