#ifdef SYSTEMC
/*
 * $Id: Update_Prediction_Table_transition.cpp 97 2008-12-19 15:34:00Z rosiere $
 *
 * [ Description ]
 * 
 */

#include "Behavioural/Core/Multi_Front_end/Front_end/Prediction_unit/Update_Prediction_Table/include/Update_Prediction_Table.h"

namespace morpheo                    {
namespace behavioural {
namespace core {
namespace multi_front_end {
namespace front_end {
namespace prediction_unit {
namespace update_prediction_table {

#undef  FUNCTION
#define FUNCTION "Update_Prediction_Table::transition"
  void Update_Prediction_Table::transition (void)
  {
    log_begin(Update_Prediction_Table,FUNCTION);
    log_function(Update_Prediction_Table,FUNCTION,_name.c_str());

    if (PORT_READ(in_NRESET) == 0)
      {
        // Initialisation

        reg_UPDATE_PRIORITY = 0;

        // All pointer is set at 0
	for (uint32_t i=0; i<_param->_nb_context; i++)
	  {
            for (uint32_t j=0; j<_param->_size_ufpt_queue[i]; ++j)
              reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._state = UPDATE_FETCH_PREDICTION_STATE_EMPTY;
            reg_UFPT_BOTTOM          [i] = 0;
            reg_UFPT_TOP             [i] = 0;
            reg_UFPT_UPDATE          [i] = 0;
            reg_UFPT_NB_NEED_UPDATE  [i] = 0;
                                                                
            for (uint32_t j=0; j<_param->_size_upt_queue[i]; ++j)
              reg_UPDATE_PREDICTION_TABLE [i][j]._state = UPDATE_PREDICTION_STATE_EMPTY;
            reg_UPT_BOTTOM           [i] = 0;
            reg_UPT_TOP              [i] = 0;
            reg_UPT_TOP_EVENT        [i] = 0;
            reg_UPT_UPDATE           [i] = 0;
                                                                                    
            reg_IS_ACCURATE          [i] = true;
            
            reg_EVENT_STATE          [i] = EVENT_STATE_OK;
          }
      }
    else
      {
        bool flush_UFPT [_param->_nb_context];
	for (uint32_t i=0; i<_param->_nb_context; i++)
          flush_UFPT [i] = false;

	// ===================================================================
	// =====[ GARBAGE COLLECTOR ]=========================================
	// ===================================================================

        // Each cycle, if the most lastest branch have update all prediction struction (state = end), free this slot
        //   * Update state -> new status is "empty"
        //   * Update pointer (bottom and accurate)
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * GARBAGE COLLECTOR");
	for (uint32_t i=0; i<_param->_nb_context; i++)
	  {
            // UPDATE_FETCH_PREDICTION_TABLE
            {
              uint32_t bottom = reg_UFPT_BOTTOM [i];
              
              // Test if state is end
              if (reg_UPDATE_FETCH_PREDICTION_TABLE [i][bottom]._state == UPDATE_FETCH_PREDICTION_STATE_END)
                {
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UFPT [%d][%d]",i,bottom);
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UFPT [%d][%d].state =  UPDATE_FETCH_PREDICTION_STATE_EMPTY",i,bottom);

                  // Free slot
                  reg_UPDATE_FETCH_PREDICTION_TABLE [i][bottom]._state = UPDATE_FETCH_PREDICTION_STATE_EMPTY;
                  // Update pointer
                  reg_UFPT_BOTTOM [i] = (bottom+1)%_param->_size_ufpt_queue[i];
                }
            }

            // UPDATE_PREDICTION_TABLE
            {
              uint32_t bottom = reg_UPT_BOTTOM [i];
              bool     end_ok = (reg_UPDATE_PREDICTION_TABLE [i][bottom]._state == UPDATE_PREDICTION_STATE_END_OK);
              bool     end_ko = (reg_UPDATE_PREDICTION_TABLE [i][bottom]._state == UPDATE_PREDICTION_STATE_END_KO);

              // Test if state is end
              if (end_ok or end_ko)
                {
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT [%d][%d]",i,bottom);
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT [%d][%d]._state =  UPDATE_PREDICTION_STATE_EMPTY",i,bottom);

                  // Free slot
                  reg_UPDATE_PREDICTION_TABLE [i][bottom]._state = UPDATE_PREDICTION_STATE_EMPTY;

                  // Update pointer
                  reg_UPT_BOTTOM [i] = (bottom+1)%_param->_size_upt_queue[i];
//                   if (bottom = reg_UPT_UPDATE [i])
//                     reg_UPT_UPDATE [i] = reg_UPT_BOTTOM [i];
                  if (end_ko) // free
                    {
                      reg_UPT_TOP    [i] = reg_UPT_TOP_EVENT [i];
                      reg_UPT_UPDATE [i] = reg_UPT_TOP_EVENT [i];
                    }
                }
            }
	  }

	// ===================================================================
	// =====[ PREDICT ]===================================================
	// ===================================================================
        
        // An ifetch_unit compute next cycle and have an branch : predict_val is set
        //   * Alloc new entry -> new status is "wait decod"
        //   * Save input (to restore in miss or error)
        //   * Update pointer

	for (uint32_t i=0; i<_param->_nb_inst_predict; i++)
	  if (PORT_READ(in_PREDICT_VAL[i]) and internal_PREDICT_ACK [i])
	    {
	      Tcontext_t context = (_param->_have_port_context_id)?PORT_READ(in_PREDICT_CONTEXT_ID [i]):0;
	      uint32_t   top     = internal_PREDICT_UPDATE_PREDICTION_ID [i];

	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * PREDICT[%d] - Accepted",i);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * context : %d",context);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * top     : %d",top);

#ifdef DEBUG_TEST
              if (reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._state != UPDATE_FETCH_PREDICTION_STATE_EMPTY)
                throw ERRORMORPHEO(FUNCTION,_("Predict : invalid state."));
#endif

              log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UFPT [%d][%d].state <- UPDATE_FETCH_PREDICTION_STATE_WAIT_DECOD (predict)",context,top);
 	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._state        = UPDATE_FETCH_PREDICTION_STATE_WAIT_DECOD;

              Tbranch_condition_t condition = PORT_READ(in_PREDICT_BTB_CONDITION [i]);

	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._condition    = condition;
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._address_src  = PORT_READ(in_PREDICT_BTB_ADDRESS_SRC  [i]);
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._address_dest = PORT_READ(in_PREDICT_BTB_ADDRESS_DEST [i]);
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._last_take    = PORT_READ(in_PREDICT_BTB_LAST_TAKE    [i]);
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._is_accurate  = PORT_READ(in_PREDICT_BTB_IS_ACCURATE  [i]);
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._history      = (_param->_have_port_history)?PORT_READ(in_PREDICT_DIR_HISTORY [i]):0;
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._address_ras  = PORT_READ(in_PREDICT_RAS_ADDRESS      [i]);
	      reg_UPDATE_FETCH_PREDICTION_TABLE [context][top]._index_ras    = PORT_READ(in_PREDICT_RAS_INDEX        [i]);

              reg_UFPT_TOP     [context] = (top+1)%_param->_size_ufpt_queue [context];
//            reg_UFPT_UPDATE  [context] = reg_UFPT_TOP [context];
              if (need_update(condition))
                reg_UFPT_NB_NEED_UPDATE [context] ++;
	    }

	// ===================================================================
	// =====[ DECOD ]=====================================================
	// ===================================================================


        // An decod is detected by decod stage
        //   1) Hit prediction : The instruction bundle have a branch predicted in ifetch stage and it is this branch
        //      * Update state, wait_decod -> wait_end
        //      * Pop ufpt -> push upt
        //      * Update accurate register : if the predict stage have tagged this branch as not accurate, stop decod
        //   2) Miss           : The instruction bundle have a branch but it is not predicted
        //      * Flush ufpt
        //      * decod information is write in upt

	for (uint32_t i=0; i<_param->_nb_inst_decod; i++)
	  if (PORT_READ(in_DECOD_VAL[i]) and internal_DECOD_ACK [i])
	    {
	      Tcontext_t          context       = (_param->_have_port_context_id)?PORT_READ(in_DECOD_CONTEXT_ID [i]):0;
	      Tcontrol_t          miss_ifetch   = PORT_READ(in_DECOD_MISS_IFETCH [i]);
	      Tcontrol_t          miss_decod    = PORT_READ(in_DECOD_MISS_DECOD  [i]);
              uint32_t            upt_ptr_write = internal_DECOD_UPT_PTR_WRITE [i];
              Tbranch_condition_t condition  ;
              Tcontrol_t          is_accurate;
              Taddress_t          address_src   = PORT_READ(in_DECOD_BTB_ADDRESS_SRC  [i]);
              Taddress_t          address_dest  = PORT_READ(in_DECOD_BTB_ADDRESS_DEST [i]);
              Tcontrol_t          last_take     = PORT_READ(in_DECOD_BTB_LAST_TAKE    [i]);

              log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * DECOD[%d] - Accepted",i);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * context       : %d",context);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * miss_ifetch   : %d",miss_ifetch);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * miss_decod    : %d",miss_decod);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * upt_ptr_write : %d",upt_ptr_write);
	      
