psub.pas 94 KB

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