optcse.pas 23 KB

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