psub.pas 93 KB

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