optloop.pas 20 KB

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