              if (miss_ifetch or miss_decod)
		{
                  // Have a miss !!!
#ifdef DEBUG_TEST
                  if (reg_EVENT_STATE [context] != EVENT_STATE_OK)
                    throw ERRORMORPHEO(FUNCTION,_("Decod : invalid event state."));
#endif
                  
                  if (reg_UFPT_NB_NEED_UPDATE [context] == 0)
                    {
                      // Change state
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_UPDATE_CONTEXT (decod - miss - no flush ufpt)",context);
                      reg_EVENT_STATE [context] = EVENT_STATE_UPDATE_CONTEXT;
                    }
                  else
                    {
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_FLUSH_UFPT (decod - miss - flush ufpt)",context);
                      reg_EVENT_STATE [context] = EVENT_STATE_FLUSH_UFPT;
                    }

                  // Flush UPFT
                  flush_UFPT [context] = true;

                  reg_EVENT_ADDRESS_SRC     [context] = address_src; // delay_slot is compute in Context_State
                  reg_EVENT_ADDRESS_DEST_VAL[context] = last_take;
                  reg_EVENT_ADDRESS_DEST    [context] = address_dest;

                  // Push upt (from decod interface)
                  condition   = PORT_READ(in_DECOD_BTB_CONDITION [i]);
                  is_accurate = PORT_READ(in_DECOD_IS_ACCURATE   [i]);

                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._condition         = condition;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_src       = address_src ;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_dest      = address_dest;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._last_take         = last_take   ;
//                reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._good_take;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._is_accurate       = is_accurate;
//                reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._history           = ; // static prediction
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_ras       = PORT_READ(in_DECOD_RAS_ADDRESS [i]);
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._index_ras         = PORT_READ(in_DECOD_RAS_INDEX   [i]);
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._ifetch_prediction = false; // static prediction
		}
	      else
		{
		  // Normal case : branch is previous predicated, change state of branch
                  uint32_t ufpt_ptr_read = (_param->_have_port_depth)?PORT_READ(in_DECOD_UPDATE_PREDICTION_ID [i]):0;

                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * ufpt_ptr_read : %d",ufpt_ptr_read);

#ifdef DEBUG_TEST
                  if (reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._state != UPDATE_FETCH_PREDICTION_STATE_WAIT_DECOD)
                    throw ERRORMORPHEO(FUNCTION,_("Decod : invalid ufpt state."));
#endif
                  // Change state
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UFPT [%d][%d].state <- UPDATE_FETCH_PREDICTION_STATE_END (decod - hit)",context,ufpt_ptr_read);
                  reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._state = UPDATE_FETCH_PREDICTION_STATE_END;

                  // Push upt (from Pop ufpt)
                  condition   = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._condition;
                  is_accurate = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._is_accurate;

                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._condition         = condition;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_src       = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._address_src ;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_dest      = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._address_dest;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._last_take         = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._last_take   ;
//                reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._good_take;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._is_accurate       = is_accurate;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._history           = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._history     ;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._address_ras       = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._address_ras ;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._index_ras         = reg_UPDATE_FETCH_PREDICTION_TABLE [context][ufpt_ptr_read]._index_ras   ;
                  reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._ifetch_prediction = true; // prediction from ifetch

                  // Update pointer
                  if (need_update(condition))
                    {
                      reg_UFPT_NB_NEED_UPDATE [context] --;
                    }
		}

