optcse.pas 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. cclasses,
  38. verbose,
  39. nutils,
  40. procinfo,
  41. nbas,nld,ninl,ncal,ncnv,nadd,nmem,
  42. pass_1,
  43. symconst,symtype,symdef,symsym,
  44. defutil,
  45. optbase;
  46. const
  47. cseinvariant : set of tnodetype = [addn,muln,subn,divn,slashn,modn,andn,orn,xorn,notn,vecn,
  48. derefn,equaln,unequaln,ltn,gtn,lten,gten,typeconvn,subscriptn,
  49. inn,symdifn,shrn,shln,ordconstn,realconstn,unaryminusn,pointerconstn,stringconstn,setconstn,niln,
  50. setelementn,{arrayconstructorn,arrayconstructorrangen,}
  51. isn,asn,starstarn,nothingn,temprefn,loadparentfpn {,callparan},assignn];
  52. function searchsubdomain(var n:tnode; arg: pointer) : foreachnoderesult;
  53. begin
  54. if (n.nodetype in cseinvariant) or
  55. ((n.nodetype=inlinen) and
  56. (tinlinenode(n).inlinenumber in [in_assigned_x])
  57. ) or
  58. ((n.nodetype=callparan) and not(assigned(tcallparanode(n).right))) or
  59. ((n.nodetype=loadn) and
  60. not((tloadnode(n).symtableentry.typ in [staticvarsym,localvarsym,paravarsym]) and
  61. (vo_volatile in tabstractvarsym(tloadnode(n).symtableentry).varoptions))
  62. ) then
  63. result:=fen_true
  64. else
  65. begin
  66. pboolean(arg)^:=false;
  67. result:=fen_norecurse_true;
  68. end;
  69. end;
  70. type
  71. tlists = record
  72. nodelist : tfplist;
  73. locationlist : tfplist;
  74. equalto : tfplist;
  75. refs : tfplist;
  76. avail : TDFASet;
  77. end;
  78. plists = ^tlists;
  79. { collectnodes needs the address of itself to call foreachnodestatic,
  80. so we need a wrapper because @<func> inside <func doesn't work }
  81. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;forward;
  82. function collectnodes2(var n:tnode; arg: pointer) : foreachnoderesult;
  83. begin
  84. result:=collectnodes(n,arg);
  85. end;
  86. function collectnodes(var n:tnode; arg: pointer) : foreachnoderesult;
  87. var
  88. i,j : longint;
  89. begin
  90. result:=fen_false;
  91. { don't add the tree below an untyped const parameter: there is
  92. no information available that this kind of tree actually needs
  93. to be addresable, this could be improved }
  94. if ((n.nodetype=callparan) and
  95. (tcallparanode(n).left.resultdef.typ=formaldef) and
  96. (tcallparanode(n).parasym.varspez=vs_const)) then
  97. begin
  98. result:=fen_norecurse_false;
  99. exit;
  100. end;
  101. if
  102. { node possible to add? }
  103. assigned(n.resultdef) and
  104. (
  105. { regable expressions }
  106. (n.actualtargetnode.flags*[nf_write,nf_modify]=[]) and
  107. ((tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable) and
  108. { is_int/fpuregable allows arrays and records to be in registers, cse cannot handle this }
  109. (not(n.resultdef.typ in [arraydef,recorddef])) and
  110. { same for voiddef }
  111. not(is_void(n.resultdef)) and
  112. { adding tempref and callpara nodes itself is worthless but
  113. their complexity is probably <= 1 anyways }
  114. not(n.nodetype in [temprefn,callparan]) and
  115. { node worth to add?
  116. We consider almost every node because even loading a variables from
  117. a register instead of memory is more beneficial. This behaviour should
  118. not increase register pressure because if a variable is already
  119. in a register, the reg. allocator can merge the nodes. If a variable
  120. is loaded from memory, loading this variable and spilling another register
  121. should not add a speed penalty.
  122. }
  123. {
  124. load nodes are not considered if they load para or local symbols from the
  125. current stack frame, those are in registers anyways if possible
  126. }
  127. (not(n.nodetype=loadn) or
  128. not(tloadnode(n).symtableentry.typ in [paravarsym,localvarsym]) or
  129. (node_complexity(n)>1)
  130. ) and
  131. {
  132. Const nodes however are only considered if their complexity is >1
  133. This might be the case for the risc architectures if they need
  134. more than one instruction to load this particular value
  135. }
  136. (not(is_constnode(n)) or (node_complexity(n)>1)))
  137. {$ifndef x86}
  138. or
  139. { store reference of expression? }
  140. { loading the address of a global symbol takes typically more than
  141. one instruction on every platform except x86
  142. so consider in this case loading the address of the data
  143. }
  144. (((n.resultdef.typ in [arraydef,recorddef]) or is_object(n.resultdef)) and
  145. (n.nodetype=loadn) and
  146. (tloadnode(n).symtableentry.typ=staticvarsym)
  147. )
  148. {$endif x86}
  149. ) then
  150. begin
  151. plists(arg)^.nodelist.Add(n);
  152. plists(arg)^.locationlist.Add(@n);
  153. plists(arg)^.refs.Add(nil);
  154. plists(arg)^.equalto.Add(pointer(-1));
  155. DFASetInclude(plists(arg)^.avail,plists(arg)^.nodelist.count-1);
  156. for i:=0 to plists(arg)^.nodelist.count-2 do
  157. begin
  158. if tnode(plists(arg)^.nodelist[i]).isequal(n) and DFASetIn(plists(arg)^.avail,i) then
  159. begin
  160. { use always the first occurence }
  161. if plists(arg)^.equalto[i]<>pointer(-1) then
  162. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=plists(arg)^.equalto[i]
  163. else
  164. plists(arg)^.equalto[plists(arg)^.nodelist.count-1]:=pointer(ptrint(i));
  165. plists(arg)^.refs[i]:=pointer(plists(arg)^.refs[i])+1;
  166. break;
  167. end;
  168. end;
  169. { boolean and/or require a special handling: after evaluating the and/or node,
  170. the expressions of the right side might not be available due to short boolean
  171. evaluation, so after handling the right side, mark those expressions
  172. as unavailable }
  173. if (n.nodetype in [orn,andn]) and is_boolean(taddnode(n).left.resultdef) then
  174. begin
  175. foreachnodestatic(pm_postprocess,taddnode(n).left,@collectnodes2,arg);
  176. j:=plists(arg)^.nodelist.count;
  177. foreachnodestatic(pm_postprocess,taddnode(n).right,@collectnodes2,arg);
  178. for i:=j to plists(arg)^.nodelist.count-1 do
  179. DFASetExclude(plists(arg)^.avail,i);
  180. result:=fen_norecurse_false;
  181. end;
  182. end;
  183. end;
  184. function searchcsedomain(var n: tnode; arg: pointer) : foreachnoderesult;
  185. var
  186. csedomain : boolean;
  187. lists : tlists;
  188. templist : tfplist;
  189. i : longint;
  190. def : tstoreddef;
  191. nodes : tblocknode;
  192. creates,
  193. statements : tstatementnode;
  194. hp : ttempcreatenode;
  195. addrstored : boolean;
  196. hp2 : tnode;
  197. begin
  198. result:=fen_false;
  199. if n.nodetype in cseinvariant then
  200. begin
  201. csedomain:=true;
  202. foreachnodestatic(pm_postprocess,n,@searchsubdomain,@csedomain);
  203. if not(csedomain) then
  204. begin
  205. { try to transform the tree to get better cse domains, consider:
  206. +
  207. / \
  208. + C
  209. / \
  210. A B
  211. if A is not cse'able but B and C are, then the compiler cannot do cse so the tree is transformed into
  212. +
  213. / \
  214. A +
  215. / \
  216. B C
  217. Because A could be another tree of this kind, the whole process is done in a while loop
  218. }
  219. if (n.nodetype in [andn,orn,addn,muln]) and
  220. (n.nodetype=tbinarynode(n).left.nodetype) and
  221. { do is optimizations only for integers, reals (no currency!), vectors, sets or booleans }
  222. (is_integer(n.resultdef) or is_real(n.resultdef) or is_vector(n.resultdef) or is_set(n.resultdef) or
  223. is_boolean(n.resultdef)) and
  224. { either if fastmath is on }
  225. ((cs_opt_fastmath in current_settings.optimizerswitches) or
  226. { or for the logical operators, they cannot overflow }
  227. (n.nodetype in [andn,orn]) or
  228. { or for integers if range checking is off }
  229. ((is_integer(n.resultdef) and
  230. (n.localswitches*[cs_check_range,cs_check_overflow]=[]) and
  231. (tbinarynode(n).left.localswitches*[cs_check_range,cs_check_overflow]=[]))) or
  232. { for sets, we can do this always }
  233. (is_set(n.resultdef))
  234. ) then
  235. while n.nodetype=tbinarynode(n).left.nodetype do
  236. begin
  237. csedomain:=true;
  238. foreachnodestatic(pm_postprocess,tbinarynode(n).right,@searchsubdomain,@csedomain);
  239. if csedomain then
  240. begin
  241. csedomain:=true;
  242. foreachnodestatic(pm_postprocess,tbinarynode(tbinarynode(n).left).right,@searchsubdomain,@csedomain);
  243. if csedomain then
  244. begin
  245. hp2:=tbinarynode(tbinarynode(n).left).left;
  246. tbinarynode(tbinarynode(n).left).left:=tbinarynode(tbinarynode(n).left).right;
  247. tbinarynode(tbinarynode(n).left).right:=tbinarynode(n).right;
  248. tbinarynode(n).right:=tbinarynode(n).left;
  249. tbinarynode(n).left:=hp2;
  250. { the transformed tree could result in new possibilities to fold constants
  251. so force a firstpass on the root node }
  252. exclude(tbinarynode(n).right.flags,nf_pass1_done);
  253. do_firstpass(tbinarynode(n).right);
  254. end
  255. else
  256. break;
  257. end
  258. else
  259. break;
  260. end;
  261. end
  262. else
  263. begin
  264. statements:=nil;
  265. result:=fen_norecurse_true;
  266. {$ifdef csedebug}
  267. writeln('============ cse domain ==================');
  268. printnode(output,n);
  269. writeln('Complexity: ',node_complexity(n));
  270. {$endif csedebug}
  271. lists.nodelist:=tfplist.create;
  272. lists.locationlist:=tfplist.create;
  273. lists.equalto:=tfplist.create;
  274. lists.refs:=tfplist.create;
  275. foreachnodestatic(pm_postprocess,n,@collectnodes,@lists);
  276. templist:=tfplist.create;
  277. templist.count:=lists.nodelist.count;
  278. { check all nodes if one is used more than once }
  279. for i:=0 to lists.nodelist.count-1 do
  280. begin
  281. { current node used more than once? }
  282. if assigned(lists.refs[i]) then
  283. begin
  284. if not(assigned(statements)) then
  285. begin
  286. nodes:=internalstatements(statements);
  287. addstatement(statements,internalstatements(creates));
  288. end;
  289. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  290. { we cannot handle register stored records or array in CSE yet
  291. but we can store their reference }
  292. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  293. if addrstored then
  294. templist[i]:=ctempcreatenode.create_value(getpointerdef(def),voidpointertype.size,tt_persistent,
  295. true,caddrnode.create(tnode(lists.nodelist[i])))
  296. else
  297. templist[i]:=ctempcreatenode.create_value(def,def.size,tt_persistent,
  298. def.is_intregable or def.is_fpuregable,tnode(lists.nodelist[i]));
  299. { make debugging easier and set temp. location to the original location }
  300. tnode(templist[i]).fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  301. addstatement(creates,tnode(templist[i]));
  302. { make debugging easier and set temp. location to the original location }
  303. creates.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  304. hp:=ttempcreatenode(templist[i]);
  305. do_firstpass(tnode(hp));
  306. templist[i]:=hp;
  307. if addrstored then
  308. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[i])))
  309. else
  310. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[i]));
  311. { make debugging easier and set temp. location to the original location }
  312. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  313. do_firstpass(pnode(lists.locationlist[i])^);
  314. {$ifdef csedebug}
  315. printnode(output,statements);
  316. {$endif csedebug}
  317. end
  318. { current node reference to another node? }
  319. else if lists.equalto[i]<>pointer(-1) then
  320. begin
  321. def:=tstoreddef(tnode(lists.nodelist[i]).resultdef);
  322. { we cannot handle register stored records or array in CSE yet
  323. but we can store their reference }
  324. addrstored:=(def.typ in [arraydef,recorddef]) or is_object(def);
  325. {$if defined(csedebug) or defined(csestats)}
  326. writeln;
  327. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  328. writeln('Complexity: ',node_complexity(tnode(lists.nodelist[i])),' Node ',i,' equals Node ',ptrint(lists.equalto[i]));
  329. printnode(output,tnode(lists.nodelist[i]));
  330. printnode(output,tnode(lists.nodelist[ptrint(lists.equalto[i])]));
  331. writeln('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
  332. writeln;
  333. {$endif defined(csedebug) or defined(csestats)}
  334. templist[i]:=templist[ptrint(lists.equalto[i])];
  335. if addrstored then
  336. pnode(lists.locationlist[i])^:=cderefnode.Create(ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])])))
  337. else
  338. pnode(lists.locationlist[i])^:=ctemprefnode.create(ttempcreatenode(templist[ptrint(lists.equalto[i])]));
  339. { make debugging easier and set temp. location to the original location }
  340. pnode(lists.locationlist[i])^.fileinfo:=tnode(lists.nodelist[i]).fileinfo;
  341. do_firstpass(pnode(lists.locationlist[i])^);
  342. end;
  343. end;
  344. { clean up unused trees }
  345. for i:=0 to lists.nodelist.count-1 do
  346. if lists.equalto[i]<>pointer(-1) then
  347. tnode(lists.nodelist[i]).free;
  348. {$ifdef csedebug}
  349. writeln('nodes: ',lists.nodelist.count);
  350. writeln('==========================================');
  351. {$endif csedebug}
  352. lists.nodelist.free;
  353. lists.locationlist.free;
  354. lists.equalto.free;
  355. lists.refs.free;
  356. templist.free;
  357. if assigned(statements) then
  358. begin
  359. { call para nodes need a special handling because
  360. they can be only children nodes of call nodes
  361. so the initialization code is inserted below the
  362. call para node
  363. }
  364. if n.nodetype=callparan then
  365. begin
  366. addstatement(statements,tcallparanode(n).left);
  367. tcallparanode(n).left:=nodes;
  368. do_firstpass(tcallparanode(n).left);
  369. end
  370. else
  371. begin
  372. addstatement(statements,n);
  373. n:=nodes;
  374. do_firstpass(n);
  375. end;
  376. {$ifdef csedebug}
  377. printnode(output,nodes);
  378. {$endif csedebug}
  379. end;
  380. end
  381. end;
  382. end;
  383. function do_optcse(var rootnode : tnode) : tnode;
  384. begin
  385. {$ifdef csedebug}
  386. writeln('====================================================================================');
  387. writeln('CSE optimization pass started');
  388. writeln('====================================================================================');
  389. printnode(rootnode);
  390. writeln('====================================================================================');
  391. writeln;
  392. {$endif csedebug}
  393. foreachnodestatic(pm_postprocess,rootnode,@searchcsedomain,nil);
  394. result:=nil;
  395. end;
  396. end.