psub.pas 96 KB

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