optcse.pas 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. {
  2. Common subexpression elimination on base blocks
  3. Copyright (c) 2005-2012 by Florian Klaempfl
  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 optcse;
  18. {$i fpcdefs.inc}
  19. { $define csedebug}
  20. { $define csestats}
  21. interface
  22. uses
  23. node;
  24. {
  25. the function creates non optimal code so far:
  26. - call para nodes are cse barriers because they can be reordered and thus the
  27. temp. creation could be done too late
  28. - the cse knows nothing about register pressure. In case of high register pressure, cse might
  29. have a negative impact
  30. - the list of cseinvariant node types and inline numbers is not complete yet
  31. Further, it could be done probably in a faster way though the complexity can't probably not reduced
  32. }
  33. function do_optcse(var rootnode : tnode) : tnode;
  34. implementation
  35. uses
  36. globtype,globals,
  37. cutils,cclasses,
  38. nutils,
  39. nbas,nld,ninl,ncal,nadd,nmem,
  40. pass_1,
  41. symconst,symdef,symsym,
  42. defutil,
  43. optbase;
  44. const
  45. cseinvariant : set of tnodetype = [addn,muln,subn,divn,slashn,modn,andn,orn,xorn,notn,vecn,
  46. derefn,equaln,unequaln,ltn,gtn,lten,gten,typeconvn,subscriptn,
  47. inn,symdifn,shrn,shln,ordconstn,realconstn,unaryminusn,pointerconstn,stringconstn,setconstn,niln,
  48. setelementn,{arrayconstructorn,arrayconstructorrangen,}
  49. isn,asn,starstarn,nothingn,temprefn,loadparentfpn {,callparan},assignn,addrn];
  50. function searchsubdomain(var n:tnode; arg: pointer) : foreachnoderesult;
  51. begin
  52. if (n.nodetype in cseinvariant) or
  53. ((n.nodetype=inlinen) and
  54. (tinlinenode(n).inlinenumber in [in_length_x,in_assigned_x,in_sqr_real,in_sqrt_real,in_sin_real,in_cos_real,in_abs_long,
  55. in_abs_real,in_exp_real,in_ln_real,in_pi_real,in_popcnt_x,in_arctan_real,in_round_real,in_trunc_real,
  56. { cse on fma will still not work because it would require proper handling of call nodes
  57. with more than one parameter }
  58. in_fma_single,in_fma_double,in_fma_extended,in_fma_float128])
  59. ) or
  60. (tinlinenode(n).inlinenumber >= 200) or
  61. ((n.nodetype=callparan) and not(assigned(tcallparanode(n).right))) or
  62. ((n.nodetype=loadn) and
  63. not((tloadnode(n).symtableentry.typ in [staticvarsym,localvarsym,paravarsym]) and
  64. (vo_volatile in tabstractvarsym(tloadnode(n).symtableentry).varoptions))
  65. ) then
  66. result:=fen_true
  67. else
  68. begin
  69. pboolean(arg)^:=false;
  70. result:=fen_norecurse_true;
  71. end;
  72. end;
  73. type
  74. tlists = record
  75. nodelist : tfplist;
  76. locationlist : tfplist;
  77. equalto : tfplist;
  78. refs : tfplist;
  79. avail : TDFASet;
  80. end;
  81. plists = ^tlists;
  82. { collectnodes needs the address of itself to call foreachnodestatic,
  83. so we need a wrapper because @<func> inside <func doesn't work }
  84. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;forward;
  85. function collectnodes2(var n:tnode; arg: pointer) : foreachnoderesult;
  86. begin
  87. result:=collectnodes(n,arg);
  88. end;
  89. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;
  90. { when compiling a tree like
  91. and
  92. / \
  93. and C
  94. / \
  95. A B
  96. all expressions of B are available during evaluation of C. However considerung the whole expression,
  97. values of B and C might not be available due to short boolean evaluation.
  98. So recurseintobooleanchain detectes such chained and/or expressions and makes sub-expressions of B
  99. available during the evaluation of C
  100. firstleftend is later used to remove all sub expressions of B and C by storing the expression count
  101. in the cse table after handling A
  102. }
  103. var
  104. firstleftend : longint;
  105. procedure recurseintobooleanchain(t : tnodetype;n : tnode);
  106. begin
  107. if (tbinarynode(n).left.nodetype=t) and is_boolean(tbinarynode(n).left.resultdef) then
  108. recurseintobooleanchain(t,tbinarynode(n).left)
  109. else
  110. foreachnodestatic(pm_postprocess,tbinarynode(n).left,@collectnodes2,arg);
  111. firstleftend:=min(plists(arg)^.nodelist.count,firstleftend);
  112. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@collectnodes2,arg);
  113. end;
  114. var
  115. i : longint;
  116. begin
  117. result:=fen_false;
  118. { don't add the tree below an untyped const parameter: there is
  119. no information available that this kind of tree actually needs
  120. to be addresable, this could be improved }
  121. if ((n.nodetype=callparan) and
  122. (tcallparanode(n).left.resultdef.typ=formaldef) and
  123. (tcallparanode(n).parasym.varspez=vs_const)) then
  124. begin
  125. result:=fen_norecurse_false;
  126. exit;
  127. end;
  128. if
  129. { node possible to add? }
  130. assigned(n.resultdef) and
  131. (
  132. { regable expressions }
  133. (actualtargetnode(@n)^.flags*[nf_write,nf_modify,nf_address_taken]=[]) and
  134. ((((tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable or tstoreddef(n.resultdef).is_const_intregable) and
  135. { is_int/fpuregable allows arrays and records to be in registers, cse cannot handle this }
  136. (not(n.resultdef.typ in [arraydef,recorddef]))) or is_dynamic_array(n.resultdef)) and
  137. { same for voiddef }
  138. not(is_void(n.resultdef)) and
  139. { adding tempref and callpara nodes itself is worthless but
  140. their complexity is probably <= 1 anyways
  141. neither add setelementn nodes because the compiler sometimes depends on the fact
  142. that a certain node stays a setelementn, this does not hurt either because
  143. setelementn nodes itself generate no real code (except moving data into register) }
  144. not(n.nodetype in [temprefn,callparan,setelementn]) and
  145. { node worth to add?
  146. We consider almost every node because even loading a variables from
  147. a register instead of memory is more beneficial. This behaviour should
  148. not increase register pressure because if a variable is already
  149. in a register, the reg. allocator can merge the nodes. If a variable
  150. is loaded from memory, loading this variable and spilling another register
  151. should not add a speed penalty.
  152. }
  153. {
  154. load nodes are not considered if they load para or local symbols from the
  155. current stack frame, those are in registers anyways if possible
  156. }
  157. (not(actualtargetnode(@n)^.nodetype=loadn) or
  158. not(tloadnode(actualtargetnode(@n)^).symtableentry.typ in [paravarsym,localvarsym,staticvarsym]) or
  159. { apply cse on non-regable variables }
  160. ((tloadnode(actualtargetnode(@n)^).symtableentry.typ in [paravarsym,localvarsym,staticvarsym]) and
  161. not(tabstractvarsym(tloadnode(actualtargetnode(@n)^).symtableentry).is_regvar(false)) and
  162. not(vo_volatile in tabstractvarsym(tloadnode(actualtargetnode(@n)^).symtableentry).varoptions)) or
  163. (node_complexity(n)>1)
  164. ) and
  165. {
  166. Const nodes however are only considered if their complexity is >1
  167. This might be the case for the risc architectures if they need
  168. more than one instruction to load this particular value
  169. }
  170. (not(is_constnode(n)) or (node_complexity(n)>1)))
  171. {$if not(defined(i386)) and not(defined(i8086))}
  172. or
  173. { store reference of expression? }
  174. { loading the address of a global symbol takes typically more than
  175. one instruction on every platform except i8086/i386
  176. so consider in this case loading the address of the data
  177. }
  178. (((n.resultdef.typ in [arraydef,recorddef]) or is_object(n.resultdef)) and not(is_dynamic_array(n.resultdef)) and
  179. (n.nodetype=loadn) and
  180. (tloadnode(n).symtableentry.typ=staticvarsym)
  181. )
  182. {$endif not(defined(i386)) and not(defined(i8086))}
  183. ) then
  184. begin
  185. plists(arg)^.nodelist.Add(n);
  186. plists(arg)^.locationlist.Add(@n);
  187. plists(arg)^.refs.Add(nil);
  188. plists(arg)^.equalto.Add(pointer(-1));
  189. DFASetInclude(plists(arg)^.avail,plists(arg)^.nodelist.count-1);
  190. for i:=0 to plists(arg)^.nodelist.count-2 do
  191. begin
  192. if tnode(plists(arg)^.nodelist[i]).isequal(n) and DFASetIn(plists(arg)^.avail,i) then
  193. begin
  194. { use always the first occurence }
  195. if plists(arg)^.equalto[i]<>pointer(-1) then
  196. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=plists(arg)^.equalto[i]
  197. else
  198. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=pointer(ptrint(i));
  199. plists(arg)^.refs[i]:=pointer(plists(arg)^.refs[i])+1;
  200. { tree has been found, no need to search further,
  201. sub-trees have been added by the first occurence of
  202. the tree already }
  203. result:=fen_norecurse_false;
  204. break;
  205. end;
  206. end;
  207. end;
  208. { boolean and/or require a special handling: after evaluating the and/or node,
  209. the expressions of the right side might not be available due to short boolean
  210. evaluation, so after handling the right side, mark those expressions
  211. as unavailable }
  212. if (n.nodetype in [orn,andn]) and is_boolean(taddnode(n).left.resultdef) then
  213. begin
  214. firstleftend:=high(longint);
  215. recurseintobooleanchain(n.nodetype,n);
  216. for i:=firstleftend to plists(arg)^.nodelist.count-1 do
  217. DFASetExclude(plists(arg)^.avail,i);
  218. result:=fen_norecurse_false;
  219. end;
  220. {$ifdef cpuhighleveltarget}
  221. { The high level targets use the functionality from ncgnstld for
  222. nested accesses, and that one stores the complete location of the
  223. nested variable in tloadnode.left rather than only the location of
  224. the parent context containing it. This causes problems with the
  225. CSE in case the nested variable is used as an lvalue, so disable
  226. CSE in that case
  227. }
  228. if (n.nodetype=loadn) and assigned(tloadnode(n).left) then
  229. result:=fen_norecurse_false;
  230. {$endif}
  231. end;
  232. function searchcsedomain(var n: tnode; arg: pointer) : foreachnoderesult;
  233. var
  234. csedomain : boolean;
  235. lists : tlists;
  236. templist : tfplist;
  237. i : longint;
  238. def : tstoreddef;
  239. nodes : tblocknode;
  240. creates,
  241. statements : tstatementnode;
  242. hp : ttempcreatenode;
  243. addrstored : boolean;
  244. hp2 : tnode;
  245. begin
  246. result:=fen_false;
  247. nodes:=nil;
  248. if n.nodetype in cseinvariant then
  249. begin
  250. csedomain:=true;
  251. foreachnodestatic(pm_postprocess,n,@searchsubdomain,@csedomain);
  252. if not(csedomain) then
  253. begin
  254. { try to transform the tree to get better cse domains, consider:
  255. +
  256. / \
  257. + C
  258. / \
  259. A B
  260. if A is not cse'able but B and C are, then the compiler cannot do cse so the tree is transformed into
  261. +
  262. / \
  263. A +
  264. / \
  265. B C
  266. Because A could be another tree of this kind, the whole process is done in a while loop
  267. }
  268. if (n.nodetype in [andn,orn,addn,muln]) and
  269. (n.nodetype=tbinarynode(n).left.nodetype) and
  270. { do is optimizations only for integers, reals (no currency!), vectors, sets or booleans }
  271. (is_integer(n.resultdef) or is_real(n.resultdef) or is_vector(n.resultdef) or is_set(n.resultdef) or
  272. is_boolean(n.resultdef)) and
  273. { either if fastmath is on }
  274. ((cs_opt_fastmath in current_settings.optimizerswitches) or
  275. { or for the logical operators, they cannot overflow }
  276. (n.nodetype in [andn,orn]) or
  277. { or for integers if range checking is off }
  278. ((is_integer(n.resultdef) and
  279. (n.localswitches*[cs_check_range,cs_check_overflow]=[]) and
  280. (tbinarynode(n).left.localswitches*[cs_check_range,cs_check_overflow]=[]))) or
  281. { for sets, we can do this always }
  282. (is_set(n.resultdef))
  283. ) then
  284. while (n.nodetype=tbinarynode(n).left.nodetype) and
  285. { the resulttypes of the operands we'll swap must be equal,
  286. required in case of a 32x32->64 multiplication, then we
  287. cannot swap out one of the 32 bit operands for a 64 bit one
  288. }
  289. (tbinarynode(tbinarynode(n).left).left.resultdef=tbinarynode(n).left.resultdef) and
  290. (tbinarynode(n).left.resultdef=tbinarynode(n).right.resultdef) do
  291. begin
  292. csedomain:=true;
  293. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@searchsubdomain,@csedomain);
  294. if csedomain then
  295. begin
  296. csedomain:=true;
  297. foreachnodestatic(pm_postprocess,tbinarynode(tbinarynode(n).left).right,@searchsubdomain,@csedomain);
  298. if csedomain then
  299. begin
  300. hp2:=tbinarynode(tbinarynode(n).left).left;
  301. tbinarynode(tbinarynode(n).left).left:=tbinarynode(tbinarynode(n).left).right;
  302. tbinarynode(tbinarynode(n).left).right:=tbinarynode(n).right;
  303. tbinarynode(n).right:=tbinarynode(n).left;
  304. tbinarynode(n).left:=hp2;
  305. { the transformed tree could result in new possibilities to fold constants
  306. so force a firstpass on the root node }
  307. exclude(tbinarynode(n).right.flags,nf_pass1_done);
  308. do_firstpass(tbinarynode(n).right);
  309. end
  310. else
  311. break;
  312. end
  313. else
  314. break;
  315. end;
  316. end
  317. else
  318. begin
  319. statements:=nil;
  320. result:=fen_norecurse_true;
  321. {$ifdef csedebug}
  322. writeln('============ cse domain ==================');
  323. printnode(output,n);
  324. writeln('Complexity: ',node_complexity(n));
  325. {$endif csedebug}
  326. lists.nodelist:=tfplist.create;
  327. lists.locationlist:=tfplist.create;
  328. lists.equalto:=tfplist.create;
  329. lists.refs:=tfplist.create;
  330. foreachnodestatic(pm_postprocess,n,@collectnodes,@lists);
  331. templist:=tfplist.create;
  332. templist.count:=lists.nodelist.count;
  333. { check all nodes if one is used more than once }
  334. for i:=0 to lists.nodelist.count-1 do
  335. begin
  336. { current node used more than once? }
  337. if assigned(lists.refs[i]) then
  338. begin
  339. if not(assigned(statements)) then
  340. begin
  341. nodes:=internalstatements(statements);
  342. addstatement(statements,internalstatements(creates));
  343. end;
  344. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  345. { we cannot handle register stored records or array in CSE yet
  346. but we can store their reference }
  347. addrstored:=((def.typ in [arraydef,recorddef]) or is_object(def)) and not(is_dynamic_array(def));
  348. if addrstored then
  349. templist[i]:=ctempcreatenode.create_value(getpointerdef(def),voidpointertype.size,tt_persistent,
  350. true,caddrnode.create_internal(tnode(lists.nodelist[i])))
  351. else
  352. templist[i]:=ctempcreatenode.create_value(def,def.size,tt_persistent,
  353. def.is_intregable or def.is_fpuregable or def.is_const_intregable,tnode(lists.nodelist[i]));
  354. { the value described by the temp. is immutable and the temp. can be always in register
  355. ttempcreatenode.create normally takes care of the register location but it does not
  356. know about immutability so it cannot take care of managed types }
  357. include(ttempcreatenode(templist[i]).tempinfo^.flags,ti_const);
  358. include(ttempcreatenode(templist[i]).tempinfo^.flags,ti_may_be_in_reg);
  359. { make debugging easier and set temp. location to the original location }
  360. tnode(templist[i]).fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  361. addstatement(creates,tnode(templist[i]));
  362. { make debugging easier and set temp. location to the original location }
  363. creates.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  364. hp:=ttempcreatenode(templist[i]);
  365. do_firstpass(tnode(hp));
  366. templist[i]:=hp;
  367. if addrstored then
  368. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[i])))
  369. else
  370. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[i]));
  371. { make debugging easier and set temp. location to the original location }
  372. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  373. do_firstpass(pnode(lists.locationlist[i])^);
  374. {$ifdef csedebug}
  375. printnode(output,statements);
  376. {$endif csedebug}
  377. end
  378. { current node reference to another node? }
  379. else if lists.equalto[i]<>pointer(-1) then
  380. begin
  381. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  382. { we cannot handle register stored records or array in CSE yet
  383. but we can store their reference }
  384. addrstored:=((def.typ in [arraydef,recorddef]) or is_object(def)) and not(is_dynamic_array(def));
  385. {$if defined(csedebug) or defined(csestats)}
  386. writeln;
  387. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  388. writeln('Complexity: ',node_complexity(tnode(lists.nodelist[i])),' Node ',i,' equals Node ',ptrint(lists.equalto[i]));
  389. printnode(output,tnode(lists.nodelist[i]));
  390. printnode(output,tnode(lists.nodelist[ptrint(lists.equalto[i])]));
  391. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  392. writeln;
  393. {$endif defined(csedebug) or defined(csestats)}
  394. templist[i]:=templist[ptrint(lists.equalto[i])];
  395. if addrstored then
  396. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])])))
  397. else
  398. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])]));
  399. { make debugging easier and set temp. location to the original location }
  400. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  401. do_firstpass(pnode(lists.locationlist[i])^);
  402. end;
  403. end;
  404. { clean up unused trees }
  405. for i:=0 to lists.nodelist.count-1 do
  406. if lists.equalto[i]<>pointer(-1) then
  407. tnode(lists.nodelist[i]).free;
  408. {$ifdef csedebug}
  409. writeln('nodes: ',lists.nodelist.count);
  410. writeln('==========================================');
  411. {$endif csedebug}
  412. lists.nodelist.free;
  413. lists.locationlist.free;
  414. lists.equalto.free;
  415. lists.refs.free;
  416. templist.free;
  417. if assigned(statements) then
  418. begin
  419. { call para nodes need a special handling because
  420. they can be only children nodes of call nodes
  421. so the initialization code is inserted below the
  422. call para node
  423. }
  424. if n.nodetype=callparan then
  425. begin
  426. addstatement(statements,tcallparanode(n).left);
  427. tcallparanode(n).left:=nodes;
  428. do_firstpass(tcallparanode(n).left);
  429. end
  430. else
  431. begin
  432. addstatement(statements,n);
  433. n:=nodes;
  434. do_firstpass(n);
  435. end;
  436. {$ifdef csedebug}
  437. printnode(output,nodes);
  438. {$endif csedebug}
  439. end;
  440. end
  441. end;
  442. end;
  443. function do_optcse(var rootnode : tnode) : tnode;
  444. begin
  445. {$ifdef csedebug}
  446. writeln('====================================================================================');
  447. writeln('CSE optimization pass started');
  448. writeln('====================================================================================');
  449. printnode(rootnode);
  450. writeln('====================================================================================');
  451. writeln;
  452. {$endif csedebug}
  453. foreachnodestatic(pm_postprocess,rootnode,@searchcsedomain,nil);
  454. result:=nil;
  455. end;
  456. end.