              // All case !!!

#ifdef DEBUG_TEST
              if (reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._state != UPDATE_PREDICTION_STATE_EMPTY)
                throw ERRORMORPHEO(FUNCTION,_("Decod : invalid upt state."));
#endif
              
              // Change state
              log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT  [%d][%d].state <- UPDATE_PREDICTION_STATE_WAIT_END (decod - hit)",context,upt_ptr_write);
              reg_UPDATE_PREDICTION_TABLE [context][upt_ptr_write]._state = UPDATE_PREDICTION_STATE_WAIT_END;
              
              // Write new accurate 
#ifdef DEBUG_TEST
              if (not reg_IS_ACCURATE [context]  and not is_accurate)
                throw ERRORMORPHEO(FUNCTION,_("Decod : invalid accurate flag."));
#endif
              reg_IS_ACCURATE [context] = is_accurate;
              
              // Update pointer
              reg_UPT_TOP     [context] = (upt_ptr_write+1)%_param->_size_upt_queue [context];
//            reg_UPT_UPDATE  [context] = reg_UPT_TOP [context];
	    }

	// ===================================================================
	// =====[ BRANCH_COMPLETE ]===========================================
	// ===================================================================
        
        // The branch is complete
        //   * Hit  prediction : 
        //     * update status
        //   * Miss prediction :
	for (uint32_t i=0; i<_param->_nb_inst_branch_complete; i++)
	  if (PORT_READ(in_BRANCH_COMPLETE_VAL[i]) and internal_BRANCH_COMPLETE_ACK [i])
	    {
	      Tcontext_t context = (_param->_have_port_context_id)?PORT_READ(in_BRANCH_COMPLETE_CONTEXT_ID [i]):0;
	      Tdepth_t   depth   = (_param->_have_port_depth     )?PORT_READ(in_BRANCH_COMPLETE_DEPTH      [i]):0;
              Tcontrol_t miss      = internal_BRANCH_COMPLETE_MISS_PREDICTION [i];
              Tcontrol_t good_take = internal_BRANCH_COMPLETE_TAKE            [i];
              Taddress_t good_addr = internal_BRANCH_COMPLETE_ADDRESS_DEST    [i];

	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * BRANCH_COMPLETE[%d] - Accepted",i);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * context    : %d",context);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * depth      : %d",depth);
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * miss       : %d",miss);
	      
