psub.pas 93 KB

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