Cleaning up: Removing the full-blown graph traversal.
[jpf-core.git] / src / main / gov / nasa / jpf / listener / StateReducer.java
index f70c992219956b8e9fc003bc289bff1882bbaca2..0a27b5ce2f8f30f70d970576746d900d1dfeb7fd 100644 (file)
@@ -34,7 +34,17 @@ import java.util.*;
 // TODO: Fix for Groovy's model-checking
 // TODO: This is a setter to change the values of the ChoiceGenerator to implement POR
 /**
- * simple tool to log state changes
+ * Simple tool to log state changes.
+ *
+ * This DPOR implementation is augmented by the algorithm presented in this SPIN paper:
+ * http://spinroot.com/spin/symposia/ws08/spin2008_submission_33.pdf
+ *
+ * The algorithm is presented on page 11 of the paper. Basically, we create a graph G
+ * (i.e., visible operation dependency graph)
+ * that maps inter-related threads/sub-programs that trigger state changes.
+ * The key to this approach is that we evaluate graph G in every iteration/recursion to
+ * only update the backtrack sets of the threads/sub-programs that are reachable in graph G
+ * from the currently running thread/sub-program.
  */
 public class StateReducer extends ListenerAdapter {
 
@@ -42,10 +52,10 @@ public class StateReducer extends ListenerAdapter {
   private boolean debugMode;
   private boolean stateReductionMode;
   private final PrintWriter out;
-  volatile private String detail;
-  volatile private int depth;
-  volatile private int id;
-  Transition transition;
+  private String detail;
+  private int depth;
+  private int id;
+  private Transition transition;
 
   // State reduction fields
   private Integer[] choices;
@@ -65,8 +75,26 @@ public class StateReducer extends ListenerAdapter {
   // Stores explored backtrack lists in the form of HashSet of Strings
   private HashSet<String> backtrackSet;
   private HashMap<Integer, HashSet<Integer>> conflictPairMap;
-  // Map choicelist with start index
-//  private HashMap<Integer[],Integer> choiceListStartIndexMap;
+
+  // Map that represents graph G
+  // (i.e., visible operation dependency graph (VOD Graph)
+  private HashMap<Integer, HashSet<Integer>> vodGraphMap;
+  // Set that represents hash table H
+  // (i.e., hash table that records encountered states)
+  // VOD graph is updated when the state has not yet been seen
+  // Current state
+  private int stateId;
+  // Previous choice number
+  private int prevChoiceValue;
+  // HashSet that stores references to unused CGs
+  private HashSet<IntChoiceFromSet> unusedCG;
+
+  //private HashMap<Integer, ConflictTracker.Node> stateGraph;
+  private HashMap<Integer, HashSet<Integer>> stateToEventMap;
+  // Map state to event
+  // Visited states in the previous and current executions/traces for terminating condition
+  private HashSet<Integer> prevVisitedStates;
+  private HashSet<Integer> currVisitedStates;
 
   public StateReducer(Config config, JPF jpf) {
     debugMode = config.getBoolean("debug_state_transition", false);
@@ -81,6 +109,18 @@ public class StateReducer extends ListenerAdapter {
     id = 0;
     transition = null;
     isBooleanCGFlipped = false;
+    vodGraphMap = new HashMap<>();
+    stateId = -1;
+    prevChoiceValue = -1;
+    cgMap = new HashMap<>();
+    readWriteFieldsMap = new HashMap<>();
+    backtrackMap = new HashMap<>();
+    backtrackSet = new HashSet<>();
+    conflictPairMap = new HashMap<>();
+    unusedCG = new HashSet<>();
+    stateToEventMap = new HashMap<>();
+    prevVisitedStates = new HashSet<>();
+    currVisitedStates = new HashSet<>();
     initializeStateReduction();
   }
 
@@ -93,11 +133,10 @@ public class StateReducer extends ListenerAdapter {
       maxUpperBound = 0;
       isInitialized = false;
       isResetAfterAnalysis = false;
-      cgMap = new HashMap<>();
-      readWriteFieldsMap = new HashMap<>();
-      backtrackMap = new HashMap<>();
-      backtrackSet = new HashSet<>();
-      conflictPairMap = new HashMap<>();
+      cgMap.clear();
+      resetReadWriteAnalysis();
+      backtrackMap.clear();
+      backtrackSet.clear();
     }
   }
 
@@ -121,6 +160,47 @@ public class StateReducer extends ListenerAdapter {
     }
   }
 
+  private void resetReadWriteAnalysis() {
+    // Reset the following data structure when the choice counter reaches 0 again
+    conflictPairMap.clear();
+    readWriteFieldsMap.clear();
+  }
+
+  private IntChoiceFromSet setNewCG(IntChoiceFromSet icsCG) {
+    icsCG.setNewValues(choices);
+    icsCG.reset();
+    // Use a modulo since choiceCounter is going to keep increasing
+    int choiceIndex = choiceCounter % (choices.length - 1);
+    icsCG.advance(choices[choiceIndex]);
+    if (choiceIndex == 0) {
+      resetReadWriteAnalysis();
+    }
+    return icsCG;
+  }
+
+  private void initializeChoiceGenerators(IntChoiceFromSet icsCG, Integer[] cgChoices) {
+    if (choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
+      // Update the choices of the first CG and add '-1'
+      if (choices == null) {
+        // Initialize backtrack set that stores all the explored backtrack lists
+        maxUpperBound = cgChoices.length;
+        // All the choices are always the same so we only need to update it once
+        choices = new Integer[cgChoices.length + 1];
+        System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
+        choices[choices.length - 1] = -1;
+        String firstChoiceListString = buildStringFromChoiceList(choices);
+        backtrackSet.add(firstChoiceListString);
+      }
+      IntChoiceFromSet setCG = setNewCG(icsCG);
+      cgMap.put(setCG, choices[choiceCounter]);
+    } else {
+      // We repeat the same trace if a state match is not found yet
+      IntChoiceFromSet setCG = setNewCG(icsCG);
+      unusedCG.add(setCG);
+    }
+    choiceCounter++;
+  }
+
   @Override
   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
     if (stateReductionMode) {
@@ -135,28 +215,10 @@ public class StateReducer extends ListenerAdapter {
           isInitialized = true;
         }
         // Record the subsequent Integer CGs only until we hit the upper bound
-        if (!isResetAfterAnalysis && choiceCounter <= choiceUpperBound && !cgMap.containsValue(choiceCounter)) {
-          // Update the choices of the first CG and add '-1'
-          if (choices == null) {
-            // Initialize backtrack set that stores all the explored backtrack lists
-            maxUpperBound = cgChoices.length;
-            // All the choices are always the same so we only need to update it once
-            choices = new Integer[cgChoices.length + 1];
-            System.arraycopy(cgChoices, 0, choices, 0, cgChoices.length);
-            choices[choices.length - 1] = -1;
-            String firstChoiceListString = buildStringFromChoiceList(choices);
-            backtrackSet.add(firstChoiceListString);
-          }
-          icsCG.setNewValues(choices);
-          icsCG.reset();
-          // Advance the current Integer CG
-          // This way we explore all the event numbers in the first pass
-          icsCG.advance(choices[choiceCounter]);
-          cgMap.put(icsCG, choices[choiceCounter]);
-          choiceCounter++;
+        if (!isResetAfterAnalysis) {
+          initializeChoiceGenerators(icsCG, cgChoices);
         } else {
-          // Set done the subsequent CGs
-          // We only need n CGs (n is event numbers)
+          // Set new CGs to done so that the search algorithm explores the existing CGs
           icsCG.setDone();
         }
       }
@@ -168,6 +230,10 @@ public class StateReducer extends ListenerAdapter {
     Set<Integer> eventSet = backtrackMap.keySet();
     // Return if there is no conflict at all (highly unlikely)
     if (eventSet.isEmpty()) {
+      // Set every CG to done!
+      for (IntChoiceFromSet cg : cgMap.keySet()) {
+        cg.setDone();
+      }
       return;
     }
     // Reset every CG with the first backtrack lists
@@ -183,6 +249,87 @@ public class StateReducer extends ListenerAdapter {
         cg.setDone();
       }
     }
+    // Set done every CG in the unused CG set
+    for (IntChoiceFromSet cg : unusedCG) {
+      cg.setDone();
+    }
+    unusedCG.clear();
+    saveVisitedStates();
+  }
+
+  // Detect cycles in the current execution/trace
+  // We terminate the execution iff:
+  // (1) the state has been visited in the current execution
+  // (2) the state has one or more cycles that involve all the events
+  // With simple approach we only need to check for a re-visited state.
+  // Basically, we have to check that we have executed all events between two occurrences of such state.
+  private boolean containsCyclesWithAllEvents(int stId) {
+
+    HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
+    boolean containsCyclesWithAllEvts = false;
+    if (checkIfAllEventsInvolved(visitedEvents)) {
+      containsCyclesWithAllEvts = true;
+    }
+
+    return containsCyclesWithAllEvts;
+  }
+
+  private boolean checkIfAllEventsInvolved(HashSet<Integer> visitedEvents) {
+
+    // Check if this set contains all the event choices
+    // If not then this is not the terminating condition
+    for(int i=0; i<=choiceUpperBound; i++) {
+      if (!visitedEvents.contains(i)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private void saveVisitedStates() {
+    // CG is being reset
+    // Save all the visited states
+    prevVisitedStates.addAll(currVisitedStates);
+    currVisitedStates.clear();
+  }
+
+  private void updateChoices(IntChoiceFromSet icsCG) {
+    if (choices == null || choices != icsCG.getAllChoices()) {
+      currCG = icsCG;
+      choices = icsCG.getAllChoices();
+      // Reset a few things for the sub-graph
+      resetReadWriteAnalysis();
+      choiceCounter = 0;
+    }
+  }
+
+  private void exploreNextBacktrackSets(IntChoiceFromSet icsCG) {
+    // Traverse the sub-graphs
+    if (isResetAfterAnalysis) {
+      // Advance choice counter for sub-graphs
+      choiceCounter++;
+      // Do this for every CG after finishing each backtrack list
+      // We try to update the CG with a backtrack list if the state has been visited multiple times
+      if ((icsCG.getNextChoice() == -1 || choiceCounter > 1) && cgMap.containsKey(icsCG)) {
+        int event = cgMap.get(icsCG);
+        LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
+        if (choiceLists != null && choiceLists.peekFirst() != null) {
+          Integer[] choiceList = choiceLists.removeFirst();
+          // Deploy the new choice list for this CG
+          icsCG.setNewValues(choiceList);
+          icsCG.reset();
+        } else {
+          // Set done if this was the last backtrack list
+          icsCG.setDone();
+        }
+        saveVisitedStates();
+      }
+    } else {
+      // Update and reset the CG if needed (do this for the first time after the analysis)
+      // Start backtracking if this is a visited state and it is not a repeating state
+      resetAllCGs();
+      isResetAfterAnalysis = true;
+    }
   }
 
   @Override
@@ -202,42 +349,54 @@ public class StateReducer extends ListenerAdapter {
       if (currentCG instanceof IntChoiceFromSet) {
         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
         // Update the current pointer to the current set of choices
-        if (choices == null || choices != icsCG.getAllChoices()) {
-          currCG = icsCG;
-          choices = icsCG.getAllChoices();
-          // Reset a few things for the sub-graph
-          conflictPairMap.clear();
-          readWriteFieldsMap.clear();
-          choiceCounter = 0;
-        }
-        // Traverse the sub-graphs
-        if (isResetAfterAnalysis) {
-          // Advance choice counter for sub-graphs
-          choiceCounter++;
-          // Do this for every CG after finishing each backtrack list
-          if (icsCG.getNextChoice() == -1) {
-            int event = cgMap.get(icsCG);
-            LinkedList<Integer[]> choiceLists = backtrackMap.get(event);
-            if (choiceLists != null && choiceLists.peekFirst() != null) {
-              Integer[] choiceList = choiceLists.removeFirst();
-              // Deploy the new choice list for this CG
-              icsCG.setNewValues(choiceList);
-              icsCG.reset();
-            } else {
-              // Set done if this was the last backtrack list
-              icsCG.setDone();
-            }
-          }
-        }
-        // Update and reset the CG if needed (do this for the first time after the analysis)
-        if (!isResetAfterAnalysis && icsCG.getNextChoice() == -1) {
-          resetAllCGs();
-          isResetAfterAnalysis = true;
+        updateChoices(icsCG);
+        // Check if we have seen this state or this state contains cycles that involve all events
+        if (prevVisitedStates.contains(stateId) || containsCyclesWithAllEvents(stateId)) {
+          exploreNextBacktrackSets(icsCG);
         }
+        // Update the VOD graph always with the latest
+        updateVODGraph(icsCG.getNextChoice());
       }
     }
   }
 
+  private void updateVODGraph(int currChoiceValue) {
+    // Update the graph when we have the current choice value
+    HashSet<Integer> choiceSet;
+    if (vodGraphMap.containsKey(prevChoiceValue)) {
+      // If the key already exists, just retrieve it
+      choiceSet = vodGraphMap.get(prevChoiceValue);
+    } else {
+      // Create a new entry
+      choiceSet = new HashSet<>();
+      vodGraphMap.put(prevChoiceValue, choiceSet);
+    }
+    choiceSet.add(currChoiceValue);
+    prevChoiceValue = currChoiceValue;
+  }
+
+  private void mapStateToEvent(Search search) {
+    // Insert state ID and event choice into the map
+    HashSet<Integer> eventSet;
+    if (stateToEventMap.containsKey(stateId)) {
+      eventSet = stateToEventMap.get(stateId);
+    } else {
+      eventSet = new HashSet<>();
+      stateToEventMap.put(stateId, eventSet);
+    }
+    eventSet.add(prevChoiceValue);
+  }
+
+  private void updateStateInfo(Search search) {
+    if (stateReductionMode) {
+      // Update the state variables
+      // Line 19 in the paper page 11 (see the heading note above)
+      stateId = search.getStateId();
+      currVisitedStates.add(stateId);
+      mapStateToEvent(search);
+    }
+  }
+
   @Override
   public void stateAdvanced(Search search) {
     if (debugMode) {
@@ -257,6 +416,7 @@ public class StateReducer extends ListenerAdapter {
       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
               " which is " + detail + " Transition: " + transition + "\n");
     }
+    updateStateInfo(search);
   }
 
   @Override
@@ -270,6 +430,7 @@ public class StateReducer extends ListenerAdapter {
       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
               " and depth: " + depth + "\n");
     }
+    updateStateInfo(search);
   }
 
   @Override
@@ -425,7 +586,7 @@ public class StateReducer extends ListenerAdapter {
       // The start index for the recursion is always 1 (from the main branch)
     } else { // This is a sub-graph
       // There is a case/bug that after a re-initialization, currCG is not yet initialized
-      if (currCG != null) {
+      if (currCG != null && cgMap.containsKey(currCG)) {
         int backtrackListIndex = cgMap.get(currCG);
         backtrackChoiceLists = backtrackMap.get(backtrackListIndex);
         int listLength = choices.length;
@@ -487,15 +648,53 @@ public class StateReducer extends ListenerAdapter {
     return false;
   }
 
+  // This method checks whether a choice is reachable in the VOD graph from a reference choice
+  // This is a BFS search
+  private boolean isReachableInVODGraph(int checkedChoice, int referenceChoice) {
+    // Record visited choices as we search in the graph
+    HashSet<Integer> visitedChoice = new HashSet<>();
+    visitedChoice.add(referenceChoice);
+    LinkedList<Integer> nodesToVisit = new LinkedList<>();
+    // If the state doesn't advance as the threads/sub-programs are executed (basically there is no new state),
+    // there is a chance that the graph doesn't have new nodes---thus this check will return a null.
+    if (vodGraphMap.containsKey(referenceChoice)) {
+      nodesToVisit.addAll(vodGraphMap.get(referenceChoice));
+      while(!nodesToVisit.isEmpty()) {
+        int currChoice = nodesToVisit.getFirst();
+        if (currChoice == checkedChoice) {
+          return true;
+        }
+        if (visitedChoice.contains(currChoice)) {
+          // If there is a loop then we don't find it
+          return false;
+        }
+        // Continue searching
+        visitedChoice.add(currChoice);
+        HashSet<Integer> currChoiceNextNodes = vodGraphMap.get(currChoice);
+        if (currChoiceNextNodes != null) {
+          // Add only if there is a mapping for next nodes
+          for (Integer nextNode : currChoiceNextNodes) {
+            // Skip cycles
+            if (nextNode == currChoice) {
+              continue;
+            }
+            nodesToVisit.addLast(nextNode);
+          }
+        }
+      }
+    }
+    return false;
+  }
+
   @Override
   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
     if (stateReductionMode) {
       if (isInitialized) {
-        if (choiceCounter > choices.length - 1) {
+        int currentChoice = (choiceCounter % (choices.length - 1)) - 1;
+        if (currentChoice < 0) {
           // We do not compute the conflicts for the choice '-1'
           return;
         }
-        int currentChoice = choiceCounter - 1;
         // Record accesses from executed instructions
         if (executedInsn instanceof JVMFieldInstruction) {
           // Analyze only after being initialized
@@ -514,13 +713,9 @@ public class StateReducer extends ListenerAdapter {
             String fieldClass = ((JVMFieldInstruction) nextInsn).getFieldInfo().getFullName();
             // We don't care about libraries
             if (!isFieldExcluded(fieldClass)) {
-              // For the main graph we go down to 0, but for subgraph, we only go down to 1 since 0 contains
-              // the reversed event
-//              int end = !isResetAfterAnalysis ? 0 : choiceListStartIndexMap.get(choices);
               // Check for conflict (go backward from currentChoice and get the first conflict)
               // If the current event has conflicts with multiple events, then these will be detected
               // one by one as this recursively checks backward when backtrack set is revisited and executed.
-//              for (int eventNumber = currentChoice - 1; eventNumber >= end; eventNumber--) {
               for (int eventNumber = currentChoice - 1; eventNumber >= 0; eventNumber--) {
                 // Skip if this event number does not have any Read/Write set
                 if (!readWriteFieldsMap.containsKey(choices[eventNumber])) {
@@ -536,9 +731,12 @@ public class StateReducer extends ListenerAdapter {
                   // We do not record and service the same backtrack pair/point twice!
                   // If it has been serviced before, we just skip this
                   if (recordConflictPair(currentChoice, eventNumber)) {
-                    createBacktrackChoiceList(currentChoice, eventNumber);
-                    // Break if a conflict is found!
-                    break;
+                    // Lines 4-8 of the algorithm in the paper page 11 (see the heading note above)
+                    if (vm.isNewState() || isReachableInVODGraph(choices[currentChoice], choices[currentChoice-1])) {
+                      createBacktrackChoiceList(currentChoice, eventNumber);
+                      // Break if a conflict is found!
+                      break;
+                    }
                   }
                 }
               }