              if (miss)
		{
                  // Have a miss !!!
                  // Flush UPFT
                  flush_UFPT [context] = true;
                  
                  // Flush UPT
                  uint32_t top        = reg_UPT_TOP [context];
                  uint32_t new_update = ((top==0)?_param->_size_upt_queue[context]:top)-1; 

                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * top        : %d",top);
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * new_update : %d",new_update);

                  for (uint32_t j=(depth+1)%_param->_size_upt_queue[context];
                                j!=top; 
                                j=(j+1)%_param->_size_upt_queue[context])
                    reg_UPDATE_PREDICTION_TABLE [context][j]._state = UPDATE_PREDICTION_STATE_EVENT;
                  
                  
//                reg_UPT_BOTTOM    [context];
                  reg_UPT_TOP       [context] = depth;
                  reg_UPT_TOP_EVENT [context] = top;

#ifdef DEBUG_TEST
                  if (reg_UPDATE_PREDICTION_TABLE [context][depth]._state != UPDATE_PREDICTION_STATE_WAIT_END)
                    throw ERRORMORPHEO(FUNCTION,_("Branch complete : invalid upt state."));
#endif
                  
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT  [%d][%d].state <- UPDATE_PREDICTION_STATE_KO (branch_complete, ifetch hit)",context,depth);
                  reg_UPDATE_PREDICTION_TABLE [context][depth]._state = UPDATE_PREDICTION_STATE_KO;
                  
                  Taddress_t    address_src         = reg_UPDATE_PREDICTION_TABLE [context][depth]._address_src;
                  event_state_t event_state         = reg_EVENT_STATE [context];
                  bool          previous_update_ras = (event_state == EVENT_STATE_FLUSH_UPT);
                  bool          update_ras          = (new_update != depth);

                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * update_ras : %d",update_ras);

                  if (reg_UFPT_NB_NEED_UPDATE [context] > 0)
                    {
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_FLUSH_UFPT_AND_UPT (branch_complete - miss)",context);
                      reg_EVENT_STATE [context] = EVENT_STATE_FLUSH_UFPT_AND_UPT;
                    }
                  else
                    {
                      if (not previous_update_ras)
                        {
                          // have ras prediction ?
                          log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_FLUSH_UPT (branch_complete - miss)",context);

                          reg_EVENT_STATE [context] = EVENT_STATE_FLUSH_UPT;
             
                        }
                    }

                  if (not previous_update_ras)
                    {
                      reg_UPT_UPDATE [context]  = new_update;
                    }
                  // else no update

                  reg_EVENT_ADDRESS_SRC     [context] = address_src; // delay_slot is compute in Context_State
                  reg_EVENT_ADDRESS_DEST_VAL[context] = good_take;
                  reg_EVENT_ADDRESS_DEST    [context] = good_addr;
		}
	      else
		{
                  // Hit case

#ifdef DEBUG_TEST
                  if (reg_UPDATE_PREDICTION_TABLE [context][depth]._state != UPDATE_PREDICTION_STATE_WAIT_END)
                    throw ERRORMORPHEO(FUNCTION,_("Branch complete : invalid upt state."));
#endif
                    
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT  [%d][%d].state <- UPDATE_PREDICTION_STATE_OK (branch_complete, ifetch hit)",context,depth);
                  reg_UPDATE_PREDICTION_TABLE [context][depth]._state = UPDATE_PREDICTION_STATE_OK;
		}

