psub.pas 105 KB

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