optloop.pas 20 KB

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