	      // In all case : update good_take
	      reg_UPDATE_PREDICTION_TABLE [context][depth]._good_take = good_take;
            }

	// ===================================================================
	// =====[ UPDATE ]====================================================
	// ===================================================================
        {
          bool can_continue [_param->_nb_context];
          for (uint32_t i=0; i<_param->_nb_context; ++i)
            can_continue [i] = true;

          for (uint32_t i=0; i<_param->_nb_inst_update; i++)
            {
	      Tcontext_t context   = internal_UPDATE_CONTEXT_ID [i];

              if ((internal_UPDATE_VAL[i] and PORT_READ(in_UPDATE_ACK [i])) or
                  (internal_UPDATE_VAL_WITHOUT_ACK [i] and can_continue [context]))
                {
                  Tdepth_t   depth     = internal_UPDATE_DEPTH      [i];
                  
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * UPDATE[%d] - Accepted",i);
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * context : %d",context);
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * depth   : %d",depth);
                  
                  if (internal_UPDATE_FROM_UFPT [i])
                    {
                      // if free a slot, also all queue is updated
                      // Last slot ?
                      if (reg_UFPT_UPDATE [context] == reg_UFPT_BOTTOM [context])
                        switch (reg_EVENT_STATE [context])
                          {
                          case EVENT_STATE_FLUSH_UFPT             : reg_EVENT_STATE [context] = EVENT_STATE_UPDATE_CONTEXT; break;
                            // impossible to have an update on ufpt and reg_upt_update>reg_upt_top
                          case EVENT_STATE_FLUSH_UFPT_AND_UPT : reg_EVENT_STATE [context] = EVENT_STATE_FLUSH_UPT ; break;
                          default : break;
                          }
                      
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * Update Fetch Prediction Table");
                      
                      // Change state
#ifdef DEBUG_TEST
                      if (reg_UPDATE_FETCH_PREDICTION_TABLE [context][depth]._state != UPDATE_FETCH_PREDICTION_STATE_EVENT)
                        throw ERRORMORPHEO(FUNCTION,_("Update : invalid ufpt state."));
#endif
                      
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UFPT [%d][%d].state <- UPDATE_FETCH_PREDICTION_STATE_END (update)",context,depth);
                      
                      reg_UPDATE_FETCH_PREDICTION_TABLE [context][depth]._state = UPDATE_FETCH_PREDICTION_STATE_END;
                      
                      
                      // Update pointer
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_UFPT_UPDATE (before) : %d",reg_UFPT_UPDATE [context]);
                      reg_UFPT_UPDATE [context] = ((depth==0)?_param->_size_ufpt_queue[context]:depth)-1;
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_UFPT_UPDATE (after ) : %d",reg_UFPT_UPDATE [context]);
                      // Free a register that need update ?
                      if (need_update(reg_UPDATE_FETCH_PREDICTION_TABLE [context][depth]._condition))
                        reg_UFPT_NB_NEED_UPDATE [context] --;
                    }
                  else
                    {
                      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * Update Prediction Table");
                      
                      // Change state
#ifdef DEBUG_TEST 
                      if (internal_UPDATE_RAS [i])
                        {
                          if ((reg_UPDATE_PREDICTION_TABLE [context][depth]._state != UPDATE_PREDICTION_STATE_EVENT) and
                              (reg_UPDATE_PREDICTION_TABLE [context][depth]._state != UPDATE_PREDICTION_STATE_KO   ))
                            throw ERRORMORPHEO(FUNCTION,_("Update : invalid upt state."));
                        }
                      else
                        {
                          if (reg_UPDATE_PREDICTION_TABLE [context][depth]._state != UPDATE_PREDICTION_STATE_OK   )
                            throw ERRORMORPHEO(FUNCTION,_("Update : invalid upt state."));
                        }
#endif

//                    bool have_event = ((reg_UPDATE_PREDICTION_TABLE [context][depth]._state == UPDATE_PREDICTION_STATE_KO) or
//                                       (reg_UPDATE_PREDICTION_TABLE [context][depth]._state == UPDATE_PREDICTION_STATE_EVENT));
#ifdef STATISTICS
                      Tbranch_condition_t condition = reg_UPDATE_PREDICTION_TABLE [context][depth]._condition;
                      bool ok     = (reg_UPDATE_PREDICTION_TABLE [context][depth]._state == UPDATE_PREDICTION_STATE_OK);
#endif
                      bool ko     = (reg_UPDATE_PREDICTION_TABLE [context][depth]._state == UPDATE_PREDICTION_STATE_KO);

                      // Have an update, test the state to transiste to the good state
                      if (ko)
                        {
                          log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT  [%d][%d].state <- UPDATE_PREDICTION_STATE_END_KO (update)",context,depth);
                          
                          reg_UPDATE_PREDICTION_TABLE [context][depth]._state = UPDATE_PREDICTION_STATE_END_KO;

#ifdef STATISTICS
                          if (usage_is_set(_usage,USE_STATISTICS))
                            (*_stat_nb_branch_miss [context][condition])++;
#endif
                        }
                      else
                        {
                          log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * UPT  [%d][%d].state <- UPDATE_PREDICTION_STATE_END_OK (update)",context,depth);
                          
                          reg_UPDATE_PREDICTION_TABLE [context][depth]._state = UPDATE_PREDICTION_STATE_END_OK;


#ifdef STATISTICS
                          if (usage_is_set(_usage,USE_STATISTICS))
                            {
                              if (ok)
                                (*_stat_nb_branch_hit    [context][condition]) ++;
                              else
                                (*_stat_nb_branch_unused [context]) ++;
                            }
#endif
                        }
                      
                      // Update pointer
                      //  * if update RAS : update pointer is decreaste until it equal at top pointer
                      if (internal_UPDATE_RAS [i])
                        {
                          // if end_event, restart too bottom, else decrease pointer
                          bool end_event  = (reg_UPT_UPDATE [context] == reg_UPT_TOP [context]);
                          
                          reg_UPT_UPDATE [context] = (end_event)?reg_UPT_BOTTOM[context]:(((depth==0)?_param->_size_upt_queue[context]:depth)-1);
                          if (end_event)
                            {
                              reg_UPT_UPDATE [context] = reg_UPT_BOTTOM[context];
                              reg_EVENT_STATE [context] = EVENT_STATE_UPDATE_CONTEXT;
                            }
                          else
                            {
                              reg_UPT_UPDATE [context] = (((depth==0)?_param->_size_upt_queue[context]:depth)-1);
                            }
                        }
                      else
                        {
                          // increase pointer
                          reg_UPT_UPDATE [context] = (depth+1)%_param->_size_upt_queue[context];
                        }
                      
                      // Free the branch with no accurate ?
                      if (reg_UPDATE_PREDICTION_TABLE [context][depth]._is_accurate == false)
                        reg_IS_ACCURATE [context] = true;
                    }
                }
              else
                can_continue [context] = false;
            }
	
          // Round robin
          reg_UPDATE_PRIORITY = (reg_UPDATE_PRIORITY+1)%_param->_nb_context;
        }

