/*******************************************************************\

Module: Loop IDs

Author: Daniel Kroening, kroening@kroening.com

\*******************************************************************/

#include <xml.h>
#include <xml_irep.h>

#include "loop_ids.h"

/*******************************************************************\

Function: set_loop_ids

  Inputs:

 Outputs:

 Purpose:

\*******************************************************************/

void set_loop_ids(
  goto_programt &goto_program,
  unsigned &count)
{
  for(goto_programt::instructionst::iterator
      it=goto_program.instructions.begin();
      it!=goto_program.instructions.end();
      it++)
    if(it->is_backwards_goto())
    {
      count++;
      it->location.set("loop-id", count);
    }
}

/*******************************************************************\

Function: set_loop_ids

  Inputs:

 Outputs:

 Purpose:

\*******************************************************************/

void set_loop_ids(goto_functionst &goto_functions)
{
  unsigned count=0;

  for(goto_functionst::function_mapt::iterator
      it=goto_functions.function_map.begin();
      it!=goto_functions.function_map.end();
      it++)
    set_loop_ids(it->second.body, count);
}

/*******************************************************************\

Function: show_loop_ids

  Inputs:

 Outputs:

 Purpose:

\*******************************************************************/

void show_loop_ids(
  ui_message_handlert::uit ui,
  const goto_programt &goto_program)
{
  for(goto_programt::instructionst::const_iterator
      it=goto_program.instructions.begin();
      it!=goto_program.instructions.end();
      it++)
  {
    if(it->is_backwards_goto())
    {
      const irep_idt &loop_id=it->location.get("loop-id");

      if(ui==ui_message_handlert::XML_UI)
      {
        xmlt xml("loop");
        xml.new_element("loop-id").data=id2string(loop_id);
        
        xmlt &l=xml.new_element();
        convert(it->location, l);
        l.name="location";
        
        std::cout << xml << std::endl;
      }
      else if(ui==ui_message_handlert::PLAIN)
      {
        std::cout << "Loop " << loop_id << ":" << std::endl;

        std::cout << "  " << it->location << std::endl;
        std::cout << std::endl;
      }
      else
        assert(false);
    }
  }
}

/*******************************************************************\

Function: show_loop_ids

  Inputs:

 Outputs:

 Purpose:

\*******************************************************************/

void show_loop_ids(
  ui_message_handlert::uit ui,
  const goto_functionst &goto_functions)
{
  for(goto_functionst::function_mapt::const_iterator
      it=goto_functions.function_map.begin();
      it!=goto_functions.function_map.end();
      it++)
    show_loop_ids(ui, it->second.body);
}

