optloop.pas 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. {
  2. Loop optimization
  3. Copyright (c) 2005 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 optloop;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. node;
  22. function unroll_loop(node : tnode) : tnode;
  23. function OptimizeInductionVariables(node : tnode) : boolean;
  24. implementation
  25. uses
  26. cutils,cclasses,
  27. globtype,globals,constexp,
  28. symdef,symsym,
  29. defutil,
  30. cpuinfo,
  31. nutils,
  32. nadd,nbas,nflw,ncon,ninl,ncal,nld,nmem,ncnv,
  33. ncgmem,
  34. pass_1,
  35. optbase,optutils,
  36. procinfo;
  37. var
  38. nodecount : aword;
  39. function donodecount(var n: tnode; arg: pointer): foreachnoderesult;
  40. begin
  41. inc(nodecount);
  42. result:=fen_false;
  43. end;
  44. { rough estimation how large the tree "node" is }
  45. function countnodes(node : tnode) : aword;
  46. begin
  47. nodecount:=0;
  48. foreachnodestatic(node,@donodecount,nil);
  49. result:=nodecount;
  50. end;
  51. function number_unrolls(node : tnode) : cardinal;
  52. begin
  53. {$ifdef i386}
  54. { multiply by 2 for CPUs with a long pipeline }
  55. if current_settings.cputype in [cpu_Pentium4] then
  56. number_unrolls:=60 div countnodes(node)
  57. else
  58. {$endif i386}
  59. number_unrolls:=30 div countnodes(node);
  60. if number_unrolls=0 then
  61. number_unrolls:=1;
  62. end;
  63. function unroll_loop(node : tnode) : tnode;
  64. var
  65. unrolls,i : cardinal;
  66. counts : qword;
  67. unrollstatement,newforstatement : tstatementnode;
  68. unrollblock : tblocknode;
  69. begin
  70. result:=nil;
  71. if (cs_opt_size in current_settings.optimizerswitches) then
  72. exit;
  73. if not(node.nodetype in [forn]) then
  74. exit;
  75. unrolls:=number_unrolls(tfornode(node).t2);
  76. if unrolls>1 then
  77. begin
  78. { number of executions known? }
  79. if (tfornode(node).right.nodetype=ordconstn) and (tfornode(node).t1.nodetype=ordconstn) then
  80. begin
  81. if lnf_backward in tfornode(node).loopflags then
  82. counts:=tordconstnode(tfornode(node).right).value-tordconstnode(tfornode(node).t1).value+1
  83. else
  84. counts:=tordconstnode(tfornode(node).t1).value-tordconstnode(tfornode(node).right).value+1;
  85. { don't unroll more than we need }
  86. if unrolls>counts then
  87. unrolls:=counts;
  88. { create block statement }
  89. unrollblock:=internalstatements(unrollstatement);
  90. { let's unroll (and rock of course) }
  91. for i:=1 to unrolls do
  92. begin
  93. { create and insert copy of the statement block }
  94. addstatement(unrollstatement,tfornode(node).t2.getcopy);
  95. { set and insert entry label? }
  96. if (counts mod unrolls<>0) and
  97. ((counts mod unrolls)=unrolls-i) then
  98. begin
  99. tfornode(node).entrylabel:=clabelnode.create(cnothingnode.create,tlabelsym.create('$optunrol'));
  100. addstatement(unrollstatement,tfornode(node).entrylabel);
  101. end;
  102. { for itself increases at the last iteration }
  103. if i<unrolls then
  104. begin
  105. { insert incrementation of counter var }
  106. addstatement(unrollstatement,
  107. geninlinenode(in_inc_x,false,ccallparanode.create(tfornode(node).left.getcopy,nil)));
  108. end;
  109. end;
  110. { can we get rid of the for statement? }
  111. if unrolls=counts then
  112. begin
  113. { create block statement }
  114. result:=internalstatements(newforstatement);
  115. { initial assignment }
  116. addstatement(newforstatement,cassignmentnode.create(
  117. tfornode(node).left.getcopy,tfornode(node).right.getcopy));
  118. addstatement(newforstatement,unrollblock);
  119. end;
  120. end
  121. else
  122. begin
  123. { unrolling is a little bit more tricky if we don't know the
  124. loop count at compile time, but the solution is to use a jump table
  125. which is indexed by "loop count mod unrolls" at run time and which
  126. jumps then at the appropriate place inside the loop. Because
  127. a module division is expensive, we can use only unroll counts dividable
  128. by 2 }
  129. case unrolls of
  130. 1..2:
  131. ;
  132. 3:
  133. unrolls:=2;
  134. 4..7:
  135. unrolls:=4;
  136. { unrolls>4 already make no sense imo, but who knows (FK) }
  137. 8..15:
  138. unrolls:=8;
  139. 16..31:
  140. unrolls:=16;
  141. 32..63:
  142. unrolls:=32;
  143. 64..$7fff:
  144. unrolls:=64;
  145. else
  146. exit;
  147. end;
  148. { we don't handle this yet }
  149. exit;
  150. end;
  151. if not(assigned(result)) then
  152. begin
  153. tfornode(node).t2.free;
  154. tfornode(node).t2:=unrollblock;
  155. end;
  156. end;
  157. end;
  158. var
  159. initcode,
  160. calccode,
  161. deletecode : tblocknode;
  162. initcodestatements,
  163. calccodestatements,
  164. deletecodestatements: tstatementnode;
  165. templist : tfplist;
  166. inductionexprs : tfplist;
  167. changedforloop,
  168. containsnestedforloop : boolean;
  169. function is_loop_invariant(loop : tnode;expr : tnode) : boolean;
  170. begin
  171. result:=is_constnode(expr);
  172. case expr.nodetype of
  173. loadn:
  174. begin
  175. if (pi_dfaavailable in current_procinfo.flags) and
  176. assigned(loop.optinfo) and
  177. assigned(expr.optinfo) then
  178. { no aliasing? }
  179. result:=not(tabstractvarsym(tloadnode(expr).symtableentry).addr_taken) and
  180. { no definition in the loop? }
  181. not(DFASetIn(loop.optinfo^.defsum,expr.optinfo^.index));
  182. end;
  183. vecn:
  184. begin
  185. result:=((tvecnode(expr).left.nodetype=loadn) or is_loop_invariant(loop,tvecnode(expr).left)) and
  186. is_loop_invariant(loop,tvecnode(expr).right);
  187. end;
  188. typeconvn:
  189. result:=is_loop_invariant(loop,ttypeconvnode(expr).left);
  190. end;
  191. end;
  192. { checks if the strength of n can be recuded, arg is the tforloop being considered }
  193. function dostrengthreductiontest(var n: tnode; arg: pointer): foreachnoderesult;
  194. function findpreviousstrengthreduction : boolean;
  195. var
  196. i : longint;
  197. begin
  198. result:=false;
  199. for i:=0 to inductionexprs.count-1 do
  200. begin
  201. { do we already maintain one expression? }
  202. if tnode(inductionexprs[i]).isequal(n) then
  203. begin
  204. n.free;
  205. case n.nodetype of
  206. muln:
  207. n:=ctemprefnode.create(ttempcreatenode(templist[i]));
  208. vecn:
  209. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(
  210. ttempcreatenode(templist[i]))),n.resultdef);
  211. else
  212. internalerror(200809211);
  213. end;
  214. result:=true;
  215. exit;
  216. end;
  217. end;
  218. end;
  219. procedure CreateNodes;
  220. begin
  221. if not assigned(initcode) then
  222. begin
  223. initcode:=internalstatements(initcodestatements);
  224. calccode:=internalstatements(calccodestatements);
  225. deletecode:=internalstatements(deletecodestatements);
  226. end;
  227. end;
  228. var
  229. tempnode : ttempcreatenode;
  230. dummy : longint;
  231. begin
  232. result:=fen_false;
  233. case n.nodetype of
  234. forn:
  235. { inform for loop search routine, that it needs to search more deeply }
  236. containsnestedforloop:=true;
  237. muln:
  238. begin
  239. if (taddnode(n).right.nodetype=loadn) and
  240. taddnode(n).right.isequal(tfornode(arg).left) and
  241. { plain read of the loop variable? }
  242. not(nf_write in taddnode(n).right.flags) and
  243. not(nf_modify in taddnode(n).right.flags) and
  244. is_loop_invariant(tfornode(arg),taddnode(n).left) and
  245. { for now, we can handle only constant lower borders }
  246. is_constnode(tfornode(arg).right) then
  247. taddnode(n).swapleftright;
  248. if (taddnode(n).left.nodetype=loadn) and
  249. taddnode(n).left.isequal(tfornode(arg).left) and
  250. { plain read of the loop variable? }
  251. not(nf_write in taddnode(n).left.flags) and
  252. not(nf_modify in taddnode(n).left.flags) and
  253. is_loop_invariant(tfornode(arg),taddnode(n).right) and
  254. { for now, we can handle only constant lower borders }
  255. is_constnode(tfornode(arg).right) then
  256. begin
  257. changedforloop:=true;
  258. { did we use the same expression before already? }
  259. if not(findpreviousstrengthreduction) then
  260. begin
  261. tempnode:=ctempcreatenode.create(n.resultdef,n.resultdef.size,tt_persistent,
  262. tstoreddef(n.resultdef).is_intregable or tstoreddef(n.resultdef).is_fpuregable);
  263. templist.Add(tempnode);
  264. inductionexprs.Add(n);
  265. CreateNodes;
  266. if lnf_backward in tfornode(arg).loopflags then
  267. addstatement(calccodestatements,
  268. geninlinenode(in_dec_x,false,
  269. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))))
  270. else
  271. addstatement(calccodestatements,
  272. geninlinenode(in_inc_x,false,
  273. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(taddnode(n).right.getcopy,nil))));
  274. addstatement(initcodestatements,tempnode);
  275. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  276. caddnode.create(muln,
  277. caddnode.create(subn,tfornode(arg).right.getcopy,cordconstnode.create(1,tfornode(arg).right.resultdef,false)),
  278. taddnode(n).right.getcopy)
  279. )
  280. );
  281. { finally replace the node by a temp. ref }
  282. n:=ctemprefnode.create(tempnode);
  283. { ... and add a temp. release node }
  284. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  285. end;
  286. { set types }
  287. do_firstpass(n);
  288. result:=fen_norecurse_false;
  289. end;
  290. end;
  291. vecn:
  292. begin
  293. { is the index the counter variable? }
  294. if not(is_special_array(tvecnode(n).left.resultdef)) and
  295. (tvecnode(n).right.isequal(tfornode(arg).left) or
  296. { fpc usually creates a type cast to access an array }
  297. ((tvecnode(n).right.nodetype=typeconvn) and
  298. ttypeconvnode(tvecnode(n).right).left.isequal(tfornode(arg).left)
  299. )
  300. ) and
  301. { plain read of the loop variable? }
  302. not(nf_write in tvecnode(n).right.flags) and
  303. not(nf_modify in tvecnode(n).right.flags) and
  304. { direct array access? }
  305. ((tvecnode(n).left.nodetype=loadn) or
  306. { ... or loop invariant expression? }
  307. is_loop_invariant(tfornode(arg),tvecnode(n).left)) and
  308. { removing the multiplication is only worth the
  309. effort if it's not a simple shift }
  310. not(ispowerof2(tcgvecnode(n).get_mul_size,dummy)) then
  311. begin
  312. changedforloop:=true;
  313. { did we use the same expression before already? }
  314. if not(findpreviousstrengthreduction) then
  315. begin
  316. tempnode:=ctempcreatenode.create(voidpointertype,voidpointertype.size,tt_persistent,true);
  317. templist.Add(tempnode);
  318. inductionexprs.Add(n);
  319. CreateNodes;
  320. if lnf_backward in tfornode(arg).loopflags then
  321. addstatement(calccodestatements,
  322. geninlinenode(in_dec_x,false,
  323. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  324. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))))
  325. else
  326. addstatement(calccodestatements,
  327. geninlinenode(in_inc_x,false,
  328. ccallparanode.create(ctemprefnode.create(tempnode),ccallparanode.create(
  329. cordconstnode.create(tcgvecnode(n).get_mul_size,tfornode(arg).right.resultdef,false),nil))));
  330. addstatement(initcodestatements,tempnode);
  331. addstatement(initcodestatements,cassignmentnode.create(ctemprefnode.create(tempnode),
  332. caddrnode.create(
  333. cvecnode.create(tvecnode(n).left.getcopy,tfornode(arg).right.getcopy)
  334. )
  335. ));
  336. { finally replace the node by a temp. ref }
  337. n:=ctypeconvnode.create_internal(cderefnode.create(ctemprefnode.create(tempnode)),n.resultdef);
  338. { ... and add a temp. release node }
  339. addstatement(deletecodestatements,ctempdeletenode.create(tempnode));
  340. end;
  341. { set types }
  342. do_firstpass(n);
  343. result:=fen_norecurse_false;
  344. end;
  345. end;
  346. end;
  347. end;
  348. function OptimizeInductionVariablesSingleForLoop(node : tnode) : tnode;
  349. var
  350. loopcode : tblocknode;
  351. loopcodestatements,
  352. newcodestatements : tstatementnode;
  353. fornode : tfornode;
  354. begin
  355. result:=nil;
  356. if node.nodetype<>forn then
  357. exit;
  358. templist:=TFPList.Create;
  359. inductionexprs:=TFPList.Create;
  360. initcode:=nil;
  361. calccode:=nil;
  362. deletecode:=nil;
  363. initcodestatements:=nil;
  364. calccodestatements:=nil;
  365. deletecodestatements:=nil;
  366. { find all expressions being candidates for strength reduction
  367. and replace them }
  368. foreachnodestatic(pm_postprocess,node,@dostrengthreductiontest,node);
  369. { clue everything together }
  370. if assigned(initcode) then
  371. begin
  372. do_firstpass(tnode(initcode));
  373. do_firstpass(tnode(calccode));
  374. do_firstpass(tnode(deletecode));
  375. { create a new for node, the old one will be released by the compiler }
  376. with tfornode(node) do
  377. begin
  378. fornode:=cfornode.create(left,right,t1,t2,lnf_backward in loopflags);
  379. left:=nil;
  380. right:=nil;
  381. t1:=nil;
  382. t2:=nil;
  383. end;
  384. node:=fornode;
  385. loopcode:=internalstatements(loopcodestatements);
  386. addstatement(loopcodestatements,calccode);
  387. addstatement(loopcodestatements,tfornode(node).t2);
  388. tfornode(node).t2:=loopcode;
  389. do_firstpass(node);
  390. result:=internalstatements(newcodestatements);
  391. addstatement(newcodestatements,initcode);
  392. addstatement(newcodestatements,node);
  393. addstatement(newcodestatements,deletecode);
  394. end;
  395. templist.Free;
  396. inductionexprs.Free;
  397. end;
  398. function iterforloops(var n: tnode; arg: pointer): foreachnoderesult;
  399. var
  400. hp : tnode;
  401. begin
  402. Result:=fen_false;
  403. if n.nodetype=forn then
  404. begin
  405. { do we have DFA available? }
  406. if pi_dfaavailable in current_procinfo.flags then
  407. begin
  408. CalcDefSum(n);
  409. end;
  410. containsnestedforloop:=false;
  411. hp:=OptimizeInductionVariablesSingleForLoop(n);
  412. if assigned(hp) then
  413. begin
  414. n.Free;
  415. n:=hp;
  416. end;
  417. { can we avoid further searching? }
  418. if not(containsnestedforloop) then
  419. Result:=fen_norecurse_false;
  420. end;
  421. end;
  422. function OptimizeInductionVariables(node : tnode) : boolean;
  423. begin
  424. changedforloop:=false;
  425. foreachnodestatic(pm_postprocess,node,@iterforloops,nil);
  426. Result:=changedforloop;
  427. end;
  428. end.