 	// ===================================================================
	// =====[ BRANCH_EVENT ]==============================================
	// ===================================================================
	for (uint32_t i=0; i<_param->_nb_context; i++)
	  if (internal_BRANCH_EVENT_VAL [i] and PORT_READ(in_BRANCH_EVENT_ACK [i]))
            {
	      log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * BRANCH_EVENT [%d] - Accepted",i);

#ifdef DEBUG_TEST
              if (reg_EVENT_STATE [i] != EVENT_STATE_UPDATE_CONTEXT)
                throw ERRORMORPHEO(FUNCTION,_("Decod : invalid event state."));
#endif
              
              // Change state
              log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_WAIT_END_EVENT (branch_event)",i);
              
              reg_EVENT_STATE [i] = EVENT_STATE_WAIT_END_EVENT;
            }

 	// ===================================================================
	// =====[ EVENT ]=====================================================
	// ===================================================================
        for (uint32_t i=0; i<_param->_nb_context; ++i)
          if (PORT_READ(in_EVENT_VAL [i]) and internal_EVENT_ACK [i])
            {
              //----------------------------------------------------------------
              // Cases
              //----------------------------------------------------------------
              //   * EVENT_TYPE_NONE               - nothing
              //   * EVENT_TYPE_MISS_SPECULATION   - Change state, reset pointer
              //   * EVENT_TYPE_EXCEPTION          - Flush upft and upt, Change state, reset pointer
              //   * EVENT_TYPE_BRANCH_NO_ACCURATE - nothing : manage in decod and update
              //   * EVENT_TYPE_SPR_ACCESS         - nothing
              //   * EVENT_TYPE_MSYNC              - nothing
              //   * EVENT_TYPE_PSYNC              - nothing
              //   * EVENT_TYPE_CSYNC              - nothing
              
              Tevent_type_t  event_type  = PORT_READ(in_EVENT_TYPE  [i]);
//            Tdepth_t       depth       = PORT_READ(in_EVENT_DEPTH [i]);
            
              // Test if end of miss
              if (event_type  == EVENT_TYPE_MISS_SPECULATION)
                {
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * EVENT");
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * type  : EVENT_TYPE_MISS_SPECULATION");
                  
#ifdef DEBUG_TEST
                  if (reg_EVENT_STATE [i] != EVENT_STATE_WAIT_END_EVENT)
                    throw ERRORMORPHEO(FUNCTION,_("Event : invalid event state."));
#endif
                  
                  // Change state
                  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * EVENT [%d] <- EVENT_STATE_OK (event)",i);
                  
                  reg_EVENT_STATE [i] = EVENT_STATE_OK;
                }
            }

