nutils.pas 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl
  3. Type checking and register allocation for inline nodes
  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 nutils;
  18. {$i fpcdefs.inc}
  19. {$modeswitch nestedprocvars}
  20. interface
  21. uses
  22. globtype,constexp,
  23. symtype,symsym,symbase,symtable,
  24. node,compinnr,
  25. nbas;
  26. const
  27. NODE_COMPLEXITY_INF = 255;
  28. type
  29. { resultdef of functions that process on all nodes in a (sub)tree }
  30. foreachnoderesult = (
  31. { false, continue recursion }
  32. fen_false,
  33. { false, stop recursion }
  34. fen_norecurse_false,
  35. { true, continue recursion }
  36. fen_true,
  37. { true, stop recursion }
  38. fen_norecurse_true
  39. );
  40. tforeachprocmethod = ({ children are processed before the parent node }
  41. pm_preprocess,
  42. { children are processed after the parent node }
  43. pm_postprocess,
  44. { children are processed after the parent node and
  45. then the parent node is processed again }
  46. pm_postandagain);
  47. tmhs_flag = (
  48. { exceptions (overflow, sigfault etc.) are considered as side effect }
  49. mhs_exceptions
  50. );
  51. tmhs_flags = set of tmhs_flag;
  52. pmhs_flags = ^tmhs_flags;
  53. foreachnodefunction = function(var n: tnode; arg: pointer): foreachnoderesult of object;
  54. staticforeachnodefunction = function(var n: tnode; arg: pointer): foreachnoderesult;
  55. function foreachnode(var n: tnode; f: foreachnodefunction; arg: pointer): boolean;
  56. function foreachnode(procmethod : tforeachprocmethod; var n: tnode; f: foreachnodefunction; arg: pointer): boolean;
  57. function foreachnodestatic(var n: tnode; f: staticforeachnodefunction; arg: pointer): boolean;
  58. function foreachnodestatic(procmethod : tforeachprocmethod; var n: tnode; f: staticforeachnodefunction; arg: pointer): boolean;
  59. { checks if the given node tree contains only nodes of the given type,
  60. if this isn't the case, an ie is thrown
  61. }
  62. procedure checktreenodetypes(n : tnode;typeset : tnodetypeset);
  63. procedure load_procvar_from_calln(var p1:tnode);
  64. function get_local_or_para_sym(const aname: string): tabstractvarsym;
  65. function maybe_call_procvar(var p1:tnode;tponly:boolean):boolean;
  66. function load_high_value_node(vs:tparavarsym):tnode;
  67. function load_self_node:tnode;
  68. function load_result_node:tnode;
  69. function load_safecallresult_node:tnode;
  70. function load_self_pointer_node:tnode;
  71. function load_vmt_pointer_node:tnode;
  72. function is_self_node(p:tnode):boolean;
  73. { create a tree that loads the VMT based on a self-node of an object/class/
  74. interface }
  75. function load_vmt_for_self_node(self_node: tnode): tnode;
  76. function node_complexity(p: tnode): cardinal;
  77. function node_resources_fpu(p: tnode): cardinal;
  78. procedure node_tree_set_filepos(var n:tnode;const filepos:tfileposinfo);
  79. { tries to simplify the given node after inlining }
  80. procedure doinlinesimplify(var n : tnode);
  81. { creates an ordinal constant, optionally based on the result from a
  82. simplify operation: normally the type is the smallest integer type
  83. that can hold the value, but when inlining the "def" will be used instead,
  84. which was determined during an earlier typecheck pass (because the value
  85. may e.g. be a parameter to a call, which needs to be of the declared
  86. parameter type) }
  87. function create_simplified_ord_const(const value: tconstexprint; def: tdef; forinline, rangecheck: boolean): tnode;
  88. { returns true if n is only a tree of administrative nodes
  89. containing no code }
  90. function has_no_code(n : tnode) : boolean;
  91. procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
  92. function node_to_propaccesslist(p1:tnode):tpropaccesslist;
  93. { checks whether sym is a static field and if so, translates the access
  94. to the appropriate node tree }
  95. function handle_staticfield_access(sym: tsym; var p1: tnode): boolean;
  96. { returns true if n is an array element access of a bitpacked array with
  97. elements of the which the vitsize mod 8 <> 0, or if is a field access
  98. with bitsize mod 8 <> 0 or bitoffset mod 8 <> 0 of an element in a
  99. bitpacked structure }
  100. function is_bitpacked_access(n: tnode): boolean;
  101. { creates a load of field 'fieldname' in the record/class/...
  102. represented by n }
  103. function genloadfield(n: tnode; const fieldname: string): tnode;
  104. { returns true, if the tree given might have side effects }
  105. function might_have_sideeffects(n : tnode;const flags : tmhs_flags = []) : boolean;
  106. { returns true, if n contains nodes which might be conditionally executed }
  107. function has_conditional_nodes(n : tnode) : boolean;
  108. { count the number of nodes in the node tree,
  109. rough estimation how large the tree "node" is
  110. If more than max nodes, returns max, so node_count(n, 10 + 1) <= 10 answers whether the tree has ≤10 nodes but avoids traversing the remaining 990. }
  111. function node_count(node : tnode; max : dword = High(dword)) : dword;
  112. function node_count_weighted(node : tnode; max : dword = High(dword)) : dword;
  113. { returns true, if the value described by node is constant/immutable, this approximation is safe
  114. if no dirty tricks like buffer overflows or pointer magic are used }
  115. function is_const(node : tnode) : boolean;
  116. { returns a pointer to the real node a node refers to,
  117. skipping (absolute) equal type conversions. Returning
  118. a pointer allows the caller to move/remove/replace this
  119. node
  120. }
  121. function actualtargetnode(n : pnode) : pnode;
  122. { moves src into dest, before doing so, right is set to nil and dest is freed.
  123. Because dest and src are var parameters, this can be done inline in an existing
  124. node tree }
  125. procedure replacenode(var dest,src : tnode);
  126. { strip off deref/addr combinations when looking for a the load node of an open array/array of const
  127. since there is no possiblity to defined a pointer to an open array/array of const, we have not to
  128. take care of type casts, further, it means also that deref/addr nodes must always appear coupled
  129. }
  130. function get_open_const_array(p : tnode) : tnode;
  131. { excludes the flags passed in nf from the node tree passed }
  132. procedure node_reset_flags(p : tnode;nf : TNodeFlags; tnf : TTransientNodeFlags);
  133. { include or exclude cs from p.localswitches }
  134. procedure node_change_local_switch(p : tnode;cs : tlocalswitch;enable : boolean);
  135. { returns true, if p is a node which shall be short boolean evaluated,
  136. if it is not an orn/andn with boolean operans, the result is undefined }
  137. function doshortbooleval(p : tnode) : Boolean;
  138. { returns true if the node has the int value l }
  139. function is_constintvalue(p : tnode;l : Tconstexprint) : Boolean;
  140. { if the node is a constant node which can be an int value, this value is returned }
  141. function get_int_value(p : tnode): Tconstexprint;
  142. { returns true if the node is an inline node of type i }
  143. function is_inlinefunction(p : tnode;i : tinlinenumber) : Boolean;
  144. { checks if p is a series of length(a) statments, if yes, they are returned
  145. in a and the function returns true }
  146. function GetStatements(p : tnode;var a : array of tstatementnode) : Boolean;
  147. { checks if p is a single statement, if yes, it is returned in s }
  148. function IsSingleStatement(p : tnode;var s : tnode) : Boolean;
  149. { gets the last statement in a sequence of statements/blocks }
  150. function GetLastStatement(p : tnode) : tnode;
  151. type
  152. TMatchProc2 = function(n1,n2 : tnode) : Boolean is nested;
  153. TTransformProc2 = function(n1,n2 : tnode) : tnode is nested;
  154. TMatchProc4 = function(n1,n2,n3,n4 : tnode) : Boolean is nested;
  155. TTransformProc4 = function(n1,n2,n3,n4 : tnode) : tnode is nested;
  156. { calls matchproc with n1 and n2 as parameters, if it returns true, transformproc is called, does the same with the nodes swapped,
  157. the result of transformproc is assigned to res }
  158. function MatchAndTransformNodesCommutative(n1,n2 : tnode;matchproc : TMatchProc2;transformproc : TTransformProc2;var res : tnode) : Boolean;
  159. { calls matchproc with n1, n2, n3 and n4 as parameters being considered as the leafs of commutative nodes so all 8 possible
  160. combinations are tested, if it returns true, transformproc is called,
  161. the result of transformproc is assigned to res
  162. this allows to find pattern like (3*a)+(3*b) and transfrom them into 3*(a+b)
  163. }
  164. function MatchAndTransformNodesCommutative(n1,n2,n3,n4 : tnode;matchproc : TMatchProc4;transformproc : TTransformProc4;var res : tnode) : Boolean;
  165. {
  166. resets all flags so that nf_write/nf_modify information is regenerated
  167. }
  168. procedure node_reset_pass1_write(n: tnode);
  169. { Returns True if n one of its children has a type that appears in TypeList }
  170. function has_node_of_type(n: TNode; TypeList: TNodeTypeSet): Boolean; {$IFDEF USEINLINE}inline;{$ENDIF USEINLINE}
  171. { returns true if n is guranteed not to return an ordinal zero }
  172. function node_not_zero(n : tnode) : Boolean;
  173. implementation
  174. uses
  175. cutils,verbose,globals,
  176. symconst,symdef,
  177. defcmp,defutil,
  178. ncon,ncnv,nld,nflw,nset,ncal,nadd,nmem,ninl,
  179. cpubase,cgbase,procinfo,
  180. pass_1;
  181. type
  182. ForEachNodeContext = object
  183. procmethod: tforeachprocmethod;
  184. f: staticforeachnodefunction;
  185. arg: pointer;
  186. res: boolean;
  187. procedure perform(var n: tnode);
  188. procedure process_children(n: tnode);
  189. procedure process_casenode(n: tcasenode);
  190. end;
  191. procedure ForEachNodeContext.perform(var n: tnode);
  192. var
  193. fr: foreachnoderesult;
  194. begin
  195. if not assigned(n) then
  196. exit;
  197. if procmethod=pm_preprocess then
  198. process_children(n);
  199. fr:=f(n,arg);
  200. res:=(fr in [fen_true, fen_norecurse_true]) or res;
  201. if fr in [fen_norecurse_false, fen_norecurse_true] then
  202. exit;
  203. if procmethod in [pm_postprocess,pm_postandagain] then
  204. begin
  205. process_children(n);
  206. if procmethod=pm_postandagain then
  207. begin
  208. fr:=f(n,arg);
  209. res:=(fr in [fen_true, fen_norecurse_true]) or res;
  210. end;
  211. end;
  212. end;
  213. procedure ForEachNodeContext.process_children(n: tnode);
  214. begin
  215. case n.nodetype of
  216. asn:
  217. if assigned(tasnode(n).call) then
  218. begin
  219. perform(tasnode(n).call);
  220. exit
  221. end;
  222. calln:
  223. begin
  224. perform(tnode(tcallnode(n).callinitblock));
  225. perform(tcallnode(n).methodpointer);
  226. perform(tcallnode(n).funcretnode);
  227. perform(tnode(tcallnode(n).vmt_entry));
  228. perform(tnode(tcallnode(n).callcleanupblock));
  229. end;
  230. callparan:
  231. begin
  232. perform(tnode(tcallparanode(n).fparainit));
  233. perform(tcallparanode(n).fparacopyback);
  234. end;
  235. ifn, whilerepeatn, forn, tryexceptn:
  236. begin
  237. perform(tloopnode(n).t1);
  238. perform(tloopnode(n).t2);
  239. end;
  240. raisen, tryfinallyn:
  241. { frame tree/copy of finally code }
  242. perform(ttertiarynode(n).third);
  243. tempcreaten:
  244. { temp. initialization code }
  245. if assigned(ttempcreatenode(n).tempinfo^.tempinitcode) then
  246. perform(ttempcreatenode(n).tempinfo^.tempinitcode);
  247. casen:
  248. process_casenode(tcasenode(n));
  249. else
  250. ;
  251. end;
  252. if n.inheritsfrom(tbinarynode) then
  253. begin
  254. { first process the "payload" of statementnodes }
  255. perform(tbinarynode(n).left);
  256. perform(tbinarynode(n).right);
  257. end
  258. else if n.inheritsfrom(tunarynode) then
  259. perform(tunarynode(n).left);
  260. end;
  261. procedure ForEachNodeContext.process_casenode(n: tcasenode);
  262. var
  263. i: SizeInt;
  264. block: pointer;
  265. begin
  266. for i := 0 to n.blocks.count-1 do
  267. begin
  268. block := n.blocks[i];
  269. if assigned(block) then
  270. perform(pcaseblock(block)^.statement);
  271. end;
  272. perform(n.elseblock);
  273. end;
  274. { Adapts foreachnodefunction to staticforeachnodefunction. }
  275. type
  276. BoundToStaticForEachNodeContext = record
  277. f: foreachnodefunction;
  278. arg: pointer;
  279. end;
  280. function BoundToStaticForEachNodeAdapter(var n: tnode; arg: pointer): foreachnoderesult;
  281. var
  282. adaptCtx: ^BoundToStaticForEachNodeContext absolute arg;
  283. begin
  284. result := adaptCtx^.f(n, adaptCtx^.arg);
  285. end;
  286. function foreachnode(procmethod : tforeachprocmethod;var n: tnode; f: foreachnodefunction; arg: pointer): boolean;
  287. var
  288. adaptCtx: BoundToStaticForEachNodeContext;
  289. begin
  290. adaptCtx.f := f;
  291. adaptCtx.arg := arg;
  292. result:=foreachnodestatic(procmethod,n,@BoundToStaticForEachNodeAdapter,@adaptCtx);
  293. end;
  294. function foreachnode(var n: tnode; f: foreachnodefunction; arg: pointer): boolean;
  295. begin
  296. result:=foreachnode(pm_postprocess,n,f,arg);
  297. end;
  298. function foreachnodestatic(procmethod : tforeachprocmethod;var n: tnode; f: staticforeachnodefunction; arg: pointer): boolean;
  299. var
  300. fen: ForEachNodeContext;
  301. begin
  302. fen.procmethod := procmethod;
  303. fen.f := f;
  304. fen.arg := arg;
  305. fen.res := false;
  306. fen.perform(n);
  307. result := fen.res;
  308. end;
  309. function foreachnodestatic(var n: tnode; f: staticforeachnodefunction; arg: pointer): boolean;
  310. begin
  311. result:=foreachnodestatic(pm_postprocess,n,f,arg);
  312. end;
  313. function do_check(var n: tnode; arg: pointer): foreachnoderesult;
  314. begin
  315. if not(n.nodetype in pnodetypeset(arg)^) then
  316. internalerror(200610141);
  317. result:=fen_true;
  318. end;
  319. procedure checktreenodetypes(n : tnode;typeset : tnodetypeset);
  320. begin
  321. foreachnodestatic(n,@do_check,@typeset);
  322. end;
  323. procedure load_procvar_from_calln(var p1:tnode);
  324. var
  325. p2 : tnode;
  326. begin
  327. if p1.nodetype<>calln then
  328. internalerror(200212251);
  329. { was it a procvar, then we simply remove the calln and
  330. reuse the right }
  331. if assigned(tcallnode(p1).right) then
  332. begin
  333. p2:=tcallnode(p1).right;
  334. tcallnode(p1).right:=nil;
  335. end
  336. else
  337. begin
  338. p2:=cloadnode.create_procvar(tcallnode(p1).symtableprocentry,
  339. tprocdef(tcallnode(p1).procdefinition),tcallnode(p1).symtableproc);
  340. { when the methodpointer is typen we've something like:
  341. tobject.create. Then only the address is needed of the
  342. method without a self pointer }
  343. if assigned(tcallnode(p1).methodpointer) and
  344. (tcallnode(p1).methodpointer.nodetype<>typen) then
  345. tloadnode(p2).set_mp(tcallnode(p1).methodpointer.getcopy);
  346. end;
  347. typecheckpass(p2);
  348. p1.free;
  349. p1:=p2;
  350. end;
  351. function maybe_call_procvar(var p1:tnode;tponly:boolean):boolean;
  352. var
  353. hp : tnode;
  354. begin
  355. result:=false;
  356. if not (p1.resultdef.typ in [procvardef,objectdef]) or
  357. (
  358. (p1.resultdef.typ=objectdef) and
  359. (
  360. not is_invokable(p1.resultdef) or
  361. (nf_load_procvar in p1.flags) or
  362. not (
  363. is_funcref(p1.resultdef) or
  364. invokable_has_argless_invoke(tobjectdef(p1.resultdef))
  365. )
  366. )
  367. ) or
  368. (tponly and
  369. not(m_tp_procvar in current_settings.modeswitches)) then
  370. exit;
  371. { ignore vecn,subscriptn }
  372. hp:=p1;
  373. repeat
  374. case hp.nodetype of
  375. vecn,
  376. derefn,
  377. typeconvn,
  378. subscriptn :
  379. hp:=tunarynode(hp).left;
  380. blockn:
  381. hp:=laststatement(tblocknode(hp)).left
  382. else
  383. break;
  384. end;
  385. until false;
  386. { a tempref is used when it is loaded from a withsymtable }
  387. if (hp.nodetype in [calln,loadn,temprefn]) then
  388. begin
  389. hp:=ccallnode.create_procvar(nil,p1);
  390. typecheckpass(hp);
  391. p1:=hp;
  392. result:=true;
  393. end;
  394. end;
  395. function get_local_or_para_sym(const aname: string): tabstractvarsym;
  396. var
  397. pd: tprocdef;
  398. ressym: tsym;
  399. begin
  400. ressym:=nil;
  401. result:=nil;
  402. { is not assigned while parsing a property }
  403. if not assigned(current_procinfo) then
  404. exit;
  405. { we can't use searchsym here, because the
  406. symtablestack is not fully setup when pass1
  407. is run for nested procedures }
  408. pd:=current_procinfo.procdef;
  409. repeat
  410. ressym:=tsym(pd.localst.Find(aname));
  411. if assigned(ressym) then
  412. break;
  413. ressym:=tsym(pd.parast.Find(aname));
  414. if assigned(ressym) then
  415. break;
  416. { try the parent of a nested function }
  417. if assigned(pd.owner.defowner) and
  418. (pd.owner.defowner.typ=procdef) then
  419. pd:=tprocdef(pd.owner.defowner)
  420. else
  421. break;
  422. until false;
  423. if assigned(ressym) and
  424. not(ressym.typ in [localvarsym,paravarsym]) then
  425. internalerror(2020122604);
  426. result:=tabstractvarsym(ressym);
  427. end;
  428. function load_high_value_node(vs:tparavarsym):tnode;
  429. begin
  430. result:=gen_load_var(get_high_value_sym(vs));
  431. typecheckpass(result);
  432. end;
  433. function load_self_node:tnode;
  434. begin
  435. result:=gen_load_var(get_local_or_para_sym('self'));
  436. if result.nodetype=loadn then
  437. include(tloadnode(result).loadnodeflags,loadnf_is_self)
  438. else if result.nodetype<>errorn then
  439. internalerror(2020122603);
  440. typecheckpass(result);
  441. end;
  442. function load_result_node:tnode;
  443. begin
  444. result:=gen_load_var(get_local_or_para_sym('result'));
  445. typecheckpass(result);
  446. end;
  447. function load_safecallresult_node: tnode;
  448. begin
  449. result:=gen_load_var(get_local_or_para_sym('safecallresult'));
  450. typecheckpass(result);
  451. end;
  452. function load_self_pointer_node:tnode;
  453. var
  454. srsym : tabstractvarsym;
  455. begin
  456. srsym:=get_local_or_para_sym('self');
  457. result:=gen_load_var(srsym);
  458. if assigned(srsym) and
  459. (is_object(tabstractvarsym(srsym).vardef) or is_record(tabstractvarsym(srsym).vardef)) then
  460. begin
  461. if result.nodetype=loadn then
  462. include(tloadnode(result).loadnodeflags,loadnf_load_addr)
  463. else if result.nodetype<>errorn then
  464. internalerror(2020122602);
  465. end;
  466. typecheckpass(result);
  467. end;
  468. function load_vmt_pointer_node:tnode;
  469. begin
  470. result:=gen_load_var(get_local_or_para_sym('vmt'));
  471. typecheckpass(result);
  472. end;
  473. function is_self_node(p:tnode):boolean;
  474. begin
  475. is_self_node:=(p.nodetype=loadn) and
  476. (tloadnode(p).symtableentry.typ=paravarsym) and
  477. (vo_is_self in tparavarsym(tloadnode(p).symtableentry).varoptions);
  478. end;
  479. function load_vmt_for_self_node(self_node: tnode): tnode;
  480. var
  481. self_resultdef: tdef;
  482. obj_def: tobjectdef;
  483. self_temp,
  484. vmt_temp: ttempcreatenode;
  485. check_self,n: tnode;
  486. stat: tstatementnode;
  487. block: tblocknode;
  488. paras: tcallparanode;
  489. docheck,is_typecasted_classref: boolean;
  490. begin
  491. self_resultdef:=self_node.resultdef;
  492. case self_resultdef.typ of
  493. classrefdef:
  494. begin
  495. obj_def:=tobjectdef(tclassrefdef(self_resultdef).pointeddef);
  496. end;
  497. objectdef:
  498. obj_def:=tobjectdef(self_resultdef);
  499. else
  500. internalerror(2015052701);
  501. end;
  502. n:=self_node;
  503. is_typecasted_classref:=false;
  504. if (n.nodetype=typeconvn) then
  505. begin
  506. while assigned(n) and (n.nodetype=typeconvn) and (nf_explicit in ttypeconvnode(n).flags) do
  507. n:=ttypeconvnode(n).left;
  508. if assigned(n) and (n.resultdef.typ=classrefdef) then
  509. is_typecasted_classref:=true;
  510. end;
  511. if is_classhelper(obj_def) then
  512. obj_def:=tobjectdef(tobjectdef(obj_def).extendeddef);
  513. docheck:=
  514. not(is_interface(obj_def)) and
  515. not(is_cppclass(obj_def)) and
  516. not(is_objc_class_or_protocol(obj_def)) and
  517. (([cs_check_object,cs_check_range]*current_settings.localswitches)<>[]);
  518. block:=nil;
  519. stat:=nil;
  520. self_temp:=nil;
  521. if docheck then
  522. begin
  523. { check for nil self-pointer }
  524. block:=internalstatements(stat);
  525. if is_object(self_resultdef) then
  526. begin
  527. self_temp:=ctempcreatenode.create_value(
  528. cpointerdef.getreusable(self_resultdef),cpointerdef.getreusable(self_resultdef).size,tt_persistent,true,
  529. caddrnode.create(self_node));
  530. end
  531. else
  532. self_temp:=ctempcreatenode.create_value(
  533. self_resultdef,self_resultdef.size,tt_persistent,true,
  534. self_node);
  535. addstatement(stat,self_temp);
  536. { in case of an object, self can only be nil if it's a dereferenced
  537. node somehow
  538. }
  539. if not is_object(self_resultdef) or
  540. (actualtargetnode(@self_node)^.nodetype=derefn) then
  541. begin
  542. check_self:=ctemprefnode.create(self_temp);
  543. addstatement(stat,cifnode.create(
  544. caddnode.create(equaln,
  545. ctypeconvnode.create_explicit(
  546. check_self,
  547. voidpointertype
  548. ),
  549. cnilnode.create),
  550. ccallnode.createintern('fpc_objecterror',nil),
  551. nil)
  552. );
  553. end;
  554. if is_object(self_resultdef) then
  555. self_node:=cderefnode.create(ctemprefnode.create(self_temp))
  556. else
  557. self_node:=ctemprefnode.create(self_temp)
  558. end;
  559. { in case of a classref, the "instance" is a pointer
  560. to pointer to a VMT and there is no vmt field }
  561. if is_typecasted_classref or (self_resultdef.typ=classrefdef) then
  562. result:=self_node
  563. { get the VMT field in case of a class/object }
  564. else if (self_resultdef.typ=objectdef) and
  565. assigned(tobjectdef(self_resultdef).vmt_field) then
  566. result:=csubscriptnode.create(tobjectdef(self_resultdef).vmt_field,self_node)
  567. { in case of an interface, the "instance" is a pointer to a pointer
  568. to a VMT -> dereference once already }
  569. else
  570. { in case of an interface/classref, the "instance" is a pointer
  571. to pointer to a VMT and there is no vmt field }
  572. result:=cderefnode.create(
  573. ctypeconvnode.create_explicit(
  574. self_node,
  575. cpointerdef.getreusable(voidpointertype)
  576. )
  577. );
  578. result:=ctypeconvnode.create_explicit(
  579. result,
  580. cpointerdef.getreusable(obj_def.vmt_def));
  581. typecheckpass(result);
  582. if docheck then
  583. begin
  584. { add a vmt validity check }
  585. vmt_temp:=ctempcreatenode.create_value(result.resultdef,result.resultdef.size,tt_persistent,true,result);
  586. addstatement(stat,vmt_temp);
  587. paras:=ccallparanode.create(ctemprefnode.create(vmt_temp),nil);
  588. if cs_check_object in current_settings.localswitches then
  589. begin
  590. paras:=ccallparanode.create(
  591. cloadvmtaddrnode.create(ctypenode.create(obj_def)),
  592. paras
  593. );
  594. addstatement(stat,
  595. ccallnode.createintern(
  596. 'fpc_check_object_ext',paras
  597. )
  598. );
  599. end
  600. else
  601. addstatement(stat,
  602. ccallnode.createintern(
  603. 'fpc_check_object',paras
  604. )
  605. );
  606. addstatement(stat,ctempdeletenode.create_normal_temp(vmt_temp));
  607. addstatement(stat,ctempdeletenode.create(self_temp));
  608. addstatement(stat,ctemprefnode.create(vmt_temp));
  609. result:=block;
  610. end
  611. end;
  612. { this function must return a very high value ("infinity") for }
  613. { trees containing a call, the rest can be balanced more or less }
  614. { at will, probably best mainly in terms of required memory }
  615. { accesses }
  616. function node_complexity(p: tnode): cardinal;
  617. {$ifdef x86}
  618. function in_const_set_complexity(cs: tsetconstnode): cardinal;
  619. var
  620. i,maxranges,lastv: cardinal;
  621. begin
  622. { maxranges value should match the logic in nx86set.pas:tx86innode.pass_generate_code.analizeset. }
  623. if is_smallset(cs.resultdef) then
  624. maxranges:=3
  625. else if cs_opt_size in current_settings.optimizerswitches then
  626. maxranges:=8
  627. else
  628. maxranges:=5;
  629. result:=0;
  630. lastv:=High(lastv)-1;
  631. for i:=tsetdef(cs.resultdef).setbase to tsetdef(cs.resultdef).setmax do
  632. if i in cs.value_set^ then
  633. begin
  634. if i<>lastv+1 then
  635. begin
  636. inc(result);
  637. if result>maxranges then
  638. exit(3);
  639. end;
  640. lastv:=i;
  641. end;
  642. end;
  643. {$endif}
  644. var
  645. cv : cardinal;
  646. {$ifdef ARM}
  647. dummy : byte;
  648. {$endif ARM}
  649. begin
  650. cv:=0;
  651. result:=NODE_COMPLEXITY_INF; { For early exits by default. }
  652. while assigned(p) and (cv<NODE_COMPLEXITY_INF) do { break = return cv, exit = return NODE_COMPLEXITY_INF. }
  653. begin
  654. case p.nodetype of
  655. { floating point constants usually need loading from memory }
  656. realconstn:
  657. begin
  658. inc(cv,2);
  659. break;
  660. end;
  661. temprefn:
  662. begin
  663. if (ttemprefnode(p).tempinfo^.typedef.needs_inittable) or
  664. not(ti_may_be_in_reg in ttemprefnode(p).tempflags) then
  665. inc(cv);
  666. break;
  667. end;
  668. rttin,
  669. setconstn,
  670. stringconstn,
  671. loadvmtaddrn,
  672. { main reason for the next one: we can't take the address of }
  673. { loadparentfpnode, so replacing it by a temp which is the }
  674. { address of this node's location and then dereferencing }
  675. { doesn't work. If changed, check whether webtbs/tw0935 }
  676. { still works with nodeinlining (JM) }
  677. loadparentfpn:
  678. begin
  679. inc(cv);
  680. break;
  681. end;
  682. loadn:
  683. begin
  684. if assigned(tloadnode(p).left) then
  685. inc(cv,node_complexity(tloadnode(p).left));
  686. { threadvars need a helper call }
  687. if (tloadnode(p).symtableentry.typ=staticvarsym) and
  688. (vo_is_thread_var in tstaticvarsym(tloadnode(p).symtableentry).varoptions) then
  689. inc(cv,5)
  690. else if not((tloadnode(p).symtableentry.typ in [staticvarsym,localvarsym,paravarsym,fieldvarsym]) and
  691. (tabstractvarsym(tloadnode(p).symtableentry).varregable in [vr_intreg,vr_mmreg,vr_fpureg])) then
  692. inc(cv);
  693. if (tloadnode(p).symtableentry.typ=paravarsym) and
  694. not(tabstractvarsym(tloadnode(p).symtableentry).varregable=vr_addr) and
  695. tloadnode(p).is_addr_param_load then
  696. inc(cv);
  697. p:=nil; { Check for NODE_COMPLEXITY_INF and return cv. }
  698. end;
  699. subscriptn:
  700. begin
  701. if is_implicit_pointer_object_type(tunarynode(p).left.resultdef) or
  702. is_bitpacked_access(p) then
  703. inc(cv,2)
  704. { non-packed, int. regable records cause no extra
  705. overhead no overhead if the fields are aligned to register boundaries }
  706. else if tstoreddef(p.resultdef).is_intregable and (tsubscriptnode(p).vs.fieldoffset mod sizeof(aint)<>0) then
  707. inc(cv,1);
  708. p:=tunarynode(p).left;
  709. end;
  710. blockn:
  711. p:=tunarynode(p).left;
  712. callparan:
  713. begin
  714. { call to decr? }
  715. if is_managed_type(tunarynode(p).left.resultdef) and
  716. assigned(tcallparanode(p).parasym) and (tcallparanode(p).parasym.varspez=vs_out) then
  717. exit;
  718. inc(cv);
  719. p:=tunarynode(p).left;
  720. end;
  721. notn,
  722. derefn,
  723. addrn :
  724. begin
  725. inc(cv);
  726. p:=tunarynode(p).left;
  727. end;
  728. typeconvn:
  729. begin
  730. { may be more complex in some cases }
  731. if not(ttypeconvnode(p).retains_value_location) and
  732. not((ttypeconvnode(p).convtype=tc_pointer_2_array) and (ttypeconvnode(p).left.expectloc in [LOC_CREGISTER,LOC_REGISTER,LOC_CONSTANT])) then
  733. inc(cv);
  734. p:=tunarynode(p).left;
  735. end;
  736. statementn:
  737. begin
  738. inc(cv,node_complexity(tbinarynode(p).left));
  739. p:=tbinarynode(p).right;
  740. end;
  741. addn,subn,orn,andn,xorn,symdifn,
  742. shln,shrn,
  743. equaln,unequaln,gtn,gten,ltn,lten,
  744. assignn,vecn:
  745. begin
  746. inc(cv,node_complexity(tbinarynode(p).left)+1);
  747. p:=tbinarynode(p).right;
  748. end;
  749. muln:
  750. begin
  751. inc(cv,node_complexity(tbinarynode(p).left)+{$ifdef CPU64BITALU}4{$else}8{$endif});
  752. p:=tbinarynode(p).right;
  753. end;
  754. divn,modn,slashn:
  755. begin
  756. inc(cv,node_complexity(tbinarynode(p).left)+{$ifdef CPU64BITALU}10{$else}20{$endif});
  757. p:=tbinarynode(p).right;
  758. end;
  759. inn:
  760. begin
  761. inc(cv,node_complexity(tinnode(p).left));
  762. {$if declared(in_const_set_complexity)}
  763. if tinnode(p).right.nodetype=setconstn then
  764. begin
  765. inc(cv,in_const_set_complexity(tsetconstnode(tinnode(p).right)));
  766. break;
  767. end;
  768. {$endif in_const_set_complexity}
  769. inc(cv,3);
  770. p:=tbinarynode(p).right;
  771. end;
  772. ordconstn:
  773. begin
  774. {$ifdef ARM}
  775. if not(is_shifter_const(aint(tordconstnode(p).value.svalue),dummy)) then
  776. inc(cv,2);
  777. {$endif ARM}
  778. {$ifdef RISCV}
  779. if not(is_imm12(aint(tordconstnode(p).value.svalue))) then
  780. inc(cv,2);
  781. {$endif RISCV}
  782. break;
  783. end;
  784. exitn:
  785. begin
  786. inc(cv,2);
  787. p:=texitnode(p).left;
  788. end;
  789. tempcreaten,
  790. tempdeleten,
  791. pointerconstn,
  792. nothingn,
  793. niln:
  794. break;
  795. inlinen:
  796. begin
  797. { this code assumes that the inline node has }
  798. { already been firstpassed, and consequently }
  799. { that inline nodes which are transformed into }
  800. { calls already have been transformed }
  801. case tinlinenode(p).inlinenumber of
  802. in_lo_qword,
  803. in_hi_qword,
  804. in_lo_long,
  805. in_hi_long,
  806. in_lo_word,
  807. in_hi_word,
  808. in_length_x,
  809. in_assigned_x,
  810. in_pred_x,
  811. in_succ_x,
  812. in_round_real,
  813. in_trunc_real,
  814. in_int_real,
  815. in_frac_real,
  816. in_pi_real,
  817. in_abs_real,
  818. in_aligned_x,
  819. in_unaligned_x,
  820. in_volatile_x,
  821. in_prefetch_var:
  822. begin
  823. inc(cv);
  824. p:=tunarynode(p).left;
  825. end;
  826. in_cos_real,
  827. in_sin_real,
  828. in_arctan_real,
  829. in_sqrt_real,
  830. in_ln_real:
  831. begin
  832. inc(cv,15);
  833. p:=tunarynode(p).left;
  834. end;
  835. in_sqr_real:
  836. begin
  837. inc(cv,2);
  838. p:=tunarynode(p).left;
  839. end;
  840. in_abs_long:
  841. begin
  842. inc(cv,3);
  843. p:=tunarynode(p).left;
  844. end;
  845. in_sizeof_x,
  846. in_typeof_x:
  847. begin
  848. inc(cv);
  849. if (tinlinenode(p).left.nodetype<>typen) then
  850. { get instance vmt }
  851. p:=tunarynode(p).left
  852. else
  853. { type vmt = global symbol, result is }
  854. { already increased above }
  855. break;
  856. end;
  857. {$ifdef SUPPORT_MMX}
  858. in_mmx_pcmpeqb..in_mmx_pcmpgtw,
  859. {$endif SUPPORT_MMX}
  860. { load from global symbol }
  861. in_typeinfo_x,
  862. { load frame pointer }
  863. in_get_frame,
  864. in_get_caller_frame,
  865. in_get_caller_addr:
  866. begin
  867. inc(cv);
  868. break;
  869. end;
  870. in_ror_x,
  871. in_ror_x_y,
  872. in_rol_x,
  873. in_rol_x_y,
  874. in_inc_x,
  875. in_dec_x,
  876. in_include_x_y,
  877. in_exclude_x_y,
  878. in_assert_x_y :
  879. begin
  880. { operation (add, sub, or, and }
  881. inc(cv);
  882. { left expression }
  883. inc(cv,node_complexity(tcallparanode(tunarynode(p).left).left));
  884. p:=tcallparanode(tunarynode(p).left).right;
  885. if assigned(p) then
  886. p:=tcallparanode(p).left;
  887. end;
  888. else
  889. exit;
  890. end;
  891. end;
  892. else
  893. exit;
  894. end;
  895. end;
  896. if cv>NODE_COMPLEXITY_INF then
  897. cv:=NODE_COMPLEXITY_INF;
  898. result:=cv;
  899. end;
  900. { this function returns an indication how much fpu registers
  901. will be required.
  902. Note: The algorithms need to be pessimistic to prevent a
  903. fpu stack overflow on i386 }
  904. function node_resources_fpu(p: tnode): cardinal;
  905. var
  906. res1,res2,res3 : cardinal;
  907. begin
  908. result:=0;
  909. res1:=0;
  910. res2:=0;
  911. res3:=0;
  912. if p.inheritsfrom(tunarynode) then
  913. begin
  914. if assigned(tunarynode(p).left) then
  915. res1:=node_resources_fpu(tunarynode(p).left);
  916. if p.inheritsfrom(tbinarynode) then
  917. begin
  918. if assigned(tbinarynode(p).right) then
  919. res2:=node_resources_fpu(tbinarynode(p).right);
  920. if p.inheritsfrom(ttertiarynode) and assigned(ttertiarynode(p).third) then
  921. res3:=node_resources_fpu(ttertiarynode(p).third)
  922. end;
  923. end;
  924. result:=max(max(res1,res2),res3);
  925. case p.nodetype of
  926. calln:
  927. { it could be a recursive call, so we never really know the number of used fpu registers }
  928. result:=maxfpuregs;
  929. realconstn,
  930. typeconvn,
  931. loadn :
  932. begin
  933. if p.expectloc in [LOC_CFPUREGISTER,LOC_FPUREGISTER] then
  934. result:=max(result,1);
  935. end;
  936. assignn,
  937. addn,subn,muln,slashn,
  938. equaln,unequaln,gtn,gten,ltn,lten :
  939. begin
  940. if (tbinarynode(p).left.expectloc in [LOC_CFPUREGISTER,LOC_FPUREGISTER]) or
  941. (tbinarynode(p).right.expectloc in [LOC_CFPUREGISTER,LOC_FPUREGISTER])then
  942. result:=max(result,2);
  943. if(p.expectloc in [LOC_CFPUREGISTER,LOC_FPUREGISTER]) then
  944. inc(result);
  945. end;
  946. else
  947. ;
  948. end;
  949. end;
  950. function setnodefilepos(var n: tnode; arg: pointer): foreachnoderesult;
  951. begin
  952. result:=fen_true;
  953. n.fileinfo:=pfileposinfo(arg)^;
  954. end;
  955. procedure node_tree_set_filepos(var n:tnode;const filepos:tfileposinfo);
  956. begin
  957. foreachnodestatic(n,@setnodefilepos,@filepos);
  958. end;
  959. function callsimplify(var n: tnode; arg: pointer): foreachnoderesult;
  960. var
  961. hn : tnode;
  962. treechanged : ^boolean;
  963. begin
  964. result:=fen_false;
  965. if n.inheritsfrom(tloopnode) and
  966. not (lnf_simplify_processing in tloopnode(n).loopflags) then
  967. begin
  968. // Try to simplify condition
  969. doinlinesimplify(tloopnode(n).left);
  970. // call directly second part below,
  971. // which might change the loopnode into
  972. // something else if the conditino is a constant node
  973. include(tloopnode(n).loopflags,lnf_simplify_processing);
  974. callsimplify(n,arg);
  975. // Be careful, n might have change node type
  976. if n.inheritsfrom(tloopnode) then
  977. exclude(tloopnode(n).loopflags,lnf_simplify_processing);
  978. end
  979. else
  980. begin
  981. hn:=n.simplify(true);
  982. if assigned(hn) then
  983. begin
  984. treechanged := arg;
  985. if assigned(treechanged) then
  986. treechanged^:=true
  987. else
  988. internalerror (201008181);
  989. n.free;
  990. n:=hn;
  991. typecheckpass(n);
  992. end;
  993. end;
  994. end;
  995. { tries to simplify the given node calling the simplify method recursively }
  996. procedure doinlinesimplify(var n : tnode);
  997. var
  998. treechanged : boolean;
  999. begin
  1000. // Optimize if code first
  1001. repeat
  1002. treechanged:=false;
  1003. foreachnodestatic(pm_postandagain,n,@callsimplify,@treechanged);
  1004. until not(treechanged);
  1005. end;
  1006. function create_simplified_ord_const(const value: tconstexprint; def: tdef; forinline, rangecheck: boolean): tnode;
  1007. begin
  1008. if not forinline then
  1009. result:=genintconstnode(value)
  1010. else
  1011. result:=cordconstnode.create(value,def,rangecheck);
  1012. end;
  1013. procedure propaccesslist_to_node(var p1:tnode;st:TSymtable;pl:tpropaccesslist);
  1014. var
  1015. plist : ppropaccesslistitem;
  1016. begin
  1017. plist:=pl.firstsym;
  1018. while assigned(plist) do
  1019. begin
  1020. case plist^.sltype of
  1021. sl_load :
  1022. begin
  1023. addsymref(plist^.sym);
  1024. if not assigned(st) then
  1025. st:=plist^.sym.owner;
  1026. if (plist^.sym.typ<>staticvarsym) then
  1027. begin
  1028. { p1 can already contain the loadnode of
  1029. the class variable. When there is no tree yet we
  1030. may need to load it for with or objects }
  1031. if not assigned(p1) then
  1032. begin
  1033. case st.symtabletype of
  1034. withsymtable :
  1035. p1:=tnode(twithsymtable(st).withrefnode).getcopy;
  1036. ObjectSymtable :
  1037. p1:=load_self_node;
  1038. else
  1039. ;
  1040. end;
  1041. end
  1042. end
  1043. else
  1044. begin
  1045. p1.free;
  1046. p1:=nil;
  1047. end;
  1048. if assigned(p1) then
  1049. p1:=csubscriptnode.create(plist^.sym,p1)
  1050. else
  1051. p1:=cloadnode.create(plist^.sym,st);
  1052. end;
  1053. sl_subscript :
  1054. begin
  1055. addsymref(plist^.sym);
  1056. p1:=csubscriptnode.create(plist^.sym,p1);
  1057. end;
  1058. sl_typeconv :
  1059. p1:=ctypeconvnode.create_explicit(p1,plist^.def);
  1060. sl_absolutetype :
  1061. begin
  1062. p1:=ctypeconvnode.create(p1,plist^.def);
  1063. include(p1.flags,nf_absolute);
  1064. end;
  1065. sl_vec :
  1066. p1:=cvecnode.create(p1,cordconstnode.create(plist^.value,plist^.valuedef,true));
  1067. else
  1068. internalerror(200110205);
  1069. end;
  1070. plist:=plist^.next;
  1071. end;
  1072. end;
  1073. function node_to_propaccesslist(p1:tnode):tpropaccesslist;
  1074. var
  1075. sl : tpropaccesslist;
  1076. procedure addnode(p:tnode);
  1077. begin
  1078. case p.nodetype of
  1079. subscriptn :
  1080. begin
  1081. addnode(tsubscriptnode(p).left);
  1082. sl.addsym(sl_subscript,tsubscriptnode(p).vs);
  1083. end;
  1084. typeconvn :
  1085. begin
  1086. addnode(ttypeconvnode(p).left);
  1087. if nf_absolute in ttypeconvnode(p).flags then
  1088. sl.addtype(sl_absolutetype,ttypeconvnode(p).totypedef)
  1089. else
  1090. sl.addtype(sl_typeconv,ttypeconvnode(p).totypedef);
  1091. end;
  1092. vecn :
  1093. begin
  1094. addnode(tvecnode(p).left);
  1095. if tvecnode(p).right.nodetype=ordconstn then
  1096. sl.addconst(sl_vec,tordconstnode(tvecnode(p).right).value,tvecnode(p).right.resultdef)
  1097. else
  1098. begin
  1099. Message(parser_e_illegal_expression);
  1100. { recovery }
  1101. sl.addconst(sl_vec,0,tvecnode(p).right.resultdef);
  1102. end;
  1103. end;
  1104. loadn :
  1105. sl.addsym(sl_load,tloadnode(p).symtableentry);
  1106. else
  1107. internalerror(200310282);
  1108. end;
  1109. end;
  1110. begin
  1111. sl:=tpropaccesslist.create;
  1112. addnode(p1);
  1113. result:=sl;
  1114. end;
  1115. function handle_staticfield_access(sym: tsym; var p1: tnode): boolean;
  1116. function handle_generic_staticfield_access:boolean;
  1117. var
  1118. tmp : tstoreddef;
  1119. pd : tprocdef;
  1120. begin
  1121. { in case we have a specialization inside a generic (thus the static var sym does not
  1122. exist) we simply simulate a non static access to avoid unnecessary errors }
  1123. if assigned(sym.owner.defowner) and (df_specialization in tstoreddef(sym.owner.defowner).defoptions) then
  1124. begin
  1125. tmp:=tstoreddef(sym.owner.defowner);
  1126. while assigned(tmp) do
  1127. begin
  1128. if df_generic in tmp.defoptions then
  1129. begin
  1130. p1.free;
  1131. if assigned(current_procinfo) then
  1132. begin
  1133. pd:=current_procinfo.get_normal_proc.procdef;
  1134. if assigned(pd) and pd.no_self_node then
  1135. p1:=cloadvmtaddrnode.create(ctypenode.create(pd.struct))
  1136. else
  1137. p1:=load_self_node;
  1138. end
  1139. else
  1140. p1:=load_self_node;
  1141. p1:=csubscriptnode.create(sym,p1);
  1142. exit(true);
  1143. end;
  1144. tmp:=tstoreddef(tmp.owner.defowner);
  1145. end;
  1146. end;
  1147. result:=false;
  1148. end;
  1149. var
  1150. static_name: shortstring;
  1151. srsymtable: tsymtable;
  1152. begin
  1153. result:=false;
  1154. { generate access code }
  1155. if (sp_static in sym.symoptions) then
  1156. begin
  1157. result:=true;
  1158. if handle_generic_staticfield_access then
  1159. exit;
  1160. static_name:=lower(generate_nested_name(sym.owner,'_'))+'_'+sym.name;
  1161. if sym.owner.defowner.typ=objectdef then
  1162. searchsym_in_class(tobjectdef(sym.owner.defowner),tobjectdef(sym.owner.defowner),static_name,sym,srsymtable,[ssf_search_helper])
  1163. else
  1164. searchsym_in_record(trecorddef(sym.owner.defowner),static_name,sym,srsymtable);
  1165. if assigned(sym) then
  1166. check_hints(sym,sym.symoptions,sym.deprecatedmsg);
  1167. p1.free;
  1168. p1:=nil;
  1169. { static syms are always stored as absolutevarsym to handle scope and storage properly }
  1170. propaccesslist_to_node(p1,nil,tabsolutevarsym(sym).ref);
  1171. end;
  1172. end;
  1173. function is_bitpacked_access(n: tnode): boolean;
  1174. begin
  1175. case n.nodetype of
  1176. vecn:
  1177. result:=
  1178. is_packed_array(tvecnode(n).left.resultdef) and
  1179. { only orddefs and enumdefs are actually bitpacked. Don't consider
  1180. e.g. an access to a 3-byte record as "bitpacked", since it
  1181. isn't }
  1182. (tvecnode(n).left.resultdef.typ = arraydef) and
  1183. (tarraydef(tvecnode(n).left.resultdef).elementdef.typ in [orddef,enumdef]) and
  1184. not(tarraydef(tvecnode(n).left.resultdef).elepackedbitsize in [8,16,32,64]);
  1185. subscriptn:
  1186. result:=
  1187. is_packed_record_or_object(tsubscriptnode(n).left.resultdef) and
  1188. { see above }
  1189. (tsubscriptnode(n).vs.vardef.typ in [orddef,enumdef]) and
  1190. (not(tsubscriptnode(n).vs.vardef.packedbitsize in [8,16,32,64]) or
  1191. (tsubscriptnode(n).vs.fieldoffset mod 8 <> 0));
  1192. else
  1193. result:=false;
  1194. end;
  1195. end;
  1196. function genloadfield(n: tnode; const fieldname: string): tnode;
  1197. var
  1198. vs : tsym;
  1199. begin
  1200. if not assigned(n.resultdef) then
  1201. typecheckpass(n);
  1202. vs:=tsym(tabstractrecorddef(n.resultdef).symtable.find(fieldname));
  1203. if not assigned(vs) or
  1204. (vs.typ<>fieldvarsym) then
  1205. internalerror(2010061902);
  1206. result:=csubscriptnode.create(vs,n);
  1207. end;
  1208. function has_no_code(n : tnode) : boolean;
  1209. begin
  1210. if n=nil then
  1211. begin
  1212. result:=true;
  1213. exit;
  1214. end;
  1215. case n.nodetype of
  1216. nothingn:
  1217. begin
  1218. result:=true;
  1219. exit;
  1220. end;
  1221. blockn:
  1222. begin
  1223. result:=has_no_code(tblocknode(n).left);
  1224. exit;
  1225. end;
  1226. statementn:
  1227. begin
  1228. repeat
  1229. result:=has_no_code(tstatementnode(n).left);
  1230. n:=tstatementnode(n).right;
  1231. until not(result) or not assigned(n);
  1232. exit;
  1233. end;
  1234. else
  1235. result:=false;
  1236. end;
  1237. end;
  1238. function check_for_sideeffect(var n: tnode; arg: pointer): foreachnoderesult;
  1239. begin
  1240. result:=fen_false;
  1241. if (n.nodetype in [assignn,calln,asmn,finalizetempsn]) or
  1242. ((n.nodetype=inlinen) and
  1243. tinlinenode(n).may_have_sideeffect_norecurse
  1244. ) or
  1245. ((mhs_exceptions in pmhs_flags(arg)^) and
  1246. ((n.nodetype in [derefn,vecn,divn,slashn]) or
  1247. ((n.nodetype=subscriptn) and is_implicit_pointer_object_type(tsubscriptnode(n).left.resultdef)) or
  1248. ((n.nodetype in [addn,subn,muln,unaryminusn]) and (n.localswitches*[cs_check_overflow,cs_check_range]<>[])) or
  1249. { float operations could throw an exception }
  1250. ((n.nodetype in [addn,subn,muln,slashn,unaryminusn,equaln,unequaln,gten,gtn,lten,ltn]) and is_real_or_cextended(tunarynode(n).left.resultdef))
  1251. )
  1252. ) or
  1253. ((n.nodetype=loadn) and
  1254. (
  1255. ((tloadnode(n).symtableentry.typ=absolutevarsym) and (tabsolutevarsym(tloadnode(n).symtableentry).abstyp=toaddr)) or
  1256. ((tloadnode(n).symtableentry.typ in [paravarsym,localvarsym,staticvarsym]) and
  1257. (vo_volatile in tabstractvarsym(tloadnode(n).symtableentry).varoptions)
  1258. )
  1259. )
  1260. ) or
  1261. { foreachonode does not recurse into the init code for temprefnode as this is done for
  1262. by the tempcreatenode but the considered tree might not contain the tempcreatenode so play
  1263. save and recurce into the init code if there is any }
  1264. ((n.nodetype=temprefn) and (ti_executeinitialisation in ttemprefnode(n).tempflags) and
  1265. might_have_sideeffects(ttemprefnode(n).tempinfo^.tempinitcode,pmhs_flags(arg)^)) then
  1266. result:=fen_norecurse_true
  1267. end;
  1268. function might_have_sideeffects(n : tnode; const flags : tmhs_flags) : boolean;
  1269. begin
  1270. result:=foreachnodestatic(n,@check_for_sideeffect,@flags);
  1271. end;
  1272. function check_for_conditional_nodes(var n: tnode; arg: pointer): foreachnoderesult;
  1273. begin
  1274. result:=fen_false;
  1275. { this check is not complete yet, but sufficent to cover the current use case: swapping
  1276. of trees in expressions }
  1277. if (n.nodetype in [ifn,whilerepeatn,forn,tryexceptn]) or
  1278. ((n.nodetype in [orn,andn]) and is_boolean(n.resultdef) and doshortbooleval(n)) then
  1279. result:=fen_norecurse_true;
  1280. end;
  1281. function has_conditional_nodes(n : tnode) : boolean;
  1282. begin
  1283. result:=foreachnodestatic(n,@check_for_conditional_nodes,nil);
  1284. end;
  1285. function donodecount(var n: tnode; arg: pointer): foreachnoderesult;
  1286. begin
  1287. if PDWord(arg)^>0 then
  1288. begin
  1289. dec(PDWord(arg)^);
  1290. result:=fen_false;
  1291. end
  1292. else
  1293. result:=fen_norecurse_false;
  1294. end;
  1295. function node_count(node : tnode; max : dword = High(dword)) : dword;
  1296. var
  1297. left : dword;
  1298. begin
  1299. left:=max;
  1300. foreachnodestatic(node,@donodecount,@left);
  1301. result:=max-left;
  1302. end;
  1303. function donodecount_weighted(var n: tnode; arg: pointer): foreachnoderesult;
  1304. begin
  1305. if PDWord(arg)^>0 then
  1306. begin
  1307. if not(n.nodetype in [blockn,statementn,callparan,nothingn]) then
  1308. dec(PDWord(arg)^);
  1309. result:=fen_false;
  1310. end
  1311. else
  1312. result:=fen_norecurse_false;
  1313. end;
  1314. function node_count_weighted(node : tnode; max : dword = High(dword)) : dword;
  1315. var
  1316. left : dword;
  1317. begin
  1318. left:=max;
  1319. foreachnodestatic(node,@donodecount_weighted,@left);
  1320. result:=max-left;
  1321. end;
  1322. function is_const(node : tnode) : boolean;
  1323. begin
  1324. result:=is_constnode(node) or
  1325. ((node.nodetype=temprefn) and (ti_const in ttemprefnode(node).tempflags)) or
  1326. ((node.nodetype=loadn) and (tloadnode(node).symtableentry.typ=paravarsym) and (tparavarsym(tloadnode(node).symtableentry).varspez in [vs_const,vs_constref]));
  1327. end;
  1328. function actualtargetnode(n : pnode) : pnode;
  1329. begin
  1330. result:=n;
  1331. case n^.nodetype of
  1332. typeconvn:
  1333. if ttypeconvnode(n^).retains_value_location then
  1334. result:=actualtargetnode(@ttypeconvnode(n^).left);
  1335. else
  1336. ;
  1337. end;
  1338. end;
  1339. procedure replacenode(var dest,src : tnode);
  1340. var
  1341. t : tnode;
  1342. begin
  1343. t:=src;
  1344. { set src nil before free'ing dest because
  1345. src could be part of dest }
  1346. src:=nil;
  1347. dest.Free;
  1348. dest:=t;
  1349. end;
  1350. function get_open_const_array(p : tnode) : tnode;
  1351. begin
  1352. result:=p;
  1353. if (p.nodetype=derefn) and (tderefnode(p).left.nodetype=addrn) then
  1354. result:=get_open_const_array(taddrnode(tderefnode(result).left).left);
  1355. end;
  1356. type
  1357. TFlagSet = record
  1358. nf : TNodeFlags;
  1359. tnf : TTransientNodeFlags;
  1360. end;
  1361. function do_node_reset_flags(var n: tnode; arg: pointer): foreachnoderesult;
  1362. begin
  1363. result:=fen_false;
  1364. n.flags:=n.flags-TFlagSet(arg^).nf;
  1365. n.transientflags:=n.transientflags-TFlagSet(arg^).tnf;
  1366. end;
  1367. procedure node_reset_flags(p : tnode; nf : TNodeFlags; tnf : TTransientNodeFlags);
  1368. var
  1369. FlagSet: TFlagSet;
  1370. begin
  1371. FlagSet.nf:=nf;
  1372. FlagSet.tnf:=tnf;
  1373. foreachnodestatic(p,@do_node_reset_flags,@FlagSet);
  1374. end;
  1375. type
  1376. tlocalswitchchange = record
  1377. cs : tlocalswitch;
  1378. enable : boolean;
  1379. end;
  1380. plocalswitchchange = ^tlocalswitchchange;
  1381. function do_change_local_settings(var p : tnode;plsc : pointer) : foreachnoderesult;
  1382. begin
  1383. if plocalswitchchange(plsc)^.enable then
  1384. include(p.localswitches, plocalswitchchange(plsc)^.cs)
  1385. else
  1386. exclude(p.localswitches, plocalswitchchange(plsc)^.cs);
  1387. result:=fen_true;
  1388. end;
  1389. procedure node_change_local_switch(p : tnode;cs : tlocalswitch;enable : boolean);
  1390. var
  1391. lsc : tlocalswitchchange;
  1392. begin
  1393. lsc.cs:=cs;
  1394. lsc.enable:=enable;
  1395. foreachnodestatic(p,@do_change_local_settings,@lsc);
  1396. end;
  1397. function doshortbooleval(p : tnode) : Boolean;
  1398. begin
  1399. Result:=(p.nodetype in [orn,andn]) and ((anf_short_bool in taddnode(p).addnodeflags) or not(cs_full_boolean_eval in p.localswitches));
  1400. end;
  1401. function is_constintvalue(p: tnode; l: Tconstexprint): Boolean;
  1402. begin
  1403. Result:=is_constintnode(p) and (tordconstnode(p).value=l);
  1404. end;
  1405. function get_int_value(p: tnode): Tconstexprint;
  1406. begin
  1407. case p.nodetype of
  1408. ordconstn:
  1409. result:=tordconstnode(p).value;
  1410. pointerconstn:
  1411. result:=tpointerconstnode(p).value;
  1412. niln:
  1413. result:=0;
  1414. else
  1415. internalerror(2002080202);
  1416. end;
  1417. end;
  1418. function is_inlinefunction(p: tnode; i: tinlinenumber): Boolean;
  1419. begin
  1420. Result:=(p.nodetype=inlinen) and (tinlinenode(p).inlinenumber=i);
  1421. end;
  1422. { checks if p is a series of length(a) statments, if yes, they are returned
  1423. in a and the function returns true }
  1424. function GetStatements(p : tnode;var a : array of tstatementnode) : Boolean;
  1425. var
  1426. i: Integer;
  1427. begin
  1428. Result:=false;
  1429. for i:=0 to high(a) do
  1430. begin
  1431. if not(assigned(p)) or not(p.nodetype=statementn) then
  1432. exit;
  1433. a[i]:=tstatementnode(p);
  1434. p:=tstatementnode(p).right;
  1435. end;
  1436. Result:=true;
  1437. end;
  1438. function IsSingleStatement(p: tnode; var s: tnode): Boolean;
  1439. begin
  1440. Result:=false;
  1441. if assigned(p) then
  1442. case p.nodetype of
  1443. blockn:
  1444. Result:=IsSingleStatement(tblocknode(p).statements,s);
  1445. statementn:
  1446. if not(assigned(tstatementnode(p).next)) then
  1447. begin
  1448. Result:=true;
  1449. s:=tstatementnode(p).statement;
  1450. end;
  1451. inlinen,
  1452. assignn,
  1453. calln:
  1454. begin
  1455. s:=p;
  1456. Result:=true;
  1457. end
  1458. else
  1459. ;
  1460. end;
  1461. end;
  1462. { gets the last statement in a sequence of statements/blocks }
  1463. function GetLastStatement(p : tnode) : tnode;
  1464. var
  1465. i: Integer;
  1466. begin
  1467. Result:=p;
  1468. while assigned(Result) do
  1469. begin
  1470. if Result.nodetype=statementn then
  1471. begin
  1472. if assigned(tstatementnode(Result).next) then
  1473. Result:=tstatementnode(Result).next
  1474. else if tstatementnode(Result).statement.nodetype=blockn then
  1475. Result:=tblocknode(tstatementnode(Result).left).statements
  1476. else
  1477. begin
  1478. Result:=tstatementnode(Result).statement;
  1479. exit;
  1480. end;
  1481. end
  1482. else if Result.nodetype=blockn then
  1483. Result:=tblocknode(Result).statements
  1484. else
  1485. exit;
  1486. end;
  1487. end;
  1488. function MatchAndTransformNodesCommutative(n1,n2 : tnode;matchproc : TMatchProc2;transformproc : TTransformProc2;var res : tnode) : Boolean;
  1489. begin
  1490. res:=nil;
  1491. result:=true;
  1492. if matchproc(n1,n2) then
  1493. res:=transformproc(n1,n2)
  1494. else if matchproc(n2,n1) then
  1495. res:=transformproc(n2,n1)
  1496. else
  1497. result:=false;
  1498. end;
  1499. function MatchAndTransformNodesCommutative(n1,n2,n3,n4 : tnode;matchproc : TMatchProc4;transformproc : TTransformProc4;var res : tnode) : Boolean;
  1500. begin
  1501. res:=nil;
  1502. result:=true;
  1503. if matchproc(n1,n2,n3,n4) then
  1504. res:=transformproc(n1,n2,n3,n4)
  1505. else if matchproc(n1,n2,n4,n3) then
  1506. res:=transformproc(n1,n2,n4,n3)
  1507. else if matchproc(n2,n1,n3,n4) then
  1508. res:=transformproc(n2,n1,n3,n4)
  1509. else if matchproc(n2,n1,n4,n3) then
  1510. res:=transformproc(n2,n1,n4,n3)
  1511. else if matchproc(n3,n4,n1,n2) then
  1512. res:=transformproc(n3,n4,n1,n2)
  1513. else if matchproc(n4,n3,n1,n2) then
  1514. res:=transformproc(n4,n3,n1,n2)
  1515. else if matchproc(n3,n4,n2,n1) then
  1516. res:=transformproc(n3,n4,n2,n1)
  1517. else if matchproc(n4,n3,n2,n1) then
  1518. res:=transformproc(n4,n3,n2,n1)
  1519. else
  1520. result:=false;
  1521. end;
  1522. function _node_reset_pass1_write(var n: tnode; arg: pointer): foreachnoderesult;
  1523. begin
  1524. Result := fen_false;
  1525. n.flags := n.flags - [nf_write,nf_modify];
  1526. n.transientflags := n.transientflags - [tnf_pass1_done];
  1527. if n.nodetype = assignn then
  1528. begin
  1529. { Force re-evaluation of assignments so nf_modify and nf_write
  1530. flags are correctly set. }
  1531. n.resultdef := nil;
  1532. Result := fen_true;
  1533. end;
  1534. end;
  1535. procedure node_reset_pass1_write(n: tnode);
  1536. begin
  1537. foreachnodestatic(n,@_node_reset_pass1_write,nil);
  1538. end;
  1539. function node_in_list(var n: tnode; arg: pointer): foreachnoderesult;
  1540. begin
  1541. if (n.nodetype in PNodeTypeSet(arg)^) then
  1542. result := fen_norecurse_true
  1543. else
  1544. result := fen_false;
  1545. end;
  1546. function has_node_of_type(n: TNode; TypeList: TNodeTypeSet): Boolean;
  1547. begin
  1548. Result := foreachnodestatic(n, @node_in_list, @TypeList);
  1549. end;
  1550. function node_not_zero(n: tnode): Boolean;
  1551. begin
  1552. result:=(is_constintnode(n) and (get_int_value(n)<>0)) or
  1553. ((n.resultdef.typ=orddef) and ((torddef(n.resultdef).low>0) or (torddef(n.resultdef).high<0))) or
  1554. ((n.nodetype=typeconvn) and (ttypeconvnode(n).convtype=tc_int_2_int) and (n.resultdef.size>=ttypeconvnode(n).resultdef.size) and node_not_zero(ttypeconvnode(n).left)) or
  1555. ((n.nodetype=orn) and (node_not_zero(taddnode(n).left) or node_not_zero(taddnode(n).right)));
  1556. end;
  1557. end.