with Instrument;
use Instrument;

---------------------
-- Fuse Scalar Reference
---------------------

--  This test evaluates a code  improvement  potential  that  results
--  from minimizing iteration control operations when the opportunity
--  is offered to combine two adjacent loops that  enclose  a  simple
--  redefinition of a local variable.

--  The  test  procedures  contain  a  redefinition  of   two   local
--  variables, Local_1 and Local_2.  Each redefinition is enclosed in
--  a separate loop with a loop parameter that has  the  same  static
--  discrete  range.   This  range  is  sufficiently  large  to elide
--  unrolling the loops.  The redefinitions  evaluate  a  call  to  a
--  local   function   to  ensure  that  each  redefinition  must  be
--  performed.  The function has no side-effects so that optimization
--  is possible.

--  In the nonoptimized test procedure a redefinition of Local_2 that
--  references  Local_1  is interleaved between the two loops to void
--  the opportunity for the optimization for fusing  the  two  loops.
--  When  this  redefinition  is relocated to follow the two loops in
--  the optimized test procedure, the optimization is evidenced by  a
--  difference  in  the  execution time and space requirements of the
--  two procedures.

--  The camouflaged redefinition of Global_1  using  Local_1  ensures
--  that   other  unexpected  optimizations  do  not  invalidate  the
--  benchmark.

procedure Lfsra2 is

    package New_Procs is new Procs (Integer);
    use New_Procs;

    Local_1, Local_2 : T := Ident (Init);

    function Function_1 (Input : T) return T is

    begin

        if Input = Init then
            return Input;
        end if;
        return Function_1 (Init);

    end Function_1;

begin

    Start ("LFSRA2", "Loop Fuse, Scalar Ref. (test)");
    for I in 1 .. 1000 loop

        Let (Global, Ident (Init));

        for J in 1 .. 100 loop

            Local_1 := Function_1 (Local_1);

        end loop;

        --  Local_2 := Ident(Local_1);          -- included in control version

        for J in 1 .. 100 loop

            Local_2 := Function_1 (Local_2);

        end loop;

        Local_2 := Ident (Local_2);          -- included in test version
        Let (Global, Ident (Local_1));
        Let (Global, Ident (Init));

    end loop;
    Stop;

end Lfsra2;