 	// ===================================================================
	// =====[ FLUSH ]=====================================================
	// ===================================================================

        for (uint32_t i=0; i<_param->_nb_context; ++i)
          {
            if (flush_UFPT [i])
              {
                log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * Flush Update Fetch Prediction Table");
                log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * context                          : %d",i);
                log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_UFPT_NB_NEED_UPDATE          : %d",reg_UFPT_NB_NEED_UPDATE [i]);

              // It's to accelerate miss speculation
              if (reg_UFPT_NB_NEED_UPDATE [i] == 0)
                {

                  // No entry need prediction, flush all entry -> Reset
                  for (uint32_t j=0; j<_param->_size_ufpt_queue[i]; ++j)
                    reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._state = UPDATE_FETCH_PREDICTION_STATE_EMPTY;
                  reg_UFPT_BOTTOM [i] = 0;
                  reg_UFPT_TOP    [i] = 0;
//                reg_UFPT_UPDATE [i];
                }
              else
                {
                  for (uint32_t j=0; j<_param->_size_ufpt_queue[i]; ++j)
                    reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._state = UPDATE_FETCH_PREDICTION_STATE_EVENT;
                  
                  // TOP is next write slot : last slot is TOP-1
                  uint32_t top = reg_UFPT_TOP [i];
                  reg_UFPT_UPDATE [i] = ((top==0)?_param->_size_ufpt_queue[i]:top)-1;
                  
//                reg_UFPT_BOTTOM [i];
//                reg_UFPT_TOP    [i];
                }

              log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_UFPT_UPDATE         (after ) : %d",reg_UFPT_UPDATE [i]);

              }
          }

#ifdef STATISTICS
        if (usage_is_set(_usage,USE_STATISTICS))
          for (uint32_t i=0; i<_param->_nb_context; i++)
            {
              for (uint32_t j=0; j<_param->_size_ufpt_queue[i]; j++)
                if (reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._state != UPDATE_FETCH_PREDICTION_STATE_EMPTY)
                  (*_stat_ufpt_queue_nb_elt [i]) ++;
              for (uint32_t j=0; j<_param->_size_upt_queue[i]; j++)
                if (reg_UPDATE_PREDICTION_TABLE [i][j]._state != UPDATE_PREDICTION_STATE_EMPTY)
                  (*_stat_upt_queue_nb_elt [i]) ++;
            }
#endif
        
 	// ===================================================================
	// =====[ PRINT ]=====================================================
	// ===================================================================

#if (DEBUG >= DEBUG_TRACE)
    log_printf(TRACE,Update_Prediction_Table,FUNCTION,"  * Dump Update_Prediction_Table");
    log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_UPDATE_PRIORITY       : %d",reg_UPDATE_PRIORITY);
    for (uint32_t i=0; i<_param->_nb_context; i++)
      {
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_IS_ACCURATE           : %d",reg_IS_ACCURATE        [i]);
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_EVENT_STATE           : %s"  ,toString(reg_EVENT_STATE [i]).c_str());
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_EVENT_ADDRESS_SRC     : %.8x",reg_EVENT_ADDRESS_SRC     [i]);
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_EVENT_ADDRESS_DEST_VAL: %d"  ,reg_EVENT_ADDRESS_DEST_VAL[i]);
        log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * reg_EVENT_ADDRESS_DEST    : %.8x",reg_EVENT_ADDRESS_DEST    [i]);

	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * Update_Fetch_Prediction_Table   [%d]",i);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UFPT_BOTTOM         : %d",reg_UFPT_BOTTOM         [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UFPT_TOP            : %d",reg_UFPT_TOP            [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UFPT_UPDATE         : %d",reg_UFPT_UPDATE         [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UFPT_NB_NEED_UPDATE : %d",reg_UFPT_NB_NEED_UPDATE [i]);
	for (uint32_t j=0; j<_param->_size_ufpt_queue[i]; j++)
	  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"        [%d] %.4d, %.8x %.8x, %.1d   %.1d, %.8d %.8x %.4d - %s",
                     j,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._condition,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._address_src,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._address_dest,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._last_take,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._is_accurate,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._history,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._address_ras,
                     reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._index_ras,
                     toString(reg_UPDATE_FETCH_PREDICTION_TABLE [i][j]._state).c_str()
                     );

	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"    * Update_Prediction_Table   [%d]",i);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UPT_BOTTOM          : %d",reg_UPT_BOTTOM         [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UPT_TOP             : %d",reg_UPT_TOP            [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UPT_TOP_EVENT       : %d",reg_UPT_TOP_EVENT      [i]);
	log_printf(TRACE,Update_Prediction_Table,FUNCTION,"      * reg_UPT_UPDATE          : %d",reg_UPT_UPDATE         [i]);
	for (uint32_t j=0; j<_param->_size_upt_queue[i]; j++)
	  log_printf(TRACE,Update_Prediction_Table,FUNCTION,"        [%d] %.4d, %.8x %.8x, %.1d %.1d %.1d, %.8d %.8x %.4d - %s",
                     j,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._condition,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._address_src,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._address_dest,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._last_take,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._good_take,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._is_accurate,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._history,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._address_ras,
                     reg_UPDATE_PREDICTION_TABLE [i][j]._index_ras,
                     toString(reg_UPDATE_PREDICTION_TABLE [i][j]._state).c_str()
                     );
      }
#endif
      }


#if defined(STATISTICS) or defined(VHDL_TESTBENCH)
    end_cycle ();
#endif
    
    log_end(Update_Prediction_Table,FUNCTION);
  };

}; // end namespace update_prediction_table
}; // end namespace prediction_unit
}; // end namespace front_end
}; // end namespace multi_front_end
}; // end namespace core

}; // end namespace behavioural
}; // end namespace morpheo              
#endif
